To get the data type of a variable, we use the typeof operator. JavaScript is a "dynamically typed" programming language. In such languages, the type of a variable can change throughout the program. Let us see the below code for example.
// x is a number
let x = 4242;
console.log(x);
// x is a string
x = "GeeksforGeeks";
console.log(x)
// x is an object
x = {
k: 4245,
a: "geeks"
};
console.log(x)
Output
4242
GeeksforGeeks
{ k: 4245, a: 'geeks' }
typeof Operator
The typeof helps to determine the type of a variable in Javascript. Since Javascript is a dynamically typed programming language, typeof can be used to find the variable type.
It can be used within a function to check the data type of a variable or to check if a variable is declared. Let's consider the following examples to understand this better.
let x = 12345;
console.log(typeof(x));
Output
number
Example 2: In this example, we print the type of a string in the console.
let x = "GeeksforGeeks";
console.log(typeof(x));
Output
string
Output:
stringExample 3: In this example, we print the type of various variables in the console.
let x = { k: 12, m: "geeky stuff" }
console.log(typeof (x))
console.log(typeof (x.k))
console.log(typeof (x.m))
console.log(typeof (x.s))
Output
object number string undefined
A common use of typeof operator is to determine the variable type and perform actions accordingly within a function.
Example: Invoke the above function with a number and string as an argument. Another use of the typeof operator is to check if a variable is declared before its usage.
function doX(x) {
if (typeof (x) === "number") {
console.log("x is a number")
}
if (typeof (x) === "string") {
console.log("x is a string")
}
if (typeof (x) === "undefined") {
console.log("x is undefined")
}
}
doX(12)
doX("hello gfg")
Output
x is a number x is a string
Example: Invoking the above function without passing an argument and by passing a string as an argument.
function checkX(x) {
if (typeof (x) === "undefined") {
console.log(
"x is undefined. Please declare it");
} else {
console.log("We can process x!")
}
}
checkX()
checkX("hello")
Output
x is undefined. Please declare it We can process x!
Example: One small caveat with typeof is that typeof(NaN) returns a number. When we multiply a string with a number we get NaN, as seen in the below example.
let x = "hello"
console.log(x)
let y = 10
console.log(y)
z = x * y
console.log(z)
console.log(typeof (z))
Output
hello 10 NaN number