Javascript - Function Parameters and Global Scope

Introduction

If you declare a variable using let inside a function, having the same name as a parameter, ES6 will throw a load-time error.

function fn(param) { 
    let param; // SyntaxError: Identifier 'param' has already been declared 
} 

Doing the same with a var does nothing, because it re-declares a variable.

To fix this issue use a let inside a block.

The new variable declared will only shadow the parameter:

function fn(param) { 
    { 
        let param; 
    } 
} 

For the global object in JavaScript:window in browsers and global in Node.js, let declaration removed the confusion:

let notGlobal = "hello"; 
var isGlobal = "new value"; 

{ console.log(notGlobal); } // hello 
{ console.log(isGlobal); } // new value 

global.isGlobal //'new value' 
global.notGlobal // undefined 

All properties of the global objects are global variables.

In the global scope var declarations and function declarations create such properties.

But global variables created using let and const declarations will not be properties of the global object.

Related Topic