Wednesday, August 29, 2018

Some Features of Functions and Closures in JavaScript

Although JavaScript is an 0bject-orientic language, it is not the same as other OOP language like Java in some aspects. Hence, understanding the underlying principles of JavaScript is crucial for a web developer. Today we will go through some of the traps that functions and closures can pose, with pieces of example code.

function testVar(){
    var x = 5;
    console.log('first x is '+ x);//expected output 5
    if (x == 5){
        var x = 6;
        console.log('second x is '+ x);// expected output 6
    }
    console.log('third x is '+ x);// expected output 6
}

testVar();

In this function, x was declared as 5 at the very beginning so there is no doubt that it would be output as 5 in line 3. In the condition statement, x is replaced with 6 becasue it meet the condition hence the second x is 6. Again, line 8 will output 6 because x has already been changed when it runs outside of the statement. Now let's inspect the second example.



from DZone.com Feed https://ift.tt/2LCWR4W

No comments:

Post a Comment