DEV Community

Cover image for VAR ... the Almighty Yet Obsolete
Caf RF
Caf RF

Posted on

VAR ... the Almighty Yet Obsolete

A few days ago I read an article that caught my attention, it talked about var. I’ll briefly explain about it.

Currently to declare a variable in JS we use let, const and to a lesser extent var. But var existed before let and const, in fact ‘var’ was the only type of variables within JS.

So why don't we currently use var?

While var has been around since the beginning of JS, it hasn't changed much since then, however JS has. In fact it has changed so much that now var could cause us problems.

The reason?

Var ignores code blocks and this is because a long time ago Javascript did not have lexical environments, it can be declared again and in the same way var is always processed at the beginning of a function.

Let's first review the first case. When we use var inside an 'if statement' or inside a 'loop', we can access var outside the block (which does not happen with let or const).

if (true) {
     var testVar = true;
     let testLet = false;
}

console.log(testVar); // true
console.log(testLet); // Reference error testLet not defined
Enter fullscreen mode Exit fullscreen mode

The second case is very simple, var can be declared over and over again, unlike let or const, which would give us an error mentioning that the variable has already been declared.

var testVar = 0;
var testVar = 'new value';
console.log(testVar); // new value

let testLet = 'value';
let testLet = 'no new value'; // SyntaxError 'testLet' has already been declared;

Enter fullscreen mode Exit fullscreen mode

The third case, in functions, is my favorite. Var can be declared below where they are used.

function test() {
    testVar = 'some value';
    console.log(testVar); // some value
    var testVar;
}

console.log(testVar);  // undefined
Enter fullscreen mode Exit fullscreen mode

To avoid this strange behavior, programmers invented IIFE (immediately invoked function expressions).

(function() {
  // some code
})();

(function() {
  // some code
}());

!function() {
  // some code
}();

+function() {
  // some code
}();
Enter fullscreen mode Exit fullscreen mode

They are NOT currently used, DO NOT CODE IT but it is very nice to know a little history about something you are passionate about. By the way, you can see the article about var and all JS stuff here.

Top comments (0)