Categories
JavaScript Basics

Check JavaScript Variable Data Types with the Typeof Operator

Spread the love

The typeof operator in JavaScript is useful for checking primitive types.

JavaScript is a loosely typed or a dynamically typed language. This means that a variable that’s declare with one type can be converted to another type without explicitly converting the data to another type. Variables can also contain any type at any time depending on what’s assigned. JavaScript has multiple data types. There are 7 primitive data types and an object type. The 7 primitive types are boolean, null, undefined, number, BigInt, string and symbol. Since there are different data types and they a variable or an object’s properties’ types can change anything, we need a way to check for the type of data of an variable or an object’s property.

To check for the type of an object’s property or a variable, we use the typeof operator of an object. It lets us get the type name of an object or its properties with as a string. We can use it as allows:

typeof x

Where x is a variable’s name. This is the only operand of the typeof operator. The check the type of an object’s property, we can write:

typeof x.prop

With the code above we can conveniently get the type of the prop property of x . The typeof operator returns a string containing the name of the type of the operand. It can return the following types names as a string:

  • Objects with the undefined type will return 'undefined'
  • Objects with the null type will return 'object'
  • Objects with the boolean type will return 'boolean'
  • Objects with the number type will return 'number'
  • Objects with the BigInt type will return 'bigint'
  • Objects with the String type will return 'string'
  • Objects with the Symbol type will return 'symbol'
  • Objects with the Function type will return 'function'
  • Any other types of object will return 'object'

We can use the typeof operator like in the following examples:

Numbers

The following operands will return 'number' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof 1 === 'number';
typeof 3.1 === 'number';
typeof(2) === 'number';
typeof Math.LN10 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number';
typeof Number('2') === 'number';
typeof Number('shoe') === 'number';

The number type is a double precision 64 bit number that can have values between negative 2 to the 53rd power minus one to 2 to the 53rd power minus one. There’s no specific type for integers. All numbers are floating point numbers. There’re also 3 symbolic values: Infinity , -Infinity and NaN . These are all within the range or are Infinity , -Infinity or NaN so they all have the type of 'number' . Number(‘shoe’) returns NaN and since NaN is of type number, typeof Number(‘shoe’) is number.

Strings

The following operands will return 'string' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof '' === 'string';
typeof 'abc' === 'string';
typeof `template string` === 'string';
typeof '2' === 'string';
typeof (typeof 2) === 'string';
typeof String(1) === 'string';

Strings are used to represent textual data. Each element of the string has its own position in the string. It’s zero indexed, so the position of the first character of a string is 0. The length property of the string has the total number of characters of the string.

JavaScript strings are immutable. We cannot modify a string that has been created, but we can still create a new string that contains the originally defined string. We can extract substrings from a string with the substr() function and use the concat() function to concatenate 2 strings.

In JavaScript, anything surrounded by single quotes, double quotes, or backticks are strings. Single and double quote surround normal strings, and backticks surround template strings. The String function converts anything to a string, so String(1) returns '1' , so it’s of type string. The typeof operator returns a string, so if we are applying the typeof operator to the result returned by typeof , then that should be a string.

Booleans

The following operands will return 'boolean' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(2) === 'boolean';
typeof !!(2) === 'boolean';

The Boolean function and the double not operator (!! ) will both convert truthy values to true and falsy values to false . Falsy values in JavaScript includes 0, empty string, null , undefined , and false . So if they are passed in as as arguments to the Boolean function then they are converted to false . Everything else is truthy, so they’re converted to true with the Boolean function or the double not operator.

Symbols

The following operands will return 'symbol' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'

Symbols are new to ES2015. It is unique and immutable identifier. Once you created it, it cannot be copied. Every time you create a new Symbol it is a unique one. It’s mainly used for unique identifiers in an object. It’s a Symbol’s only purpose.

The Symbol function creates a new symbol, so anything returned by it is of type symbol. Symbol.iterator is a special symbol, so that’s also of type symbol.

Undefined

The following operands will return 'undefined' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof undefined === 'undefined';
typeof declaredVariableWithoutValueAssigned === 'undefined';
typeof undeclaredVariable === 'undefined';

A variable that has not been assigned a value has type undefined. If you do not assign a value to a declared variable or try to reference an undeclared variable, then you would get type undefined if you apply the typeof operator to them. Likewise, if you have never declared the property of an object or have declared the property haven’t assigned a value to it, those properties will also have the undefined type.

Objects

The following operands will return 'object' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
typeof null === 'object';
typeof new Date() === 'object';
typeof /regex/ === 'object';

Object is a reference data type, which means it can be referenced by an identifier which points to location of the location of the object in memory. In memory, the object’s value is stored, and with the identifier, we can access the value. Object has properties, which are key-value pairs with the values being able to contain the data with primitive types or other objects, which means we can use object to build complex data structures.

In addition to data with key-value pairs having the type object, the null type also returns object when the typeof operator is operated on it. Arrays and other iterable objects also return object as the type when we apply the operator to it to get the type, since these kinds of data are also objects in JavaScript. To check if an object is an array, we can use the Array.isArray function to determine if an object is an array.

Functions

The following operands will return 'function' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';

Functions are objects in JavaScript. Any kinds of functions, like arrow functions, functions declares with the function keyword, and classes are of type function. Note that classes in JavaScript is just syntactic sugar for functions that we can create new objects with. Therefore, classes are still of type function.

BigInts

The following operands will return 'bigint' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof 42n === 'bigint';

In JavaScript, there is the BigInt type to store numbers that are beyond safe integer range. A BigInt number can be created by adding an n character to the end of a number. With BigInt, we can make calculations that have results beyond the safe range of normal numbers. So any number that ends with an n will be of type bigint .

New Operator

The new Operator will always return an object to whatever it’s applied to, so the following will always have type object. The following operands will return 'object' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
`typeof new String(null)` === 'object';`typeof new Number(undefined)` === 'object';

Notice that no matter what we have, we get type object if the new keyword is used to create the object. It doesn’t matter whether it’s boolean, number, string, or whatever you pass in, Therefore, when we don’t need to use the new keyword to create the object, then don’t do it. To convert things to boolean, we use the Boolean function, to convert things to numbers we use the Number function, and to convert things to a string, we use the String function.

Null Type

null objects are of type object because they were represented by type tag 0. The null pointer for JavaScript is 0x00 like in most platforms. Therefore, null has type tag 0, so object has object as the type returned by typeof .

Determining Types of Expressions

We can use the typeof operator to determine the type of entities returned by expressions. We parentheses to determine the type of the result combined together in expressions. For example, if we want to get the type of 1 + ‘1’ , then we need to write:

typeof (1 + '1');

If we write the code above, we get string as the type, which is the correct type of the result of the expression. If we don’t put parentheses around the expression, then we only get the type of the first part of the expression, which is number concatenated with '1' .

Errors

Using the typeof operator before a variable declared with let or const will result in a ReferenceError being thrown, since it’s referencing a variable that’s not declared yet. Previous using the typeof operator on undeclared variables will return the type 'undefined’. The typeof operator never generated an error before ES2015.

For example, if we have:

typeof letVariable;
typeof constant;
typeof c;

let letVariable;
const constant = 'constant';
class c{};

The first 3 lines will throw a ReferenceError when they’re run.

The typeof operator is useful for checking types of primitive types and objects. For primitive types, it will return the type of the object, except for null type, which will return object as the type. Objects, including arrays and other iterable objects, will always return object as the type. With variables declared with let or const keywords and classes, we have to declare them before using the typeof operator on them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *