DEV Community

Mavis
Mavis

Posted on

Types in JavaScript

Primitive types

typeof 5 // number
typeof true // boolean
typeof 'wow' // string
typeof undefined // undefined
typeof null // object
typeof Symbol('just me') // symbol since es6
Enter fullscreen mode Exit fullscreen mode

Non-Primitive types

typeof {} // object
typeof [] // object
typeof function(){} // functio
Enter fullscreen mode Exit fullscreen mode

Playground

Primitive is pass by value

In below case, variable a have an address refer to somewhere that memory hold value 5.
let b = a means it will copy value 5, and create a new memory for it to store, then b refer to this new memory location.

A pie chart showing 40% responded "Yes", 50% responded "No" and 10% responded "Not sure"

let a = 5
let b = a
console.log(a) // 5
console.log(b) // 5
b = 10
console.log(a) // 5
console.log(b) // 10
Enter fullscreen mode Exit fullscreen mode

Non-Primitive is pass by reference

obj2 = obj1 means obj2 will refer to obj1 address.
so that obj1 and obj2 point to the same location where object store in memory

A pie chart showing 40% responded "Yes", 50% responded "No" and 10% responded "Not sure"

let obj1 = {name:'hui', password:'123'}
let obj2 = obj1
obj2.password = '456'
console.log(obj1) // 456
console.log(obj1) // 456
Enter fullscreen mode Exit fullscreen mode

Top comments (0)