JavaScript

What is the difference between declaring variable with let and var

January 14, 2022

What is the difference between declaring variable with let and var

In this article you will learn the difference between declaring variable with let and var, as well as knowing when to use each of the two statements.

difference between declaring variable with let and var cover

Hey you programmer, ok? Let’s learn more about JavaScript and its ways of declaring variables!

The idea is that you should no longer use var in programs that use the most up-to-date version of the JavaScript language.

This happens because we have a scope problem using this method, which is solved with let

We can separate variables in blocks, use a variable with the same name inside and outside a function

Here’s a classic example:

let x = 12;

if(true) {
 let x = 5;
 console.log(x);
}

console.log(x);

var y = 12;

if(true) {
 var y = 5;
 console.log(y);
}

console.log(y);

The return in will be:

12
5
5
5

This is because with let we create a scope even in the ”if”, not changing our previously defined variable globally as x

The var has overwritten the value of y inside the if, which is a block element, but as it is declared with var it does not separate the scope in this statement.

So we realized that let is, above all, a good practice too, having to be opted for by new JavaScript software

Another interesting concept is that if we use a variable per var before being defined it is treated as undefined

The let returns an error, that the variable has not yet been defined.

Increasing code security, as we will only be able to use a variable if it is initialized, not returning unexpected results such as undefined

See the example:

console.log(x);
var x = 0;
console.log(y);
let y = 1;

Here we will get undefined for x and for y an error that the variable has not yet been defined

Conclusion

In this article we learned  the difference between declaring variable with let and var

I discouraged the var declaration as it has its problems, just be aware that some browsers may not support the use of let and ES6 features

For this you will have to transpile your code, making it adapt to all browsers, with Babel for example

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x