Skip to content

Primitive types vs objects in JavaScript

New Course Coming Soon:

Get Really Good at Git

What is the main difference between primitive types and objects in JavaScript?

First, let’s define what are primitive types.

Primitive types in JavaScript are

null is a special primitive type. If you run typeof null you’ll get 'object' back, but it’s actually a primitive type.

Everything that is not a primitive type is an object.

Functions are objects, too. We can set properties and method on functions. typeof will return 'function' but the Function constructor derives from the Object constructor.

The big differences between primitive types and objects are

If we copy a primitive type in this way:

let name = 'Flavio'
let secondName = name

Now we can change the name variable assigning it a new value, but secondName still holds the old value, because it was copied by value:

name = 'Roger'
secondName //'Flavio'

If we have an object:

let car = {
  color: 'yellow'
}

and we copy it to another variable:

let car = {
  color: 'yellow'
}

let anotherCar = car

in this case anotherCar points to the same object as car. If you set

car.color = 'blue'

also

anotherCar.color

will be 'blue'.

The same works for passing around objects to functions, and for comparing.

Say we want to compare car to anotherCar:

anotherCar === car //true

This is true because both variables point to exactly the same object.

But if anotherCar was an object with the same properties as car, comparing them would give a false result:

let car = {
  color: 'yellow'
}

let anotherCar = {
  color: 'yellow'
}

anotherCar === car //false
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: