How Parameters are Passed to Functions in JavaScript ?
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); |
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); |
Inside function: [ 1, 2, 3, 4 ] Outside function: [ 1, 2, 3, 4 ]