Hey All ๐
This is more of a notes rather than an article that I took while doing an course. In this article we will talk about JavaScript types and about typeof operator.
Based on the ES Specs the types are defined as -
โAn ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. โ
So it pretty much explains itself that types have some kind of values that can be manipulated by us using javascript.
Letโs talk about the primitive types that we have -
Undefined
It has only one value called undefined. Any variable which is not assigned a value has the value undefined.
Null
The Null type has exactly one value, called null. It represents an intentional absence of object value.
Boolean
This refers to two specific values - true & false.
String
The string type is generally used to represent the textual data. This is just the double quotes or single quotes string literal.
Number
The Number type is a double-precision 64-bit binary format IEEE 754 value (numbers between -(2^53 โ 1) and 2^53 โ 1). Also, it has three other values namely: +Infinity, -Infinity, and NaN ("Not a Number").
Object
An Object is a collection of properties. Each property is either a data property or an accessor property.
Symbol
The Symbol type is the set of all non-String values that may be used as the key of an Object property. It is a unique and immutable primitive value.
Note - Functions and arrays are treated as sub-type of Object type.
Note - BigInt is now recognized as primitive type which is supported by most of the browsers.
typeof(23423432423423423424234n) // 'bigint'
Read more about BigInt - here
typeof
We can use typeof operator to check the type of the value stored in a variable.
Letโs see some examples -
var a;
typeof(a); // 'undefined'
a = 5;
typeof(a); // 'number'
a = "Apple";
typeof(a); // 'string'
a = true;
typeof(a); // 'boolean'
a = {};
typeof(a); // 'object'
Here, one thing to note is that it returns the type in string.
So if you have a piece of code like this -
if(typeof(a) === Number){
...
}
Itโs not gonna work as you intend to. The correct way to do this is by using number as a string.
if(typeof(a) === 'number'){
...
}
Letโs have a look at some tricky ones -
typeof(doesntExist); // 'undefined'
var v = null;
typeof(v); // 'object'
v = function(){};
typeof(v); // 'function'
v = [1,2,3]
typeof(v); // 'object'
Here we can see that the type of a variable which is not declared yet or doesnโt exist is โundefinedโ.
Unlike typeof(undefined) which returns 'undefined', typeof(null) returns 'object' which is actually a historical bug. And now it canโt be fixed as a lot of legacy apps will break because of it.
Though function is not a type but itโs typeof() returns 'function' but thatโs not the case with an array as typeof([]) returns โobjectโ.
I'll be posting more of my notes on JS topics, So stay tuned :)
Top comments (1)
You've omitted BigInt