How to get datatype in JavaScript
By FoxLearn 11/18/2024 6:47:07 AM 85
How to get datatype in JavaScript?
1. Using typeof
Operator
The JavaScript `typeof` operator is used to determine the type of a variable or value. It returns a string indicating the data type, such as `"number"`, `"string"`, `"boolean"`, `"object"`, `"undefined"`, or `"function"`.
For example get data type javascript:
typeof 42 // "number" typeof 'hello' // "string" typeof true // "boolean" typeof undefined // "undefined" typeof {} // "object" typeof [] // "object" typeof null // "object"
In JavaScript, when a variable is declared but not assigned a value, its value is automatically set to `undefined`. The type of such a variable is also `undefined`.
let product; // Value is undefined, type is undefined
An empty string (`""`) is a valid value in JavaScript with a specific type of `string`. It's different from `undefined`, which indicates a variable has no value assigned. An empty string is not the same as `undefined`.
let product = ""; // The value is "", the typeof is "string"