Skip to content
the poor coder

const and let keywords in ES6

Poor Man
Published
Reading time
2 min read
On this page

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.

Text

// 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.

Text

// 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.

Text

// 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC