Intermediate-level JavaScript tutorial with examples

intermediate-level JavaScript tutorial with examples:

  1. 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;
  1. 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));
  1. 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);
  1. 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);
  1. 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();
  1. 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();
  1. 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));
  1. 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);
}

Leave a Reply

Your email address will not be published. Required fields are marked *