'var' vs 'let' in JavaScript. Which should you use?

'var' vs 'let' in JavaScript. Which should you use?

In JavaScript, the 'var' and 'let' keywords are used to declare variables. However, are we to use both keywords interchangeably without much thought? I will answer this question in this post.

To create a variable using the 'var' keyword, we have: var fruit = orange

To create a variable using the 'let' keyword, we have: let car = Ferrari

The keywords are used to create variables in a similar way but each has a purpose and this is because of a concept known as Scoping.

A scope is an area in a source code where an entity or item (like a variable or function) which is bound to an identifier is recognized. There is the global scope and the local scope.

The Global scope occurs when a variable is declared outside of a function. The variable is stored in a memory location that makes it available from the moment it is declared till the program ends. It can be used by all functions within the source code. Global scope variables are usually placed close to the top or almost at the beginning of programs.

The Local scope occurs when a variable is declared within a function. The variable is stored in a memory location that makes it available from the moment it is declared till the function completes its task. Local variables are usually placed close to function definitions.

Now that we understand scoping, let us move on to why the 'var' and 'let' keywords are similar yet used differently.

The 'var' keyword is used to declare variables with global scope while the 'let' keyword is used to declare variables with local scope.

To make your source code lighter, it is better to use the 'let' keyword. When a variable is created using the let keyword, a space is allocated to it in memory. Once the function the local scope variable was created for no longer exists, the memory space it occupied is then made available for another local scope variable to be declared. This is a good practice.

Now you know when to use either 'var' or 'let' to create variables.

I hope this was helpful

Please like, share and leave a comment for feedback. Thank you!