ECMAScript(ES6) features
What is ECMAScript?
ECMAScript (often abbreviated as ES) is a scripting language specification standardized by ECMA International, a European standards organization. It provides the rules, guidelines, and standards that define how scripting languages like JavaScript (the most widely known ECMAScript implementation) should work.
ECMAScript 6 (ES6), also known as ECMAScript 2015, introduced several powerful features to JavaScript, making the language more efficient, modern, and easier to write.
1. Let and Const
ES6 introduced let
and const
for better variable scoping than the traditional var
.
let
: Block-scoped, meaning it is only available within the block in which it is declared.const
: Block-scoped, but also prevents reassignment after initialization.
Example:
let x = 10;
const y = 20;
// x can be reassigned, y cannot
2. Arrow Functions
Arrow functions provide a shorter syntax for function expressions and do not bind their own this
context, making them especially useful in callback functions.
Example:
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
3. Template Literals
Template literals use backticks (`
) and allow for string interpolation, making it easy to embed expressions and variables in strings.
Example:
let name = "Sam";
let message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Sam!
4. Default Parameters
You can assign default values to function parameters in case no argument or undefined
is passed.
Example:
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Output: Hello, Guest
5. Destructuring
Destructuring allows extracting values from arrays or objects into distinct variables in a clean and easy way.
Array Destructuring:
let [a, b] = [1, 2];
console.log(a); // Output: 1
console.log(b); // Output: 2
Object Destructuring:
let person = { name: "John", age: 30 };
let { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30
6. Rest and Spread Operators (...
)
Spread Operator: Expands elements of an array or object.
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
console.log(newArr); // Output: [1, 2, 3, 4, 5]
Rest Operator: Collects all remaining elements into an array.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
7. Classes
ES6 introduced a class syntax that is syntactic sugar over JavaScript's existing prototype-based inheritance.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, I am ${this.name}`);
}
}
let john = new Person("John", 30);
john.greet(); // Output: Hello, I am John
8. Modules
ES6 introduced native support for JavaScript modules, allowing you to export and import functions, objects, or primitives between files.
Export:
// In math.js
export const add = (a, b) => a + b;
Import:
// In main.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5
9. Promises
Promises provide a cleaner way to handle asynchronous operations, replacing older callbacks.
Example:
let fetchData = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data fetched successfully");
} else {
reject("Error fetching data");
}
});
fetchData
.then(data => console.log(data))
.catch(error => console.log(error));
10. Enhanced Object Literals
ES6 allows shorter syntax for object properties and methods, especially useful when the property name matches the variable name.
Example:
let name = "Sam";
let person = {
name,
greet() {
console.log(`Hello, ${this.name}`);
}
};
person.greet(); // Output: Hello, Sam
11. Map
and Set
ES6 introduced new data structures:
Map
: A collection of key-value pairs.Set
: A collection of unique values.
Example:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // Output: value1
let set = new Set([1, 2, 2, 3]);
console.log(set); // Output: Set { 1, 2, 3 }