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();

2 Answers 2

8

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();
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.