/

JavaScript typeof Operator

JavaScript typeof Operator

In JavaScript, every value has an assigned type. To determine the type of a variable, we can use the typeof operator, which returns a string representing the variable’s type.

Here are a few examples of using the typeof operator:

1
2
3
4
5
6
7
8
typeof 1; //'number'
typeof '1'; //'string'
typeof {name: 'Flavio'}; //'object'
typeof [1, 2, 3]; //'object'
typeof true; //'boolean'
typeof undefined; //'undefined'
typeof (() => {}); //'function'
typeof Symbol(); //'symbol'

It’s interesting to note that JavaScript doesn’t have a specific “function” type. However, when we pass a function to the typeof operator, it returns 'function'. This quirk is designed to simplify our coding.

If a variable is declared but not initialized, its value will be undefined until a value is assigned to it:

1
let a; //typeof a === 'undefined'

The typeof operator also works on object properties. For example, if we have a car object with only one property:

1
2
3
const car = {
model: 'Fiesta'
}

We can check if the color property is defined on the car object using typeof:

1
2
3
if (typeof car.color === 'undefined') {
// color is undefined
}

tags: [“JavaScript”, “typeof operator”, “variable types”, “object properties”]