Module 45 : ES6 Overview.
1 : Introduction to ES6
What is ES6.
ES6 is the 6th edition of ECMAScript, standardized in 2015.
It brings features such as let, const, arrow functions, classes, template literals, destructuring, and more.
2 : Key Features of ES6
✅ 1. let and const
Explanation:
let: Block-scoped variable (unlike var which is function-scoped).
const: Same as let but cannot be reassigned.
let name = 'Alice'; const age = 25; name = 'Bob'; // ✅ OK age = 30; // ❌ Error: Assignment to constant variable.
Why it matters: Reduces bugs caused by unexpected variable hoisting or reassignment.
✅ 2. Arrow Functions
Explanation:
A concise way to write functions. Also, arrow functions do not bind their own this.
// Traditional function function greet(name) { return `Hello, ${name}`; } // Arrow function const greet = name => `Hello, ${name}`;
// Arrow function and 'this' context function Timer() { this.seconds = 0; setInterval(() => { this.seconds++; console.log(this.seconds); }, 1000); }
Why it matters: Cleaner syntax, avoids confusion with this.
✅ 3. Template Literals
let name = "Alice"; let greeting = `Hello, ${name}!`; console.log(greeting); // Hello, Alice!
Why it matters: Makes string concatenation easier and readable.
✅ 4. Destructuring
Explanation:
Extract values from arrays or objects into distinct variables.
// Array let [a, b] = [10, 20]; console.log(a); // 10 // Object let person = { name: "Alice", age: 25 }; let { name, age } = person;
Why it matters: Cleaner syntax when accessing properties/values.
5. Spread and Rest Operators
// Spread let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5] // Rest function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); }
Why it matters: Flexible handling of parameters and combining data structures.
✅ 6. Default Parameters
function multiply(a, b = 1) { return a * b; } console.log(multiply(5)); // 5
🔍 Why it matters: Prevents the need for parameter checks and fallback logic.
✅ 7. Classes and Inheritance
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); } } class Dog extends Animal { speak() { console.log(`${this.name} barks.`); } } let dog = new Dog('Rex'); dog.speak(); // Rex barks.
🔍 Why it matters: Brings object-oriented structure and reusability to JS.
✅ 8. Promises
let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Done!"), 1000); }); promise.then(result => console.log(result)); // Done!
🔍 Why it matters: Handles asynchronous operations more cleanly than callbacks.
✅ 9.(Export/Import)
// file: math.js export function add(x, y) { return x + y; } // file: app.js import { add } from './math.js'; console.log(add(5, 3)); // 8
🔍 Why it matters: Allows code organization and reuse.
3 : Exercises
1: Converting ES5 to ES6
Refactor this ES5 code to ES6.
// ES5 var greet = function(name) { return "Hello, " + name; };
Solution (ES6):
const greet = name => `Hello, ${name}`;
2: Use Destructuring and Spread
let person = { firstName: "Alice", lastName: "Smith", age: 30 }; // Destructure and print each variable
Expected:
const { firstName, lastName, age } = person; console.log(firstName, lastName, age.)
3 : Create a Class with Methods and Inheritance
Create a Vehicle class with a method start()
Create a Car class that inherits Vehicle and overrides start()
class Vehicle { constructor(type) { this.type = type; } start() { console).log(`${this.type} is starting...`); } } class Car extends Vehicle { start() { console.log(`${this.type} car is starting smoothly.`); } } const myCar = new Car("Electric"); myCar.start(); // Electric car is starting smoothly.
4: Create a Promise Chain
function asyncTask(value) { return new Promise(resolve => { setTimeout(() => resolve(value * 2), 500); }); } asyncTask(5) .then(result => asyncTask(result)) .then(finalResult => console.log(finalResult)); // 20
4 : Research
Why Was ES6
Introduced?
JavaScript lacked modern features like classes,and lexical scoping.
Other languages like Python and Java had better syntax, making JS harder to maintain.
ES6 aimed to modernize JavaScript and make it suitable for large applications.
ES6 vs ES5 Summary Table:
Feature
ES5 Syntax
ES6 Syntax
Variable Declaration
var
let, const
Functions
function()
() => {}
String Formatting
'Hello ' + name
`Hello ${name}`
Object Properties
obj.prop
let {prop} = obj
Inheritance
Prototypes
class, extends
Modules
Not native
import, export
Conclusion
ES6 revolutionized JavaScript by introducing cleaner, modular, and more powerful features. Mastery of ES6 is essential for modern web development, whether you're building frontend interfaces, backend APIs, or full-stack applications.
✅ Assignments
Refactor a small ES5 project into ES6 syntax.
Build a class-based mini app (e.g., Task Manager or Todo).
Create a chain of asynchronous actions using Promises or async/await.
No comments:
Post a Comment