DEV Community

Winson
Winson

Posted on

Var or Let?

Let is very similar to var but there are some key differences between the two. For those of you who are still struggling understanding var and let then this article will provide a quick summary of the differences between the two.

Var uses a function scope and has what’s called hoisting. Hoisting allows variable to be available on a broader scope beyond where they are declared but this increases the chance of having an error in your code. If you have another variable with the same name then things can be confusing which is why using less and having a smaller scope is a nice solution to this.

Alt text of image

In this example you can see the hoisting process where the declaration at the top and the variable are being called throughout the whole scope. Problem with this is that i is declared twice which messes up the code.

Let has what’s called a block scope which is only declared inside of the curly braces. This means the declared variable are limited in the scope unlike var where the variable is defined globally regardless of block scope. This is good for limiting any errors that might occur if you declared it outside the block scope.

Alt text of image
Alt text of image

As you can see in this example we try to console log the variable i it gives an error message because it's outside the block scope.

Alt text of image
Alt text of image

Now when we do the same thing but replace let with var we get a number for i which is 100. Now even though this works it can get confusing if someone else was editing the code and used the variable i later down the line.

Remember even though you can access variables on a global scale using var, it's best to limit the scope using let to reduce the number of errors you could face.

Top comments (0)