1

I have the below block of code which in the console print "undefine" twice after "Hello"

JavaScript Code

function f()
{
     function g() {
        console.log("Hello");
    }
    return g;
}

var x = f()();
console.log(x);

While I am trying to print only "Hello", where is the two undefined printing from

Output in console

 Hello
 undefined
 undefined
ningomba 2.0
  • 253
  • 1
  • 2
  • 11
  • 2
    What is your question? The first `undefined` appears, because `g` doesn’t return anything, the second one because `console.log` doesn’t return anything. – Sebastian Simon Oct 21 '17 at 17:46

1 Answers1

1

The first undefined is because f()() evaluates to whatever g returns, and g doesn't return anything. You store that undefined in x, then print it when you write console.log(x);.

I'm guessing the second undefined is the result of running this in a console. The last line containing console.log evaluates to undefined, which may be implicitly printed from the console/REPL. You can confirm this by adding something like the string "World" as the last line of the script. Adding anything else to the last line should get rid of the second undefined.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • Thanks for your answer, but if I remove x and change it to console.log(f()()), it would print the same. Interestingly undefined is printed twice in chrome console, if I execute in node it prints only once. – ningomba 2.0 Oct 21 '17 at 17:57
  • 1
    @ningomba2.0 That code you changed it to is the same as your old code, just without the intermediate `x` variable. I'll modify the wording in my answer. Basically, `f()()` returns undefined since `g` doesn't return anything. In your first bit of code, you stored that undefined in x. In your new code, you give that undefined straight to `console.log`. Here's a question: in your first code, what do you expect `x` to hold? – Carcigenicate Oct 21 '17 at 18:00
  • @ningomba2.0 `f()()` is `undefined`, since `g` doesn't return anything. – 4castle Oct 21 '17 at 18:00
  • @Carcigenicate, Thank you very much, I got your point, I was using x to check the difference between the two, one by assigning the result of f()() and printing x and the other by directly printing f()(). – ningomba 2.0 Oct 21 '17 at 18:20