JavaScript Basics

Vishnu Sandhi
1 min readSep 20, 2020

Closure

Let's take a counter example, we are incrementing the count on the click of a button. This counter variable lives in the event listener function. The blinder variable will die once the code is run. The counter variable lives because it is used in the event listener function.

<span class=’count’>0</span>
<button class=’btn’>Click</button>

let counter = 0;
let blinder = 1;
document.querySelector(‘.btn’).addEventListener(‘click’, function(){
counter++;
document.querySelector(‘.count’).innerText=counter;
});

Pass by Reference

You can pass an object as a parameter and change the values in the object.

let obj = {
a : 1,
b: 2,
c: 3
}
function parse(b){
obj.a =2;
obj.b=3;
obj.c =4;
};
console.log(‘before’, obj);
parse(obj);
console.log(‘after’, obj);

Pass by Value

For Strings, Numbers there are pass by values only. Changing the value does not affect the actual number.

let sampleValue = 9;

function changeValue(sampleValue){
sampleValue= 15;
console.log(‘In fun’,sampleValue);
}
console.log(‘Before’,sampleValue)
changeValue(sampleValue)
console.log(‘After’,sampleValue)

Changing the Reference

In the below sample we have passed the reference and added new data to it. So the actual reference data is changed

let arr =[1,3,4];
function pushToArr(arr){
arr.push(10);
}
console.log(‘Before’,arr);
pushToArr(arr);
console.log(‘After’,arr);

In the below example we have changed the reference itself so the array is not changed

let secondarr =[1,3,4];
function changeArr(secondarr){
secondarr =[1,3,4,10];
}
console.log(‘Before’,secondarr);
changeArr(secondarr);
console.log(‘After’,secondarr);

https://codepen.io/rohinikumar4073/pen/RwayjGP?editors=0011

--

--

Vishnu Sandhi

UI Developer who likes to learn and build things for humans.