/ javascript

Banish Javascript's var keyword from your vocabulary

Small one today, basically about the difference between var, let and why you shouldn't use var anymore.

In any sane programming language, you define a variable before using it, otherwise you get an error at either compile time (for compiled languages) or at runtime (for interpreted languages).

int i = 10;
System.out.println(i); // outputs 10

j = 10; // Compile Error - j is undefined
System.out.println(j);

However, JavaScript lets you do the following

'use strict'

z = 10;
console.log(z); // outputs 10
var z;
console.log(z); // also outputs 10

Conceptually this really doesn't make sense, assigning a value before it's defined, but it also could cause you errors if you forget that you have already assinged a value and are assuming a default value of undefined (for example).

z = 10;
// later in the code
var z;
if (!z) {
    z = 5; // Will never get called
}
console.log(z); // outputs 10

The let keyword is actually sane and works much like all other languages allowing you to pick up the error before releasing to production.

'use strict'

z = 10; // Runtime error - z is not defined
console.log(z);
let z;
console.log(z);

Of course this is assuming you're working with a browser capable of ES6 or transpile your code with Babel, Typescript or similar.