Site icon codippa

How to check the type of a value in javascript / How to check type of a variable in javascript

Overview

Determining the type of a value stored inside a variable is very important in any programming language but in javascript, it is extremely important. This is because a javascript variable can hold values of many types and just by looking at the variable definition, you cannot tell the value which it shall hold. Without knowing the type of value, operations performed on them can lead undesired result. Example, a variable can be written as :

var x = 25;
var x = “codippa”;

Suppose you are adding 5 to the value of v, then it does not make any sense to perform add operation if the value of v is “codippa” and can lead to undesirable results. Thus it is necessary to check the type of value in a variable so that application performs as expected.

How to check type of a value

Javascript has a built-in typeof operator which returns a string representing the data type of the value being checked. Syntax of typeof is

typeof operand

where operand is the value or variable whose type is checked by typeof.

Value Types in javascript

Javascript has a wide range of data types. They are:

  1. String : Represents string values. Example, ‘codippa’, “java”, “javascript” etc.
  2. Number : Represents a numeric value. It can be an integer, a decimal or a fraction. Example, 10, 4.5, 5/6 etc.
  3. Boolean : A true or false value.
  4. Undefined : When variable has not been assigned a value, it is undefined.
  5. Null : Represents a null value.
  6. Object : There are many types which are objects in javascript. These include Arrays, Functions, Date, Regular Expression etc.

Possible return types of typeof

Following table shows the actual data type of a value(from among those described above) and its corresponding value returned by typeof operator

Data Type typeof Return Value
String “string”
Number “number”
Boolean “boolean”
Undefined “undefined”
Null “object”
Object(Function, Array, Date etc.) “object”

typeof Examples

Following is a collection of some examples of typeof usage on values of different data types and the value returned by typeof. First column shows the usage of typeof on values of various data types, Second column represents the actual data type of the value whose type is checked and Third column contains the string returned by typeof operator on this value.

Expression Actual Data Type typeof Return Value
typeof ‘codippa’ String “string”
typeof 50 Number “number”
typeof true Boolean “boolean”
typeof undefined Undefined “undefined”
typeof function(){ } Function “object”
typeof (33) “Number” “number”
typeof new Date() Object “object”
typeof null Object “object”
typeof Number(6) Number “number”

Hope this post made you learn something about checking the type of a value in javascript.

Exit mobile version