(A major leap in JavaScript with cleaner syntax, better scoping, arrow functions, and more)
ES6 (ECMAScript 2015) is a major update to JavaScript that introduced new syntax and features to make code more readable, maintainable, and powerful.
let name = "John";
name = "Doe"; // Allowedconst age = 30;
// age = 31; // ❌ Error: Assignment to constant variablelet and const are block-scoped and don't hoist like var.
// Traditional function
function greet(name) {
return "Hello " + name;
}
// Arrow function
const greet = name => "Hello " + name;If there are multiple lines or parameters:
const add = (a, b) => {
return a + b;
};const name = "Alice";
console.log(`Hello, ${name}!`); // Hello, Alice!You can also write multi-line strings:
const msg = `This is
a multiline
string`;function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guestconst [a, b] = [1, 2];
console.log(a); // 1const user = { name: "Sam", age: 25 };
const { name, age } = user;const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}const name = "Bob";
const user = {
name,
greet() {
console.log("Hi " + this.name);
}
};const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}Use for...of with arrays, not objects.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded"), 1000);
});
};export const add = (a, b) => a + b;import { add } from './math.js';
console.log(add(2, 3));Requires setting type="module" in your HTML script tag or using a bundler.
let, const), cleaner syntax (arrow functions, template literals), and more.sum(...args) function using the rest operator.