Home >Web Front-end >JS Tutorial >Mastering ESeatures: let, const, and Classes in JavaScript
ECMAScript 2015 (ES6) introduced many powerful features that revolutionized JavaScript development. Among them, let, const, and classes are crucial for writing modern, clean, and efficient code.
The let keyword is used to declare variables with block scope. Unlike var, let does not allow redeclaration within the same scope and is not hoisted in the same way.
let variableName = value;
let x = 10; if (true) { let x = 20; // Block scope console.log(x); // 20 } console.log(x); // 10
The const keyword is used to declare constants. Like let, it is block-scoped but differs in that it cannot be reassigned after declaration.
const variableName = value;
const PI = 3.14159; console.log(PI); // 3.14159 // PI = 3.14; // Error: Assignment to constant variable const numbers = [1, 2, 3]; numbers.push(4); // Allowed console.log(numbers); // [1, 2, 3, 4]
Feature | let | const | var |
---|---|---|---|
Scope | Block | Block | Function |
Hoisting | No | No | Yes |
Redeclaration | Not Allowed | Not Allowed | Allowed |
Reassignment | Allowed | Not Allowed | Allowed |
ES6 introduced class syntax as a cleaner and more intuitive way to create objects and handle inheritance compared to traditional prototypes.
let variableName = value;
let x = 10; if (true) { let x = 20; // Block scope console.log(x); // 20 } console.log(x); // 10
const variableName = value;
const PI = 3.14159; console.log(PI); // 3.14159 // PI = 3.14; // Error: Assignment to constant variable const numbers = [1, 2, 3]; numbers.push(4); // Allowed console.log(numbers); // [1, 2, 3, 4]
class ClassName { constructor(parameters) { // Initialization code } methodName() { // Method code } }
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } const person1 = new Person('Alice', 25); person1.greet(); // Hello, my name is Alice and I am 25 years old.
constructor(name) { this.name = name; }
greet() { console.log("Hello"); }
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of Mastering ESeatures: let, const, and Classes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!