Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block Scoped Function ECMAScript 6 Strange Behaviour

I was reading the new features in ECMA6. One of the new features is Block Scoped Functions . That means we can have a same name for functions in different blocks. As in the code below block1 foo() logs 1 then similarly block2 foo() logs 2 and block0 foo() or global scope logs 4. And that is the expected result. But what i can't understand is that Why does the last console.log(foo()) logs 1 and not 4 because it is under block0 or global scope instead it logs 1 which is block1 foo().

//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
		//block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//should log 4 but logs 1 why?

Now again if I enclose the above code into a another block it works as expected. This is a bit confusing to me. What actually is causing this behviour?

{//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
		//block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//will log 4 but 
}
like image 223
Manish Avatar asked Nov 24 '25 11:11

Manish


1 Answers

You need to ensure strict mode is enabled. Since it is enabled in modules by default, I guess your sample code doesn't show that. Kangax's compatibility table shows an appropriate test.

"use strict";
//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
		//block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//logs 4
like image 114
CodingIntrigue Avatar answered Nov 26 '25 23:11

CodingIntrigue



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!