Search code examples
javascriptvariableswebscopejavascript-scope

Can we access a variable declared using 'var' keyword inside a block?


A variable is declared using 'var' keyword inside a block ( {...} ). Can we access that variable outside the block? I searched on several websites and the answer was 'yes'. 'Yes we can access the variable' it said. But when I executed this on a browser console it said "the variable is not defined". Any thoughts why this is so?

Here's the screenshot of the same

1

I expected it to give 12345.


Solution

  • A variable is declared using 'var' keyword inside a block ( {...} ). Can we access that variable outside the block? I searched on several websites and the answer was 'yes'.

    tldr; It's more precise to say Yes, unless that block is a function body.


    var scopes a variable to the nearest function.

    The body of the function (excepting some arrow functions) is a block.

    Not all blocks are associated with functions.

    {
        var inBlock = 1;
    }
    
    console.log(inBlock); // This logs 1
    
    function aFunction() {
        var inFunction = 2;
    }
    
    aFunction();
    
    console.log(inFunction); // This triggers a reference error