Why I am getting undefined in the second output of this code?

function foo() {
console.log(“Hello”);
}
let answer = foo()
console.log(answer);

//The first output is hello but the second output is undefined, can anyone tell me why it is undefined and how to rectify it?

Hi! If you want to assign a function to a variable do it without parenthesis:

let answer = foo 
console.log(answer)

The output:

function foo() {
  console.log('Hello')
}

the function foo doesn’t have a return statement so it outputs undefined, if you want to rectify that and have a value in answer you need to have a return statement inside foo

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.