Introduction to ES6
ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language. ECMAScript is the standardization of Javascript which was released in 2015 and subsequently renamed as ECMAScript 2015.
New Features in ES6
1. The let Keyword
The let variables are mutable i.e. their values can be changed. It works similar to the var keyword with some key differences like scoping which makes it a better option when compared to var.
let n = 10;
{
let n = 2; // Block-scoped variable
console.log(n);
}
console.log(n);
Output
2 10
It prevents variable leakage outside of the intended scope.
2. The const Keyword
const is used to declare variables with a constant value, ensuring the value cannot be reassigned.
const PI = 3.14159;
PI = 3; // Error: Assignment to constant variable
Ideal for declaring configuration constants or fixed values.
3. Arrow Functions
Arrow functions provide a concise syntax for writing function expressions and automatically bind this to the surrounding context.
// Traditional function
function add(a, b) { return a + b; }
// Arrow function
const add = (a, b) => a + b;
- Implicit return for single-expression functions.
- Do not have their own 'this' context.
4. Destructuring Assignment
Destructing in JavaScript basically means the breaking down of a complex structure(Objects or arrays) into simpler parts
Object Destructuring
const obj = {
name : "Raj",
age : 25
};
const {name, age} = obj;
console.log(name, age);
Output
Raj 25
Array Destructuring
const a = [ "red", "blue", "green" ];
const [first, second] = a;
console.log(first, second);
Output
red blue
5. The Spread (...) Operator
The spread operator expands an array or object into individual elements or properties.
const n1 = [ 1, 2, 3 ];
const n2 = [...n1, 4, 5 ];
console.log(n2);
Output
[ 1, 2, 3, 4, 5 ]
6. The For/Of Loop
The for/of loop allows you to iterate over iterable objects like arrays, strings, Maps, and Sets but in a short syntax as compared to other loops.
Iterating Over an Array
const a = [ "apple", "banana", "cherry" ];
for (const fruit of a) {
console.log(fruit);
}
Output
apple banana cherry
Iterating Over a String
const s = "hello";
for (const char of s) {
console.log(char);
}
Output
h e l l o
7. Maps and Sets
Map: Maps store key-value pairs where keys can be any data type.
const map = new Map();
map.set("a", 1);
map.set("b", 2);
console.log(map.get("a"));
Output
1
Set: Sets store unique values of any type.
const set = new Set([ 1, 2, 3, 3 ]);
console.log(set);
Output
Set(3) { 1, 2, 3 }
8. Classes
ES6 introduced classes in JavaScript. Classes in javascript can be used to create new Objects with the help of a constructor, each class can only have one constructor inside it.
class Animal {
speak() { console.log("The animal makes a sound"); }
}
const dog = new Animal();
dog.speak();
Output
The animal makes a sound
- class Animal {}: Defines a simple class named Animal.
- speak(): A method inside the class that logs a message to the console.
- new Animal(): Creates an object dog from the Animal class.
- dog.speak(): Calls the speak method on the dog object.
9. Promises
Promises simplify handling asynchronous operations by providing .then and .catch methods.
const fetch = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 2000);
});
};
fetch().then(data => console.log(data));
10. Default Parameters
Allows functions to have default values for parameters.
function greet(name = "Guest") { return `Hello, ${name}!`; }
console.log(greet());
Output
Hello, Guest!
Additional Enhancements
- String Methods:
- includes(): Check if a string contains a substring.
- startsWith(): Check if a string starts with a substring.
- endsWith(): Check if a string ends with a substring.
- Array Methods:
- find(): Locate the first element matching a condition.
- findIndex(): Locate the index of the first element matching a condition.
- from(): Convert an iterable or array-like object into an array.
- Template Literals: Simplify string concatenation and allow embedded expressions.
- Modules: Introduce import and export for better modularity.
- Rest Parameters (...args): Allow functions to accept an indefinite number of arguments as an array.
- Generators and Iterators: Enable custom iteration logic with function* and yield.
- Binary and Octal Literals: Simplify working with binary (0b) and octal (0o) numbers.
- Enhanced Object Literals: Provide shorthand for methods, properties, and dynamic keys.
- WeakMap and WeakSet: Store weakly-referenced objects for specialized use cases.
- Proxy and Reflect: Add interception capabilities and reflection utilities for objects.
- Symbol: Introduces unique, immutable primitive data types useful for property keys.
- Block-scoped Functions: Functions declared inside blocks respect block scope.
Browser Support for ES6 (2015)
ES6 is fully supported in all modern browsers since June 2017:
Chrome | Edge | Firefox | Safari | Opera |
May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |
Note: ES6 is not supported in Internet Explorer.