DEV Community

Muhammad Hamza
Muhammad Hamza

Posted on

2

Is Javascript Pass by Value or pass by Reference ?

It's a question which you will mostly hear from your interviewer. But does JavaScript pass variables by Value or by Reference ? There are good chances that if you are fresher or new to Javascript you wouldn't answer this question correctly owing to vague knowledge of how Javascript works behind the scenes, but don't worry ,it's totally normal for a new person.
And the answer to this is that Javascript pass variables by both value and reference but it depends on the data type of the variable we are working with. Primitive data types such as Strings, Booleans, Numbers, Null, , Symbol they are passed by value on the other hand Non-primitive data types such as Objects and Arrays are passed by reference

But what really is pass by Value and Pass by reference ?

Pass by value

When the variables are passed by value we target the value being passed not the actual variable. Always remember only primitive data types in Javascript use pass by value


var a = 1: 
function passByValue(a){
    a = 3
 }
passByValue(3)
console.log(a) // result is 1


Enter fullscreen mode Exit fullscreen mode

Lets see another example

let age = 55
let myAge = age
myAge = 27
age //55

Enter fullscreen mode Exit fullscreen mode

Pass By Reference

When the variables are passed by reference it means we point to actual variable. Any changes on the variable will directly effect the original declared variable. Remember Non-primitive data types perform pass by Reference in Javascript.


const car = {
  color: 'blue'
}
const anotherCar = car
anotherCar.color = 'yellow'
car.color //'yellow

Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay