Javascript Function Argument Passing

Introduction

All function arguments in Javascript are passed by value.

If the value is primitive, then it acts just like a primitive variable copy.

If the value is a reference, it acts just like a reference variable copy.

function addTen(num) {
    num += 10;/*from  w  w w  . j ava 2  s.  co m*/
    return num;
}

let count = 20;
let result = addTen(count);
console.log(count); // 20 - no change 
console.log(result); // 30 

The following code show the reference values passing.

function setName(obj) {
    obj.name = "HTML";
}

let person = new Object();
setName(person);/*from ww  w. j  a v  a  2s .c  om*/
console.log(person.name); // "HTML" 

The following code shows that the objects are passed by value:

function setName(obj) {
    obj.name = "HTML";
    obj = new Object();/*ww  w.j a v  a  2s.  c o  m*/
    obj.name = "Javascript";
}

let person = new Object();
setName(person);
console.log(person.name); // "HTML" 

When obj is overwritten inside the function, it becomes a pointer to a local object.

That local object is destroyed as soon as the function finishes executing.




PreviousNext

Related