intermediate-level JavaScript tutorial with examples:
- Arrow Functions:
Arrow functions provide a shorter syntax for writing function expressions.
// Regular Function
function square(num) {
return num * num;
}
// Arrow Function
const square = (num) => num * num;
- Higher-Order Functions:
Higher-order functions are functions that take other functions as arguments or return functions.
// Higher-Order Function
function doMath(operation, num1, num2) {
return operation(num1, num2);
}
// Callback Functions
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
console.log(doMath(add, 5, 3));
console.log(doMath(subtract, 5, 3));
- Destructuring Assignment:
Destructuring assignment allows you to extract values from arrays or objects into separate variables.
// Array Destructuring
let numbers = [1, 2, 3];
let [a, b, c] = numbers;
console.log(a, b, c);
// Object Destructuring
let person = { name: "John", age: 25 };
let { name, age } = person;
console.log(name, age);
- Spread Operator:
The spread operator allows you to spread elements of an iterable (like an array) into individual elements.
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
- Classes and Objects:
JavaScript supports object-oriented programming with classes and objects.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hello, " + this.name + "!");
}
}
let person = new Person("John", 25);
person.greet();
- Promises and Async/Await:
Promises and async/await are used for handling asynchronous operations in a more readable and sequential manner.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 2000);
});
}
async function processData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.log("Error:", error);
}
}
processData();
- Modules:
Modules help organize and split code into separate files, allowing for better code organization and reusability.
// Module: math.js
export function add(a, b) {
return a + b;
}
// Module: main.js
import { add } from "./math.js";
console.log(add(5, 3));
- Error Handling:
JavaScript provides error handling mechanisms like try/catch blocks to handle and manage exceptions.
try {
// Code that might throw an error
throw new Error("Something went wrong");
} catch (error) {
console.log("Error:", error);
}