DEV Community

StuartCreed
StuartCreed

Posted on • Updated on

var, const and let differences in Javascript

Summary
Basically there is no reason to use var and it is considered bad practice. Only use const and let.

A good video is on this topic is: https://laracasts.com/series/es6-cliffsnotes/episodes/3?autoplay=true

Scope differences

Variables declared with var are not block scoped (although they are function scoped), while with let and const they are.

if (y>10){var A = "hello"}
A would be available outside if block

if (y>10){const B = “hello} or if (y>10){let B = “hello}
B would not be available outside if block

function Test1 () {
var C = "test"
return (C)}

function Test2 () {
const C = "test"
return (C)}

For both of the functions above C would not be available outside of the function once it has been invoked.

To reference a variable outside a block that is not a function using let:

const bool = true;
let a;
if (bool) {
a = 'foo';
}
console.log(a);

Why not to use var

var hoists the variables declaration up to the top of the function scope or class scope, causing undesired results. e.g:

function test(bool) {
if (bool) {
var a = 'foo';
console.log(a);
} else {
console.log(a);
}
}

If you run: test(true) this will result in 'foo' in the console.
If you run: test(true) this will result in 'undefined' -> which does not make sense. It should be a reference error. If you change the a in the else block to anything else it becomes a reference error. Why is this? Because js is interpreting it as the following due to the hoisting (hence why the undefined error):

function test(bool) {
var a;
if (bool) {
a = 'foo';
console.log(a);
} else {
console.log(a);
}
}

This is why to avoid var.

To quote a past dev post:
https://dev.to/johnwolfe820/should-you-never-truly-use-var-bdi

No error is thrown if you declare the same variable twice using var (conversely, both let and const will throw an error if a variable is declared twice)

const - means that the variable assignment stays constant and cannot be overwritten within the block. But note that you can still alter the value of the object. I.e. if you wrote the following this would work:

const A = ['suzy','juju','uno'];
A.push('matt');
Enter fullscreen mode Exit fullscreen mode

But the following would give an error because A is already defined:

const A = ['suzy','juju','uno'];
const A = ['suzy','juju','udsdsd'];
Enter fullscreen mode Exit fullscreen mode

let - means that the variable can be overwritten at any point within the block.

Top comments (0)