Data Types
There are two kinds of data types in JavaScript: primitives and objects.
Primitive values are atomic data that is passed by value and compared by value. The following are the primitive types:
booleanstringnumberundefinednullsymbolbigint
Objects, on the other hand, are compound pieces of data that are compared by reference. Technically, JavaScript passes the reference by value. We will see more about objects in chapter 2.
The typeof operator
You can check the type of a value by using the typeof operator.
console.log(typeof "two"); // string
console.log(typeof 2); // number
console.log(typeof true); // boolean
console.log(typeof undeclaredVariable); // undefined
console.log(typeof { value: 2 }); // object
boolean
The Boolean type is similar to the Boolean type in most other programming languages, with two values: true and false.
let isRequired = true;
let isOptional = false;
string
To be discussed shortly.
number
To be discussed shortly.
Primitive types and their wrappers
The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean.
const name = "Ali";
const firstname = new String("Ali");
console.log(name); // Ali
console.log(firstname); // Ali
console.log(typeof name); // string
console.log(typeof firstname); // object
console.log(name instanceof String); // false
console.log(firstname instanceof String); // true
The values undefined and null
JavaScript has two “bottom” values.
- An uninitialized variable is
undefined. - The
nullvalue represents a value that is intentionally “absent”.
Let’s try this in the console:
console.log(name); // ReferenceError: name is not defined
Now, let’s try this:
let name;
console.log(name); // undefined
So “not defined” and “undefined” are two different things. Now, let’s try this:
let name = null;
console.log(name); // null
Initializing the variable name to null is a deliberate action to indicate that the value is “absent”.
JavaScript has a lot of quirks, and many of them involve null and undefined: how they behave, how they relate, and how they differ. We will see some of these in later sections. For now, consider this example:
console.log(typeof undefined); // undefined
console.log(typeof null); // object
symbol
The symbol type was added to JavaScript later. It enables metaprogramming (writing code that manipulates or generates other code). It is covered in the chapter on advanced topics. You typically do not need to use symbols.