Declare Before Use

Learn the importance of declaring a variable before using it to avoid errors.

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:

Press + to interact
//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 ...