Get the data type of a variable in JavaScript

To get the data type of a variable in JavaScript, use the typeof keyword before the variable name.

The typeof keyword returns the data type of the variable or property that follows it.

const myName = "John"
console.log(typeof myName) // string

const myAge = 45
console.log(typeof myAge) // number

const myTasks = ['Groceries', 'Washing', 'Exercise']
console.log(typeof myTasks) // object

const myProfile = { myName, myAge, myTasks }
console.log(typeof myProfile) // object

In JavaScript, an array is an object type, therefore the keyword typeof will return object for both arrays and traditional objects. A seperate check is therefore required to distinguish whether the variable is an array.

const myTasks = ['Groceries', 'Washing', 'Exercise']
console.log(Array.isArray(myTasks) // true

Leave a Comment