Variables in JavaScript has always been a leaky concept. We all know global variables are evil, but “hoisted” variables within a certain scope can lead to unexpected bugs that are hard to track down. Take the following example:
function whatsMyName() { if (true) { var name = 'Basem'; } alert(name); // Basem }
In other languages, the “name” variable is scoped within the if-statement only. Not true in JavaScript! Any variable created inside a function is pinned to the top of the function, no matter where you declare it. This behavior is known as “hoisting”.
The example above can be better understood like this:
function whatsMyName() { var name; // Variable hoisted to the top if (true) { name = 'Basem'; } alert(name); // Basem }
Now, let there be proper scoping in JavaScript! Introducing the new “let” keyword.
function whatsMyName() { if (true) { let name = 'Basem'; } alert(name); // Error: Name is undefined }
Another way to see this is the following:
function whatsMyName() { var name = 'John'; if (true) { let name = 'Basem'; alert(name); // Basem } alert(name); // John }
The “let” keyword is block-scoped, while “var” continues to be function-scoped. Let the refactoring begin!
Happy Coding!!
Leave a Reply