const and let keywords in ES6

Const and Let Keywords in ES6

ES6 or ECMAScript 6 is the sixth edition of the JavaScript language specification. In this version, two new keywords were introduced called "const" and "let". These keywords are used to declare variables in JavaScript.

Const Keyword:

The const keyword is used to declare a variable that cannot be reassigned once it has been declared. It is similar to declaring a variable with the "let" keyword, but with const, once a value is assigned, it cannot be changed.


// Example of using const:
const pi = 3.14159;
// pi = 3.14; // This will result in an error as pi is a constant and cannot be reassigned.

It is important to note that the const keyword only makes the binding of the variable immutable, not the value itself. This means that if a const variable holds an object, the properties of the object can still be modified.


// Example of using const with an object:
const myObj = {name: "John", age: 30};
myObj.age = 31; // This is allowed as the object is not immutable, only the binding is.

Let Keyword:

The let keyword is used to declare a variable that can be reassigned later. It is similar to the var keyword, but with let, the scope of the variable is limited to the block it is declared in.


// Example of using let:
let x = 5;
if (true) {
  let x = 10; // This creates a new variable x inside the block scope.
  console.log(x); // Output: 10
}
console.log(x); // Output: 5

It is important to note that the let keyword does not create a hoisted variable like the var keyword does. This means that if you try to access a let variable before it has been declared, it will result in an error.

Conclusion:

The const and let keywords in ES6 provide better control over variable declarations in JavaScript. The const keyword makes the binding of a variable immutable while let allows for reassignment within a limited scope. It is important to use these keywords appropriately for better code readability and maintainability.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe