Intro to function
A function is a block of code designed to perform a particular task. Functions are reusable and can be called or invoked to execute the code they contain. Functions can accept inputs, known as parameters, and can return an output
Functions are a kind of object in javascript. Functions in JavaScript are first-class objects, meaning they can have properties and methods just like other objects. They can be assigned to variables, passed as arguments to other functions, and returned from functions. Here's an example:
function greet(name) {
return `Hello, ${name}!`;
}
greet.language = "English";
console.log(greet("Shadab")); // Hello, Shadab!
console.log(greet.language); // English
Type of function in js
In JavaScript, there are several types of functions, each with its own characteristics and use cases. Here are the main types:
Function Declaration:
function greet(name) {
return `Hello, ${name}!`;
}
Function Expression:
const greet = function (name) {
return `Hello, ${name}!`;
};
Arrow Function:
const greet = (name) => `Hello, ${name}!`;
Anonymous Function (usually used as a callback):
setTimeout(function () {
console.log("Hello, Shadab!");
}, 1000);
Immediately Invoked Function Expression (IIFE):
(function () {
console.log("Hello, Shadab!");
})();
Generator Function:
function* generateSequence() {
yield 1;
yield 2;
yield 3;
}
const generator = generateSequence();
console.log(generator.next().value); // 1
Async Function:
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}