Types are fundamental pieces of the language. They are used to represent data, store it and manipulate it.
JavaScript is a dynamically typed language which means that types are associated with values rather than variables.
Once a variable is assigned a certain type of value, it can later be changed to a different type.
JavaScript is also a weakly typed language. It implicitly casts types during operations if the operands are not of the same type.
JavaScript has eight primitive types. They are:
NumberStringBooleanObjectUndefinedNullSymbolBigInt
Letβs take a look at each of them.
Number
Number was the only numeric type in JavaScript until very recently. The BigInt type was introduced to handle integers of arbitrary length.
Positive numbers, negative numbers, integers and floats are all represented using the same Number type.
They can represent integer values up to 253 (or -253 for negatives).
|
|
Precision Problems
Because of the way JavaScript handles numbers, you need to be careful of precision problems.
It cannot store an infinite amount of precision.
|
|
String
String is generally used to represent textual data.
They can be represented with ""(double quotes), ''(single quotes), or ``(backticks).
The double and single quotes are the exact same.
|
|
Template Literals
The backticks are called template literals. They allow us to interpolate javascript variables and expressions inside them using ${}. Anything inside the {} will be interpreted as a JavaScript expression.
|
|
They can also be used to create multiline strings easily.
|
|
The above code outputs
|
|
Boolean
Boolean are used to represent true or false values. Note that these are keywords reserved by the language and are not simply strings.
Comparison operators such as ==, ===, > < return a Boolean.
They can also be assigned to variables.
Object
An Object type is a collection of properties.
The properties of an object is identified using keys which are either String or Symbol values.
|
|
Subtypes of Objects
There are two subtypes of objects
ArrayFunction
An Array is a an ordered collection of values.
A Function is a way to define a set of instructions which can be used many times.
|
|
undefined
undefined is used to assigned to variables that have been just been declared but havenβt been assigned any values
null
null represents the absence of a value or reference.
Symbol
The Symbol type is used as unique identifiers for Object keys.
Every Symbol value is unique and immutable.
BigInt
The BigInt type was introduced to represent an arbitrary length of integers. The length of the integer is limited only by memory space.
They are represented by appedning n to the end of an integer.
They cannot be used with the number type.
|
|