JavaScript ES6 and Modern Features
(A major leap in JavaScript with cleaner syntax, better scoping, arrow functions, and more)
What is ES6?
ES6 (ECMAScript 2015) is a major update to JavaScript that introduced new syntax and features to make code more readable, maintainable, and powerful.
It paved the way for modern JavaScript development.
1. let
and const
- Block Scoped Variables
let
- Replaces var
for reassignable variables
let name = "John";
name = "Doe"; // Allowed
const
- Immutable reference
const age = 30;
// age = 31; // ❌ Error: Assignment to constant variable
let
and const
are block-scoped and don't hoist like var
.
2. Arrow Functions (Shorter Function Syntax)
// Traditional function
function greet(name) {
return "Hello " + name;
}
// Arrow function
const greet = name => "Hello " + name;
If there are multiple lines or parameters:
const add = (a, b) => {
return a + b;
};
3. Template Literals - Using Backticks `
const name = "Alice";
console.log(`Hello, ${name}!`); // Hello, Alice!
You can also write multi-line strings:
const msg = `This is
a multiline
string`;
4. Default Parameters
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guest
5. Destructuring
Array Destructuring
const [a, b] = [1, 2];
console.log(a); // 1
Object Destructuring
const user = { name: "Sam", age: 25 };
const { name, age } = user;
6. Spread and Rest Operators (...
)
Spread (expands)
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
Rest (collects)
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
7. Enhanced Object Literals
const name = "Bob";
const user = {
name,
greet() {
console.log("Hi " + this.name);
}
};
8. for...of Loop (Array iteration)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
Use for...of
with arrays, not objects.
9. Promises (Covered in Chapter 18)
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded"), 1000);
});
};
10. Modules (import/export)
Export (in math.js)
export const add = (a, b) => a + b;
Import (in another file)
import { add } from './math.js';
console.log(add(2, 3));
Requires setting type="module"
in your HTML script tag or using a bundler.
Summary
- ES6 brought powerful improvements to variable scoping (
let
,const
), cleaner syntax (arrow functions, template literals), and more. - Spread/rest operators, destructuring, and modules simplify code and improve reusability.
- These features are foundational for modern JavaScript and frameworks like React, Vue, and Angular.
🧪 Practice Exercise:
Task:
- Rewrite a function using arrow function syntax.
- Use template literals to insert variables into a sentence.
- Use destructuring to extract values from an object.
- Create a
sum(...args)
function using the rest operator. - Create and import a module in two separate files.