Questioning the function of "let" when declaring a variable

As you have discovered it is not necessary to declare variables with let before using them. As @GoToLoop pointed out you can change this by activating ‘strict mode’, so the question you might ask is why bother with strict mode or let declarations.

If you are learning JS then the answer is not obvious and many examples found on the web don’t bother, giving the impression it doesn’t matter, but there are reasons to do so. One of the most important is that it controls the ‘scope’ of the variable, the scope defines the parts of your code that can see and use the variable.

Your code runs inside a web browser which maintains its own variables, constants, functions etc. and these are visible to and usable by your entire code. JS provides the globalThis property so you can access or modify (not recommended) the global state.

Since the global state is shared by all scripts running in the browser then it is important that your script does not try to share variables with other scripts. This means do not create global state variables in you code.

Try the following code

var aaa = 1;
let bbb = 2;
ccc = 3;

console.log(aaa, bbb, ccc);
console.log('aaa', globalThis.hasOwnProperty('aaa'));
console.log('bbb', globalThis.hasOwnProperty('bbb'));
console.log('ccc', globalThis.hasOwnProperty('ccc')); 

and you will get the following results

1 2 3 
aaa true
bbb false
ccc true

Notice that only the variable declared with let did not hoist itself onto the global state :+1::grin:

For your information let came with ES6 and is generally used and is a better alternative to the older var declaration.

My answer just scratches the surface of the topic but it is generally considered good practice to declare variables before using them. There are other benefits but I think I have gone far enough to wet your appetite.

1 Like