Open In App

How Parameters are Passed to Functions in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, parameters are passed to functions in a couple of ways: by value and by reference.

Passing by Value:

When primitive data types (like numbers, strings, or booleans) are passed as parameters, they are passed by value. This means that the actual value of the variable is passed to the function.

Example: Here, the value of x (which is 5) is passed to the double function. Changes to number inside the function do not affect the original value of x.

Javascript




function double(number) {
    number = number * 2;
    console.log("Inside function:", number);
}
 
let x = 5;
double(x);
console.log("Outside function:", x);


Output

Inside function: 10
Outside function: 5

Passing by Reference:

When objects (including arrays and functions) are passed as parameters, they are passed by reference. This means that the reference to the object in memory is passed, not the actual object.

Example: Here, the reference to myArray is passed to the addItem function. Modifying the array inside the function also affects the original array outside the function.

Javascript




function addItem(arr, item) {
    arr.push(item);
    console.log("Inside function:", arr);
}
 
let myArray = [1, 2, 3];
addItem(myArray, 4);
console.log("Outside function:", myArray);


Output

Inside function: [ 1, 2, 3, 4 ]
Outside function: [ 1, 2, 3, 4 ]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads