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 + "!";
}
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);
A function declared with a name.
function multiply(x, y) {
return x * y;
}
console.log(multiply(4, 5)); // 20
A function without a name, often used in expressions or as arguments.
const sayHi = function() {
console.log("Hi there!");
};
sayHi();
Introduced in ES6. More concise, doesn't bind its own this.
const square = (n) => n * n;
console.log(square(6)); // 36
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);
}