Demystifying pass by value and pass by reference in JavaScript once and for all

int function abc(int a){} => pass by value 
OR
int function abc(int *a){} => pass by reference
function doSomething(x){
x = x*x;
console.log(x)
}
var y = 10;
doSomething(y); // 100
console.log(y); // 10
function doSomething(argObj){
argObj.value = "shah";
}
var obj = {
name: 'jainish'
};
console.log(obj.name); // jainish
doSomething(obj);
console.log(obj.name); //shah
var x = 6 ; ======> x[6] (memory block actually hold the value 6)
var z = {name:'jainish'} ==> z[refToHeap]==>heap[ {name:'jainish'} ]
(variable z have the value of the memory location)
function abc(x){
x = x*x;
console.log(x);
}
var y = 6;
abc(6);
function abc(argObj){
argObj.name = "shah";
}
var obj = {name: 'jainish'};
console.log(obj.name);
abc(obj);
console.log(obj.name);
function abc(argObj){
argObj = {
name: 'shah'
};
}
var obj = {name : 'jainish'};
console.log(obj.name); // jainish
abc(obj);
console.log(obj.name); // jainish
abc({...obj});console.log(obj.name) // jainish;// In destructuring a new Obj is created so the reference will
// always be different. In this case you are not even using the
// reference of obj when you call the function abc
function doSomething(){ 
for(var i=0;i<10;i++){
setTimeout( function(){ console.log(i) }, i*1000);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store