JavaScript Functions

1. What is a Function?

A function is a reusable block of code designed to perform a specific task. It can take inputs (parameters), process them, and return an output.

function greet(name) {
  return "Hello, " + name + "!";
}

2. Why Use Functions?

3. Synchronous vs Asynchronous Functions

Synchronous functions are executed sequentially, one at a time.

function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // 5

Asynchronous functions can run independently of the main flow, using mechanisms like promises or async/await.

setTimeout(() => {
  console.log("I run after 2 seconds");
}, 2000);

4. Named Function

A function declared with a name.

function multiply(x, y) {
  return x * y;
}
console.log(multiply(4, 5)); // 20

5. Anonymous Function

A function without a name, often used in expressions or as arguments.

const sayHi = function() {
  console.log("Hi there!");
};
sayHi();

6. Arrow Function

Introduced in ES6. More concise, doesn't bind its own this.

const square = (n) => n * n;
console.log(square(6)); // 36

7. Asynchronous Function (Async/Await)

Declared with the async keyword, uses await to wait for promises.

async function fetchData() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  console.log(data);
}

8. Summary