Introduction:
ES6, also known as ECMAScript 2015, is a major update to the JavaScript language that was released in 2015. It introduced a number of new features and improvements over previous versions of JavaScript. In this article, we will explore some of the key features of ES6.
The let keyword is used for variables that can be reassigned, while the const keyword is used for variables that cannot be reassigned. This helps to prevent accidental overwriting of variables and makes code more readable.
Example:
let x = 10; // x can be reassigned
const y = 20; // y cannot be reassigned
Arrow functions also have a lexical this binding, which means that they inherit the this value from the surrounding code. This makes it easier to use them in object-oriented programming.
Example:
// ES5 Function
var sum = function(a, b) {
return a + b;
}
// ES6 Arrow Function
const sum = (a, b) => a + b;
Template literals are enclosed in backticks (`) instead of single or double quotes. Variables or expressions can be enclosed in ${} brackets within the template literal.
Example:
const name = 'John';
const age = 30;
// ES5 String Concatenation
var message = 'My name is ' + name + ' and I am ' + age + ' years old.';
// ES6 Template Literal
const message = `My name is ${name} and I am ${age} years old.`;
Classes can define properties and methods, which can be inherited by subclasses using the extends keyword. Classes can also define constructors, which are used to initialize object instances.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old. My major is ${this.major}.`);
}
}
const john = new Student('John', 20, 'Computer Science');
john.sayHello();
// Output: "Hello, my name is John and I am 20 years old. My major is Computer Science."
function Person(name, age) { this.name = name; this.age = age; }
Person.prototype.sayName = function() { console.log(this.name); }
ES6: class Person { constructor(name, age) { this.name = name; this.age = age; }
sayName() { console.log(this.name); } }
ES5: function greet(name) { name = name || “World”; console.log(“Hello, ” + name + “!”); }
greet(); // Output: Hello, World! greet(“John”); // Output: Hello, John!
ES6: function greet(name = “World”) { console.log(Hello, ${name}!
); }
greet(); // Output: Hello, World! greet(“John”); // Output: Hello, John!