0 votes
in JavaScript by
Guess the output of the following code:

var x = 23;

(function(){

  var x = 43;

  (function random(){

    x++;

    console.log(x);

    var x = 21;

  })();

})();

1 Answer

0 votes
by
Output is NaN .

random() function has functional scope, since x is declared and hoisted in the functional scope.

Rewriting the random function will give a better idea about the output:

function random(){

  var x; // x is hoisted

  x++; // x is not a number since it is not initialized yet

  console.log(x); // Outputs NaN

  x = 21; // Initialization of x

}

Related questions

0 votes
asked Oct 10, 2022 in JavaScript by SakshiSharma
0 votes
asked Mar 24, 2021 in JavaScript by sharadyadav1986
...