We can categorize basic forms of data, known as primitives, as follows:
Number
: a value we can calculate with another, e.g.an integer like
3
,-1
or0
a floating point number like
-273.15
String
: a string of alphanumeric charactersplain text like
String
orHello world!
plain text that has non-calculatable numbers like
Price: $200
Boolean
: a value that is either true or falsenull
: an empty valueundefined
: a variable with nothing assigned (not evennull
)Object
: a value with a special structure that organizes a set of properties and their values for a group of similar thingsSymbol
: (beyond the scope of this introduction)
null
and undefined
let x
let y = null
console.log(x)
// undefined
console.log(y)
// null
Note that 0
does not mean the same thing as null
in JavaScript (as in some human languages!):
0
represents a number with which we can do calculationsnull
represents the intentional absence of a numberundefined
represents that we have not yet decided on a value or anull
typeof
keyword
To see what the type of value a variable has, we use typeof
before a value:
let x = 3.1415
console.log(typeof x)
// number
Copying by value
When we copy some primitives, we copy by value*:*
let x = 20
let y = x
y = 40
console.log(x)
// 20
Note that despite setting y
equal to x
, then changing y
's value - the value of x
does not change!
An analogy
An analogy would be copying an image from the internet and then modifying the copy in an image editing software; the original image does not change!
This happens with:
a
Number
a
String
a
Boolean
a
null
an
undefined
a
Symbol
Copying by reference
However, with:
an
Object
a
function
an
Array
...we copy by reference:
let object1 = {
prop1: 100,
prop2: 'ax',
prop3: true
}
let object2 = object1
object2.prop1 = 400
console.log(object1.prop1)
// 400
An analogy
When we copy these "higher-level" primitives, we do something similar to editing a post on social media (our edit results in changing the original for all to see!)