Call By Value And Call By Reference In JavaScript

When you are writing some code in a programming language there are some things you should keep in mind and be aware of that as well. In programming with JavaScript there are some basic things you should be familiar with.

You should always remember that the objects are the associative arrays in JavaScript. We mean that you can write the objects just like an object oriented language or in the form of an associative array. For example

Obj.property         or            Obj[‘property’]

You can use the arrays as objects as well so they are interchangeable with each other.

The other thing you should keep in mind is that the associative array keys are first converted to strings when they are used as accessors in JavaScript. What do we mean by that lets see the following example to understand the concept.

Obj[6+2]                  is like             Obj[‘8’]

It means that 6+2 is treated as a string in associative array key as we are passing 8 in it.

In JavaScript the primitive values like numbers are passed by values to a function. It means that a distinct copy of the variable is passed to the function. It the function changes or modifies the value in it the original value of the variable will not change. This is called call by value in programming. Look at the following examples to understand more.

Example:

function first(x) {
x +=4; // no effect on x original value

}

function second() {

var x = 4;

first(x); // x has still the same value as 4

}

On the other hand the objects and arrays are passed to the function by reference. So when the value of an object or array has been changed by the function it will change the original value as well. In this case not the copy of the value is passed but the address of the object or array is passed. Let’s see the following example to understand the concept.

Example:

function first(obj){

obj.d = new Date(2013, 15); // this will change the value of the obj

}

function second(){

var x = new object();

x.d = new Date();

first(x); //x.d has been change

}

Now looking at the above examples it should be clear that what is a call by reference and call by value in JavaScript and how the variable and objects are called in JavaScript.

Comments