π§© Function Declaration
The classic way to define a function.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Usama")); // Hello, Usama!
`
π§ Function Expression
Store a function in a variable.
js
Hello, ${name}!
const greet = function(name) {
return;
};
console.log(greet("Ali"));
π― Arrow Function
Shorter syntax, often used in modern JS.
js
Hello, ${name}!
const greet = (name) =>;
console.log(greet("Ayesha"));
βοΈ Default Parameters
Provide a fallback value if no argument is given.
js
Hello, ${name}!
function greet(name = "Guest") {
return;
}
console.log(greet()); // Hello, Guest!
π¦ Rest Parameters
Gather multiple arguments into an array.
js
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(2, 4, 6, 8)); // 20
π Return Values
Send results back from a function.
js
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
πΆοΈ Anonymous Function
A function without a name, often used inline.
js
setTimeout(function() {
console.log("Hello after 1 second β°");
}, 1000);
πͺ Higher-Order Function
A function that takes or returns another function.
`js
function applyTwice(fn, value) {
return fn(fn(value));
}
const double = x => x * 2;
console.log(applyTwice(double, 5)); // 20
`
π Callbacks
Passing a function into another function to run later.
`js
function fetchData(callback) {
setTimeout(() => {
callback("β
Data received!");
}, 1000);
}
fetchData(msg => console.log(msg));
`
π Wrap Up
These 9 function concepts are building blocks for everything in JavaScript:
from loops, to DOM manipulation, to async programming π.
π Which concept was the hardest for you at first?
Drop a comment and letβs discuss! π¬
`
π View on GitHub
All these 9 function concepts with code files are available on my GitHub repo:
π GitHub Repository Link
`
Top comments (0)