Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log [duplicate]

What's happening here? I get a different result if I declare a variable after console.log in the inner function

I understand that var has a functional scope and inner function can access the variable from their parent

function outer() {
  var a = 2;

  function inner() {
    a++;
    console.log(a) //log NaN
    var a = 8
  }
  inner()
}
outer()

function outer() {
  var a = 2;

  function inner() {
    a++;
    console.log(a) //log 3
    var b = 8
  }
  inner()
}
outer()

The log returns NaN in the first example and log 3 in the second example

like image 489
Claude Avatar asked Mar 30 '19 05:03

Claude


People also ask

Why does my function return NaN?

NaN , which stands for "Not a Number", is a value that JavaScript returns from certain functions and operations when the result should be a number, but the result is not defined or not representable as a number. For example: parseInt() returns NaN if parsing failed: parseInt('bad', 10) Math.

Why do I keep getting NaN JavaScript?

Nan means “Not a number”, this is because inside your cube function, you're not calling the square function, but getting it's contents. Change return x * square; with return x * square(x); and it should work.

How does JavaScript handle NaN?

In JavaScript NaN is short for "Not-a-Number". The isNaN() method returns true if a value is NaN. The isNaN() method converts the value to a number before testing it.

What is type of NaN in JavaScript?

In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Number. isNaN() method returns true if the value is NaN , and the type is a Number.


2 Answers

This is due to hoisting

The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined

undefined++ returns NaN, hence your result.

Your code is equivalent to:

function outer() {
    var a=2;

    function inner() {
        var a;
        a++;
        console.log(a); //log NaN
        a = 8;
    }

    inner();
}

outer();

Rewriting your code in this way makes it easy to see what's going on.

like image 163
jro Avatar answered Oct 10 '22 04:10

jro


Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:

function outer() {
  var a = 2;

  function inner() {
    a++;
    console.log(a);
  }
  inner();
}
outer();
like image 37
Jack Bashford Avatar answered Oct 10 '22 05:10

Jack Bashford