What’s the difference between a boolean as primitive and a boolean as property of an object?

All arguments are passed by “value” in JavaScript. This means that when an argument is passed, a copy of what’s stored in the variable is passed.

Primitives (like booleans) store the actual data they represent and so, when a primitive is passed, a copy of the data is sent, resulting in two copies of the data. Changes to one, won’t affect the other.

But, when you assign an object to a variable, the variable stores the memory location for where that object can be found, not the object itself. Passing an object as an argument results in a copy of the memory address being passed. In these cases, you may wind up with two variables that store the same memory address, so no matter which variable you use, the same one underlying object is affected.

In your scenario, you could certainly make it work with just a boolean variable, but it appears that the tutorial wants to encapsulate that into an object so that copies of the boolean data won’t be floating around and there will be less chances of accidentally changing one variable but not another.

Here’s some basic examples:

// This function takes a single argument, which it calls "input"
// This argument will be scoped to the function.
function foo(input){
  // The function is going to alter the parameter it received
  input = input + 77;
  console.log(input); 
}

var input = 100;  // Here's a higher scoped variable also called "input"

foo(input);       // We'll pass the higher scoped variable to the function

// Now, has the higher level scoped "input" been changed by the function?
console.log(input);  // 100 <-- No, it hasn't because primitives pass a copy of their data

// ************************************************

// Now, we'll do roughly the same thing, but with objects, not primitives
function foo2(obj){
  obj.someProp = 100;
  console.log(obj.someProp);
}

var obj = {
  someProp : 50
};

foo2(obj);

// Here, we see that the original object has been changed by the funciton we passed it to
console.log(obj.someProp);

Leave a Comment