typeof
returns the primitive data type but I am not getting why it is used in javascript?
The typeof operator returns a string indicating the type of the operand's value.
The Data Type of typeofThe typeof operator is not a variable. It is an operator. Operators ( + - * / ) do not have any data type. But, the typeof operator always returns a string (containing the type of the operand).
Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.
The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
I am not getting why it is used in javascript?
typeof
is used to
return[s] the primitive data
For example, if I wanted to know if something was undefined, I could do
if (typeof object === 'undefined')
to check because if it is undefined there is no datatype (because it's undefined). This is generally why typeof
would be used other than for logging purposes, to see what is received through ajax, or for making functions that accept a parameter that can have different types and checking that type with typeof
, etc.
typeof is an unary operator that is placed before a single operand which can be of any type. Its value is a string that specifies the type of operand.
- x typeof x
undefined "undefined"
null "object"
true or false "boolean"
any number or NaN "number"
any string "string"
any function "function"
any non function native object "object"
The typeof works sufficiently well with primitive values except null.typeof cannot distinguish between null & object because null is falsy & objects are truthy.Here are few case studies which may be useful. typeof evaluates to object for all object and array values other than function.How typeof
deals with function is probably beyond the scope of this question.
Hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With