2

Firstly I want to say that I was searching some information about scope variables in javascript (e.g What is the scope of variables in JavaScript?) and I was trying to understand why my code behaves like that but finally I really don't know. I can't override var a in my function in function, I can do this only using a = 6; without var. Why a is undefined before if statement and overriding this variable ? Why there is no result like this:

5

equal 5
equal 6

I have something like this instead:

undefined

not equal 5
equal 6

Here's my code:

    var a = 5;

function something(){
    console.log(a);
    if(a == 5){
        console.log('equal 5')
    }
    else{
        console.log('not equal 5');
    }    
   var a = 6;
    
    function test(){
        if(a == 6){
        console.log('equal 6');
    }
    else{
        console.log('not equal 6')
    }
    }    
    test();    
}
something();
Community
  • 1
  • 1
elevenMinutes
  • 171
  • 1
  • 4
  • 12

2 Answers2

7

This is because javascript variable hoisting.

Your code is equal to:

var a = 5;

function something(){
    var a;  // here
    console.log(a); // a is the local variable which is undefined
    if(a == 5){
        console.log('equal 5')
    }
    else{
        console.log('not equal 5'); // a is undefined so not equal 5
    }    

    a = 6; // a is assigned to 6

    function test(){
        if(a == 6){
            console.log('equal 6');  // a is 6 here
        }
        else{
            console.log('not equal 6')
        }
    }    
    test();    
}
something();
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Because when you declare var a = 6 the second time you are overriding the first declaration of a, i.e. var a = 5. So when you define the function something(), a has not yet been defined, hence console.log(a) returns undefined.

However when you replace the second declaration of a with just a = 6 the first declaration remains valid, you just change the value of a afterwards and so you get the expected result:

5 
equal 5
equal 6 

See this post for more discussion.

Community
  • 1
  • 1
cerpintaxt
  • 256
  • 1
  • 2
  • 13