JavaScript typeof operatorThe JavaScript typeof operator is used to return a string that represents the type of JavaScript for a given value. It returns the data type of the operand in the form of a string. The operand can be a literal or a data structure like a function, an object, or a variable. SyntaxThere are following two ways of using the typeof operator. Valuesoperand: It is an expression that represents the object or primitive whose type is to be returned. The possible return values of the typeof operator are tabulated as follows:
Let's understand this operator by using some examples. Example1In this example, the operands are of number type. The typeof operator will print the "number" as the type of the operand, whether the operand is a negative interger, floating-point number, infinity, NaN, zero, or any integer. Test it NowOutput After the execution of the above code, the output will be - number number number number number number Example2In this example, the operands are of string type. The typeof operator will print the "string" as the type of the operand, whether the operand is an empty string, collection of characters, number written in quotes. Test it NowOutput After the execution of the above code, the output will be - string string string string string Example3In this example, the operands are of Boolean type. The typeof operator will print the "boolean", as the type of the operand, if the operand is true, or false. Test it NowOutput After the execution of the above code, the output will be - boolean boolean boolean Example4In this example, the operands are of undefined type. The typeof operator will print the "undefined" as the type of the operand. Here, the type of Null is undefined, it is because it is written as Null instead of null. If we write it as null, the type of it will be object. Test it NowOutput After the execution of the above code, the output will be - undefined undefined undefined Example5In this example, the operands are of Object and Function type. The typeof operator will print the "object" and "function", according to the type of the operand. Test it NowOutput After the execution of the above code, the output will be - object object object object function function Next TopicJavaScript ternary operator |