COMPOSITE DATA TYPE & CALL BY VALUE & CALL BY REFERENCE — JAVASCRIPT

Balaji sankar
2 min readNov 4, 2020

What is a composite data type?

Data types basically specify what kind of data can be stored and manipulated within a program. A composite data type in JavaScript has multiple values, which grouped together. The object and array are composite data types while string, boolean, and number are primitive data types.

There are two ways by which we can pass data to a function

  1. call by value (primitive data types are called by value).
  2. call by reference (composite data types are called by reference)

In call by value the parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller.

let a = 5;

increment(a);

function increment(x){

x = x + 1;

}

console.log(x)// 5

In the above example, the function increment takes a primitive data type number as a parameter while calling the function the value a is copied to x.So

whatever changes we do on the variable x does not reflect on the variable a.

In call by reference both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in the actual parameters of the caller.

var car = {

“model”: “BMW X3”,

“color”: “white”,

“doors”: 5

}

changeModel(car)

function changeModel(x){

x.model = “BMW i3”

}

console.log(car.model)//BMW i3

var car =====> points to the memory location of the obj car

function variable x ===== >points to the same memory location

In the above code, we are passing the reference of the object car to the function changeModel so if we try to change the properties it gets updated in the actual car object

If we want to try to pass the composite datatype as a value we have to deep clone the object.

In case of array :

let arr = [1,2,3];

addNextNumber(arr);

function addNextNumber(x){

x = […x]

x[x.length] = x[x.length-1] + 1;

}

console.log(arr)//[1,2,3];

In case of object:

var car = {

“model”: “BMW X3”,

“color”: “white”,

“doors”: 5

}

changeModel(car)

function changeModel(x){

x = {…x}

x.model = “BMW i3”

}

console.log(car.model)//BMW X3

In the function addNextNumber and changeModel we have made the variable x point to a new object created from the actual value(cloned object), so whatever changes we do in the cloned object does not apply to the actual object since they both point to different memory location.

--

--