ECMAScript 2015, also known as ES6 or ECMAScript 6, is a significant update to the JavaScript language. It introduces many new features and syntactic improvements that make JavaScript programming easier, more efficient, and more powerful. This guide will provide an overview of the key features introduced in ES6, along with examples to illustrate their use.
Key Features of ECMAScript 2015
1. Block-Scoped Variables: let and const
Before ES6, JavaScript only had function-scoped variables using var. ES6 introduced let and const for block-scoping.
let allows you to declare variables that are limited to the scope of a block statement.
const allows you to declare variables that are read-only.
Example:
let x = 10;
const y = 20;
console.log(x); // 10
console.log(y); // 20
}
console.log(typeof x); // undefined
console.log(typeof y); // undefined
2. Arrow Functions
Arrow functions provide a shorter syntax for writing function expressions and lexically bind the this value.
Example:
console.log(add(2, 3)); // 5
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
3. Template Literals
Template literals allow for easier string interpolation and multi-line strings using backticks (`).
Example:
const message = `Hello, ${name}! Welcome to ECMAScript 2015.`;
console.log(message); // Hello, John! Welcome to ECMAScript 2015.
4. Default Parameters
Default parameters allow function parameters to have default values if no value or undefined is passed.
Example:
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!
5. Destructuring Assignment
Destructuring allows for the extraction of data from arrays or objects into distinct variables.
Example:
// Array Destructuring
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
// Object Destructuring
const person = { name: 'Alice', age: 25 };
const { name, age } = person;
console.log(name, age); // Alice 25
6. Enhanced Object Literals
Enhanced object literals provide a shorthand for defining properties and methods in objects.
Example:
const x = 10;
const y = 20;
const obj = {
x, // Shorthand for x: x
y, // Shorthand for y: y
add() { // Shorthand for add: function() { ... }
return this.x + this.y;
}
};
console.log(obj.add()); // 30
7. Promises
Promises provide a way to handle asynchronous operations more effectively than callbacks.
Example:
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
fetchData.then(data => {
console.log(data); // Data received (after 2 seconds)
}).catch(error => {
console.error(error);
});
8. Classes
ES6 introduces a class syntax for creating objects, which 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, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const alice = new Person('Alice', 25);
alice.greet(); // Hello, my name is Alice and I am 25 years old.
9. Modules
ES6 introduces modules, allowing for the import and export of code between files.
Example:
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
// File: main.js
import { add, PI } from './math';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159
10. The Spread and Rest Operators
The spread operator (...) allows an iterable (like an array) to be expanded, while the rest operator allows you to represent an indefinite number of elements as an array.
Example:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]
// Rest Operator
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
11. The for...of Loop
The for...of loop provides a way to iterate over iterable objects (arrays, strings, etc.).
Example:
const array = [10, 20, 30];
for (const value of array) {
console.log(value); // 10, 20, 30
}
12. New Built-in Methods
Example:
// Array.from
const set = new Set([1, 2, 3]);
const arrayFromSet = Array.from(set);
console.log(arrayFromSet); // [1, 2, 3]
// String.prototype.includes
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.includes('fox')); // true
console.log(sentence.includes('cat')); // false
13. Symbol
Example:
const sym2 = Symbol('description');
console.log(sym1 === sym2); // false
const obj = {
[sym1]: 'value1',
[sym2]: 'value2'
};
console.log(obj[sym1]); // value1
console.log(obj[sym2]); // value2
14. Generators
Generators are functions that can be paused and resumed, allowing for more powerful iteration.
Example:
function* countUp() {
let count = 0;
while (true) {
yield count++;
}
}
const counter = countUp();
console.log(counter.next().value); // 0
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
Practice Excercise Practice now