DEV Community

Usama
Usama

Posted on

🧩 9 JavaScript Function Concepts (Easy Guide)

🧩 Function Declaration

The classic way to define a function.

function greet(name) {
  return `Hello, ${name}!`;
}
console.log(greet("Usama")); // Hello, Usama!
Enter fullscreen mode Exit fullscreen mode


`


πŸ”§ Function Expression

Store a function in a variable.

js
const greet = function(name) {
return
Hello, ${name}!;
};
console.log(greet("Ali"));


🎯 Arrow Function

Shorter syntax, often used in modern JS.

js
const greet = (name) =>
Hello, ${name}!;
console.log(greet("Ayesha"));


βš™οΈ Default Parameters

Provide a fallback value if no argument is given.

js
function greet(name = "Guest") {
return
Hello, ${name}!;
}
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)