coding
HighlightsProgramming

JavaScript Variables “let” keyword, should we use it (or omit it)?

JavaScript Variables

JavaScript variables are containers that store values or data, such as numbers, strings, and boolean values, that can be referenced and manipulated throughout a program. They are an essential component of JavaScript programming and provide flexibility and control in coding.

It is easy to assign or declare variables on Javascript and there are few ways to do that. You may use var or let keyword to declare a variable. For example, var x = 1; or let x = 1;. Both will return the same results.

If you do not want the values to be changed, you can use the const keyword to declare a javascript variable. You can also declare a variable without using any keyword. Here are some more examples below.

let a = 5;
var b = 5;
const c = 5;
d = 5;

console.log(a); //prints 5
console.log(b); //prints 5
console.log(c); //prints 5
console.log(d); //prints 5

c = 4; //returns Uncaught TypeError: Assignment to constant variable.

If you try to change the value for c, it will return an error, Uncaught TypeError: Assignment to constant variable. Both let and var keyword behaves the same, you can assign another values for both variables without any issues.

According to the documentation

The var keyword is used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

If you want your code to run in older browsers, you must use var.

When to use keyword and when not to use it, what are the differences?

In this example below, we will assign a value for both ‘x’ and ‘y’ variable. One with the ‘let’ keyword and the other without using any keyword. You may replace ‘let’ with ‘var’ but both will return the same results.

let x = 1;
y = 1;

// Execute a function
(function() {
   let x = 5; //a new 'x' variable is created in this function's scope
   y = 100; //overwrites the global scope 'y'
   console.log(x); //prints 5
   console.log(y); //prints 100
})();

console.log(x); //prints 1
console.log(y); //prints 100
javascript variables

let x = 1; defines x as a variable within the current scope (execution context). A local variable is declared if the declaration appears within a function; if it is declared globally, a global variable is declared.

On the other hand, y = 1 is just a property assignment. The scope chain is initially tested to resolve y. If it locates it anywhere along that scope chain, it executes the assignment; if it is unable to locate y, it only then constructs a property for y on a global object (which is a top level object in a scope chain).

The “constant” Keyword

“If you want a general rule: always declare variables with const.” Using const keyword will make sure that no developers can change the values for that variable. This is useful when you want to assign a variable where the value is fixed for example the value of pi “const pi = 3.14