Function
Learn JavaScript functions: declaring, using them, handling parameters, return values, and hoisting for organized, reusable code.
Learn JavaScript functions: declaring, using them, handling parameters, return values, and hoisting for organized, reusable code.
A function is a reusable block of code. You define it once and call it as many times as you need.
function greet(name) { console.log(`Hello, ${name}!`);}greet("Reza"); // Hello, Reza!greet("Alice"); // Hello, Alice!Parameters are the names in the function definition. Arguments are the values you pass when calling it.
function add(a, b) { // a and b are parameters return a + b;}
add(3, 5); // 3 and 5 are arguments — returns 8return sends a value back to the caller and stops the function:
function square(n) { return n * n;}
const result = square(4); // 16Without return, the function returns undefined.
function greet(name = "friend") { console.log(`Hello, ${name}!`);}
greet(); // Hello, friend!greet("Reza"); // Hello, Reza!Function declarations are hoisted — you can call them before they appear in the file:
greet("Reza"); // works fine
function greet(name) { console.log(`Hello, ${name}!`);}Function expressions (const greet = function() {}) and arrow functions are not hoisted.
In JavaScript, functions are values. You can store them in variables, pass them to other functions, and return them from functions:
const double = function (n) { return n * 2;};const triple = (n) => n * 3;
[1, 2, 3].map(double); // [2, 4, 6]This is what makes callbacks, array methods, and patterns like closures possible.