What is a Function? Simple Explanation with Examples
Source: Dev.to
What is a Function?
A function is a block of code that performs a specific task.
Instead of writing the same code repeatedly, you can write it once inside a function and reuse it whenever needed.
Example
function square(number) {
return number * number;
}functionis the keyword that defines a function.squareis the function name.- The parentheses contain parameters (in this case,
number). If you need multiple parameters, separate them with commas.
Calling the Function
To execute the function, call it by its name:
let calculation = square(2); // => 4
console.log(calculation); // 4square(2)passes the argument2to the parameternumber.- The function returns
number * number, which is2 * 2 = 4. - The returned value is stored in the variable
calculationand then logged to the console.