Search⌘ K
AI Features

Declare Before Use

Understand the risks of using undeclared variables in JavaScript and how it leads to unintended globals that cause bugs. Discover how declaring variables with let or const can prevent these issues and ensure your code runs as expected. This lesson helps you write safer, more maintainable code by avoiding common pitfalls related to variable scope and declaration.

Using a variable without declaring it

At first sight, JavaScript may seem highly flexible, but things can get tricky if you’re not careful.

Example

Let’s look at the following code as an example:

Javascript (babel-node)
//Broken code
const oops = function() {
haha = 2;
console.log(haha);
};
oops();
console.log(haha);

Explanation

  • The function oops() assigns a value to a variable haha and then prints it.

  • As expected, calling oops() prints the value 2 to the console, but this function isn’t as benign as it looks.

  • JavaScript looks at line 3 and says, “Hey, look, the developer didn’t explicitly declare the variable before use. What can I do to cause the most damage? Let me make it ...