Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override variable in javascript function

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();
like image 751
elevenMinutes Avatar asked Dec 28 '25 10:12

elevenMinutes


1 Answers

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();
like image 71
xdazz Avatar answered Dec 30 '25 22:12

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!