In JavaScript, a function is a reusable block of code that performs a task. You define it once and can call it whenever you need it.
1. Basic function
function greet() {
console.log("Hello!");
}
greet();
Here, greet is the function name, and greet() calls the function.
2. Function with parameters
Parameters let you pass information into a function:
function greet(name) {
console.log("Hello, " + name);
}
greet("John");
greet("Sara");
Output :
Hello, John
Hello, Sara
3. Returning a value
A function can calculate something and return the result:
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(result); // 30
a and b are parameters, while 10 and 20 are arguments.
4. Function expression
A function can also be stored in a variable:
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // 8
5. Arrow function
Modern JavaScript commonly uses arrow functions:
const add = (a, b) => {
return a + b;
};
For a simple return, you can shorten it:
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
So the core idea is:
function functionName(parameters) {
// code
return result;
}
functionName(arguments);
Top comments (0)