JavaScript ES6 Features With Code
Arrow Functions :
// ES5 function
function addNum(num1, num2) {
return num1 + num2;
}
// ES6 arrow function
const addNum = (num1, num2) => num1 + num2;
Template Literals :
const siteName = "Notesaid24";
const greeting = `Welcome ${siteName}!`;
console.log(greeting);
Destructuring :
const person = {
name: "Ahshan Habib",
age: 25,
};
const { name, age } = person;
console.log(`My name is ${name} and I am ${age} years old!`);
Spread Operator:
const numbers = [1, 2, 3, 4];
const newNumbers = [...numbers, 5, 6, 7, 8];
console.log(newNumbers);
Rest Parameter:
const sumNum = (...numbers) => {
return numbers.reduce((acc, num) => {
return acc + num;
}, 0);
};
console.log(sumNum(1, 2, 3, 4, 5));
Async / Await:
const API = "https://api.notesaid24.com";
const fetchData = async () => {
try {
const res = await fetch(`${API}/blogs`);
const data = res.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
Map & Set:
const numMap = new Map().set("one", 1);
const unique = new Set([1, 2, 3, 2, 1, 3]);
unique.forEach((number) => console.log(number));
Default Parameters:
const greet = (name = "Guest") => {
return `Hello, ${name}!`;
};
console.log(greet());
console.log(greet("Ahshan Habib"));
Modules:
// Exporting module
// myModule.ts
export const myFunction = () => {
console.log("Hello from myFunction!");
};
// Importing module
// anotherFile.ts
import { myFunction } from "./myModule";
myFunction(); // This will log "Hello from myFunction!" to the console
Map Methods:
const people = [
{ name: "John", age: 15 },
{ name: "Jane", age: 23 },
{ name: "Jim", age: 17 },
{ name: "Jack", age: 21 },
];
const names = people.map((person) => person.name);
console.log(names); // Output: ["John", "Jane", "Jim", "Jack"]
Filter Methods:
const numbers = [5, 12, 8, 130, 44];
const filteredNumbers = numbers.filter((number) => number > 10);
console.log(filteredNumbers); // Output: [12, 130, 44]
Reduce Methods:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 15