Reference and Primitive Types

Object Properties

Reference and Primitive Types

🙋 Need help? Ask an expert now!

As mentioned multiple times, JavaScript is a weakly typed language. The variables don't have a type, only their values do. JavaScript has six different data types, Number, String, Boolean, Null, Undefined and Object. Out of all these data types, only Object is a reference type. The rest of these data types are primitive types. Primitive types are passed by value, meaning they're copied each time their value is used. This means the original value isn't affected if it is referenced in a function. On the other hand, Object is passed by reference, meaning the object's value is used through a reference and will be affected by a function if it is used. Take a look at the example below for some clarification on this concept.

The first important concept to know is that all types derive from Object. This is why the typeof statement returns true when it is executed. Therefore, any data type that is not explicitly primitive is automatically a reference type. You probably noticed that the value of num didn't change while the value of arr1 changed after the functions were called. The value of num wasn't changed as the value of num was passed by value and copied to the function, which is why the original value remains unchanged. On the other hand, the value of arr1 changes because an array is an Object. The array is passed by referenced, not copied as a separate variable, which is the reason why the function addArray managed to add 1 to the start of the array. Knowing the distinction between passed by value and passed by reference is extremely important to master, so make sure you spend time on this card and fully understand the concept before moving on.

Edit Me on GitHub!

Application Question

Consider the following code segment:

let varOne = 10;
function multiply(){
  return varOne * 10;

What will the following code segment print to the console?