Main ES6 features:
// ES6 examples:
const name = `Hello, ${user}`; // Template string
const add = (a, b) => a + b; // Arrow function
const {id, title} = obj; // DestructuringES6 (ES2015) — like a new car upgrade: everything works the same, but much more convenient! 🚗✨
Before we had only [var], now we have better options:
// ❌ Problems with var
var name = 'John';
var name = 'Peter'; // Can redefine! 😱
// ✅ Better with let/const
let age = 25; // Can change
age = 26; // ✅
const name = 'John'; // Can't change
// name = 'Peter'; // ❌ Error!Arrow functions — like quick commands that execute immediately:
// Regular function
function add(a, b) {
return a + b;
}
// Arrow — shorter!
const add = (a, b) => a + b;
// Even shorter for one parameter
const square = x => x * x;Template strings — like a magnetic board where you can attach any values:
const name = 'John';
const age = 25;
// ❌ Old way
const greeting = 'Hello, ' + name + '. You are ' + age + ' years old.';
// ✅ New way
const greeting = `Hello, ${name}. You are ${age} years old.`;Destructuring — like sorting things: take what you need right away:
const user = {name: 'John', age: 25, city: 'Moscow'};
// ❌ Old way
const name = user.name;
const age = user.age;
// ✅ New way
const {name, age} = user;
// Works with arrays too
const colors = ['red', 'green', 'blue'];
const [first, second] = colors; // first = 'red', second = 'green'Classes — like blueprints for creating identical objects:
// ❌ Old way
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
return `Hello, ${this.name}`;
};
// ✅ New way
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
return `Hello, ${this.name}`;
}
}Modules — like a library: take only the books you need:
// Export
export const PI = 3.14;
export const add = (a, b) => a + b;
// Import
import {PI, add} from './math.js';// If no greeting provided, will be "Hello"
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Combine arrays
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Copy object
const original = {a: 1, b: 2};
const copy = {...original}; // {a: 1, b: 2}// Instead of callbacks — promises
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error!'));// ❌ Bad — mixing different types
var old = 'old';
let new = 'new';
const fixed = 'does not change';
// ✅ Better — use let/const
let variable = 'changes';
const constant = 'does not change';class Button {
constructor() {
// ❌ Mistake — this will be undefined
this.element.addEventListener('click', () => {
this.handleClick(); // Won't work!
});
}
}Knowing ES6 helps write modern and readable JavaScript! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪