ES6+ Modern JavaScript Basics

Beginner
100 XP
40 min
Lesson Content

ES6+ Modern JavaScript Basics

ES6 (ECMAScript 2015) introduced many powerful features that make JavaScript more expressive and easier to write. Let's explore the essential modern JavaScript features.

1. Arrow Functions

// Old way
function add(a, b) {
  return a + b;
}

// ES6 way
const add = (a, b) => a + b;

// With multiple lines
const greet = (name) => {
  return `Hello, ${name}!`;
};

2. Template Literals

// Old way
let message = 'Hello, ' + name + '! You are ' + age + ' years old.';

// ES6 way
let message = `Hello, ${name}! You are ${age} years old.`;

// Multi-line strings
let text = `Line 1
Line 2
Line 3`;

3. Destructuring

// Array destructuring
let [first, second, third] = [1, 2, 3];

// Object destructuring
let person = { name: 'John', age: 30 };
let { name, age } = person;

// Function parameters
function greet({ name, age }) {
  return `Hello, ${name}! You are ${age}.`;
}

4. Default Parameters

// Old way
function greet(name) {
  name = name || 'Guest';
  return `Hello, ${name}!`;
}

// ES6 way
function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}

5. Spread Operator

// Arrays
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Objects
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

// Function arguments
let numbers = [1, 2, 3];
Math.max(...numbers); // 3

6. Rest Parameters

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

sum(1, 2, 3, 4); // 10
Example Code

Use modern JavaScript features to write cleaner code

// Arrow functions
const multiply = (a, b) => a * b;
console.log('Multiply:', multiply(3, 4));

// Template literals
const name = 'Alice';
const age = 25;
const greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting);

// Destructuring
const person = { firstName: 'John', lastName: 'Doe', city: 'NYC' };
const { firstName, lastName } = person;
console.log(`Name: ${firstName} ${lastName}`);

// Array destructuring
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
console.log(`First: ${firstColor}, Second: ${secondColor}`);

// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log('Combined:', arr2);

// Rest parameters
function calculateSum(...numbers) {
  return numbers.reduce((sum, num) => sum + num, 0);
}
console.log('Sum:', calculateSum(1, 2, 3, 4, 5));

// Default parameters
function greet(name = 'Guest', greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}
console.log(greet());
console.log(greet('Alice', 'Hi'));

Expected Output:

Multiply: 12
Hello, Alice! You are 25 years old.
Name: John Doe
First: red, Second: green
Combined: [1,2,3,4,5]
Sum: 15
Hello, Guest!
Hi, Alice!
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code