Variable in JavaScript has value without specifying it

In JavaScript for certain variable names, a quite confusing situation can happen due to the various scopes present in the language. Let’s start off with some examples where we see the expected outcome and reach some interesting points from there. We have placed all the example code at the root of a JS file (so it is not inside any block).

var firstName = 'John';
var lastName;
console.log(firstName);
console.log(lastName);

The output of this is not surprisingly the following.

John
undefined

The first one contains a string we have specified and the second one prints undefined as we have not specified any value.

What if I declare a variable called “name”, but don’t assign a value to it?

var name;
console.log(name);

Surprisingly, it will contain an empty string. We’ll see why at the end, but until that let’s see another example.

What happens if I assign “John Doe” to the variable, and rerun my program?

var name = 'John doe';
console.log(name);

It will, of course, print “John Doe”. Nothing surprising. But what if I update the code to the following and refresh the page?

var name;
console.log(name);

This is what we see after the refresh:

John Doe

Wow! Our variable has the value we have previously set, although it’s not even in our code anymore.

Explanation

The first surprising outcome happened because the window object has a property called “name”, which contained an empty string. This is what is returned because we were using the “name” variable from the global scope. So what is the window object exactly?

The window object is supported by all browsers. It represents the browser’s window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object.

So, even before one line of our code executed, the “name” global variable already had an empty string as value. That is what we got back.

The other weird outcome is also because of the window object’s “name” property. This property is persisted between page refreshes and it is only cleared when the browser window is closed. This is why it still contained the value we have removed.

The conclusion we can draw here is that besides the JavaScript keywords (e.g. delete, var) that you cannot use for variable names, there are some other names that should not be used because of their unexpected side effects.

Of course, using global variables is not a good idea 99% of the time. But this won’t stop anyone from using them. They are especially common for practice code when we just quickly trying out something, and this is a good opportunity for beginners to have some headaches due to the above issue. So guys, be careful with your variable naming!