Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of typeof in javascript?

typeof returns the primitive data type but I am not getting why it is used in javascript?

like image 283
Rohit Goyal Avatar asked Nov 12 '15 03:11

Rohit Goyal


People also ask

What is the use of typeof () function?

The typeof operator returns a string indicating the type of the operand's value.

What is typeof method?

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).

How do I get typeof in JavaScript?

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.

What kind of operator is typeof?

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.


2 Answers

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.

like image 182
Cilan Avatar answered Oct 08 '22 21:10

Cilan


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.

like image 37
brk Avatar answered Oct 08 '22 19:10

brk