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 | typeof 1; //'number' |
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 | const car = { |
We can check if the color
property is defined on the car
object using typeof
:
1 | if (typeof car.color === 'undefined') { |
tags: [“JavaScript”, “typeof operator”, “variable types”, “object properties”]