What is function
A JavaScript function is a reusable block of code designed to perform a specific task. Instead of writing the same code multiple times, you wrap it inside a function and execute it whenever needed.
In JavaScript, functions are First-Class Objects, meaning they can be stored in variables, passed as arguments to other functions, and returned from other functions.
In JavaScript, a first-class object (or first-class citizen) means that a value can be treated like any other value in the language.
Because JavaScript treats functions just like other values such as numbers, strings, and objects.
Key Components of a Function
Definition: Creating the function using a specific syntax.
Parameters: Placeholder variables listed inside the parentheses () when defining the function.
Arguments: The actual values passed into the function when you run it.
Return Statement: An optional return keyword used to send a value back to where the function was called. It immediately stops function execution.
Invocation (Calling): Running the function by using its name followed by parentheses ().
Why Use Functions?
Code Reusability: Write your logic once and reuse it across your application.
Organization: Breaks down a complex program into smaller, manageable chunks.
Maintainability: If a task changes, you only need to update the code inside the function.
Scope Isolation: Variables defined inside a function are hidden from the outside world, preventing naming conflicts.
Example
function greet(name) { // 'name' is a parameter
console.log("Hello " + name);
}
greet("Alice"); // "Alice" is the argument
Parameter: name (placeholder inside the function).
Argument: "Alice" (real value given at call time).
Default Parameters
Default parameters are used when no argument is provided during the function call.
If no value is passed, the function automatically uses the default value.
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); //Hello Guest
greet("Aman"); //Hello Aman
Return Statement
The return statement is used to send a result back from a function.
When return executes, the function stops running at that point.
The returned value can be stored in a variable or used directly.
function add(a, b) {
return a + b; // returns the sum
}
let result = add(5, 10);
console.log(result);
Naming a function
In JavaScript, you can name a function using camelCase (most common convention).
Syntax
function functionName() {
// code
}
Examples
function greetUser() {
console.log("Hello User");
}
function calculateSum() {
console.log(10 + 20);
}
function findLargestNumber() {
console.log("Finding largest number");
}
Naming rules
Can contain:
Letters (a-z, A-Z)
Numbers (0-9) (but not at the beginning)
_ (underscore)
$ (dollar sign)
function user1() {}
function _display() {}
function $calculate() {}
Best Practices
Use names that describe what the function does:
function getUserData() {}
function calculateEMI() {}
function reverseNumber() {}
function checkLeapYear() {}
Avoid unclear names:
function a() {} // Bad
function xyz() {} // Bad
- Function names should be meaningful, follow camelCase convention, start with a letter, _, or $, and clearly describe the purpose of the function.
Parameters
Parameters are variables listed in the function definition that receive values when the function is called.
function greet(name) { // name is a parameter
console.log("Hello " + name);
}
greet("Vicky"); // "Vicky" is an argument
Parameter → Variable in the function definition.
Argument → Actual value passed to the function.
Types of Parameters
1. No Parameters
function greet() {
console.log("Hello");
}
greet();
2. Single Parameter
function square(num) {
console.log(num * num);
}
square(5);
3. Multiple Parameters
function add(a, b) {
console.log(a + b);
}
add(10, 20);
4. Default Parameters
- If no argument is passed, the default value is used.
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guest
greet("Vicky"); // Hello Vicky
5. Rest Parameters (...)
Used when you don't know how many arguments will be passed.
function sum(...numbers) {
console.log(numbers);
}
sum(10, 20, 30, 40);
Output:
[10, 20, 30, 40]
Common Cases
Case 1: Correct Number of Arguments
function add(a, b) {
console.log(a + b);
}
add(10, 20);
Output:
30
Case 2: Fewer Arguments than Parameters
function add(a, b) {
console.log(a, b);
}
add(10);
Output:
10 undefined
Because b did not receive a value.
Case 3: More Arguments than Parameters
function add(a, b) {
console.log(a, b);
}
add(10, 20, 30, 40);
Output:
10 20
Extra arguments are ignored (unless using rest parameters).
Case 4: Passing Different Data Types
function display(value) {
console.log(value);
}
display(100);
display("Hello");
display(true);
Parameter and Argument
function multiply(a, b) { // Parameters
return a * b;
}
multiply(5, 4); // Arguments
- Parameters are variables declared in a function definition that receive values (arguments) when the function is called. JavaScript supports normal parameters, multiple parameters, default parameters, and rest parameters.
Formal Arguments and Actual Arguments
function multiply(x, y) { // Formal arguments
return x * y;
}
multiply(5, 4); // Actual arguments
Formal arguments (parameters) are the variables declared in a function definition. Actual arguments are the real values passed to the function when it is called.
Parameters, also called formal arguments, are the variables declared in a function definition that receive values from the Actual arguments passed during a function call.
Return Statement in JavaScript
The return statement is used to send a value back from a function to the place where the function was called.
Syntax
function functionName() {
return value;
}
Uses of return
1. Return a Value
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(result);
Output:
30
2. Store the Returned Value
function square(num) {
return num * num;
}
let answer = square(5);
console.log(answer);
Output:
25
3. Use Returned Value in Another Expression
function add(a, b) {
return a + b;
}
console.log(add(10, 20) * 2);
Output:
60
return Stops Function Execution
function test() {
console.log("Start");
return;
console.log("End");
}
test();
Output:
Start
The code after return is never executed.
Multiple Returns with Conditions
function check(num) {
if (num > 0) {
return "Positive";
}
return "Negative or Zero";
}
Only one return statement executes during a function call.
- The return statement is used to exit a function and send a value back to the function caller. It can return any JavaScript data type such as Number, String, Boolean, Object, Array, Function, or undefined. The return statement also immediately stops further execution of the function.
Hoisting in Functions
Hoisting means JavaScript moves declarations to the top of their scope before executing the code.
1. Function Declaration → Hoisted
You can call the function before it is defined.
greet();
function greet() {
console.log("Hello");
}
Output:
Hello
Why?
JavaScript internally treats it like:
function greet() {
console.log("Hello");
}
greet();
So function declarations are fully hoisted.
2. Function Expression with var → Partially Hoisted
greet();
var greet = function() {
console.log("Hello");
};
Output:
TypeError: greet is not a function
Why?
Only the variable declaration is hoisted:
var greet; // hoisted
greet(); // undefined()
greet = function() {
console.log("Hello");
};
So greet exists, but it is undefined when called.
3. Function Expression with let → Not Usable Before Declaration
greet();
let greet = function() {
console.log("Hello");
};
Output:
ReferenceError
Because let is in the Temporal Dead Zone (TDZ) until its declaration is reached.
- Function declarations are fully hoisted, so they can be called before their declaration. Function expressions and arrow functions are not fully hoisted; only variables declared with var are hoisted as undefined, while let and const remain in the Temporal Dead Zone until their declaration is reached.
References
https://www.programiz.com/javascript/function
https://www.geeksforgeeks.org/javascript/functions-in-javascript/
Top comments (0)