Typeof
typeof
is a reserved keyword in JavaScript that does exactly what it says: it returns the type of the value in question. The proper syntax is typeof x
. Consider the following:
Using typeof
on x, y, and z would return "number", "string", and "boolean", respectively. Other types that can be returned are function, object, and undefined. When dealing with a value that MUST be a specific type, it can be very helpful to pass it through typeof
first in order to verify the type. You can then use conditionals to determine the correct option for the code for that value type.
File Location
We will be working in the following file:
Practice
In
typeof.js
, create several variables and give them different value types. Use typeof on each to print the type to the console.Write a program that has different outcomes depending on the type of value used. You can use
if/else
,switch
, or ternary operators. For an extra challenge, do all 3!
Last updated