ES6 (ECMAScript 2015) introduced modern features in JavaScript, making code cleaner, shorter, and more readable. Key features include let, const, template literals, arrow functions, and more.
This blog explains these features with examples.
⭐ 1. let and const
let
let is used to declare block-scoped variables. Unlike var, it cannot be accessed outside its block.
let name = "Sagar";
if(true){
let name = "Sidana";
console.log(name); // Sidana
}
console.log(name); // Sagar
const
const is used to declare constants. Its value cannot be reassigned.
const PI = 3.14;
console.log(PI); // 3.14
// PI = 3.1415; // Error
⭐ 2. Template Literals
Template literals use backticks (`) for multiline strings and variable interpolation.
let name = "Sagar";
let age = 22;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);
⭐ 3. Arrow Functions
Arrow functions provide a shorter syntax for writing functions.
// Traditional function
function sum(a, b){
return a + b;
}
// Arrow function
const sumArrow = (a, b) => a + b;
console.log(sumArrow(5, 3)); // 8
Arrow functions also do not have their own this, which is useful in certain contexts.
⭐ 4. Default Parameters
You can assign default values to function parameters.
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
greet("Sagar"); // Hello, Sagar
⭐ 5. Destructuring
Destructuring allows you to extract values from arrays or objects easily.
// Array destructuring
let arr = [1, 2, 3];
let [a, b, c] = arr;
console.log(a, b, c); // 1 2 3
// Object destructuring
let user = {name: "Sagar", age: 22};
let {name, age} = user;
console.log(name, age); // Sagar 22
⭐ 6. Spread Operator
The spread operator (...) expands arrays or objects.
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4]
⭐ Conclusion
ES6 features like let, const, template literals, arrow functions, destructuring, and spread operator make JavaScript modern and concise. Mastering these features is essential for writing clean and efficient code.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/