javascript – What's the difference between global variable declarations with and without var?

Question:

Let's say we have a code:

// вне всяких блоков и функций
var a1 = 'Something';
a2 = 'Something';

1) What will be the difference between variables a1 and a2 ?
2) Is a2 a variable at all?
3) Is it possible to use the second option somewhere?

Answer:

What will be the difference between variables a1 and a2?

In strict mode, the option without var will be broken:

'use strict';

var a1 = 'Something';
a2 = 'Something'; // Uncaught ReferenceError: a2 is not defined

Is a2 a variable at all?

Of course, what else?

Is it possible to use the second option somewhere?

This is everyone's business, but it makes little sense.
It's much better to explicitly designate the global object (aka window.a2 = 42; ).
Better yet, don't pollute the global scope at all.

Scroll to Top