Declaring and Using Variables

Checking a Variable Type

🙋 Need help? Ask an expert now!

Getting a basic idea of the data type of a variable is pretty simple in JavaScript. JavaScript has an operator called typeof that can be used to checked the variable type during runtime. typeof returns a string of the value's data type, which can be convenient and necessary at times. The sample code below show 4 examples of the typeof operator, the last two being special cases.

As you can assume from the first example of the typeof, it returns "number" for any numbers, "string" for any strings, and "object" for any objects. If a data type is called using an object like the second example above, the data type of the variable will be an object. The last two cases are special cases that you probably won't encounter as often as the others. The value "null", which is given to an object that hasn't been assigned to any value, is actually classified as an object according to JavaScript. On the other hand, variables that are assigned "undefined" have a data type "undefined", which you will probably never use while coding. Keep the two special cases in mind as you move on and make sure you understand how the typeof operator works.

Edit Me on GitHub!

Application Question

Consider the following code segment:

let sum = new Number(505);
            console.log(typeof sum);

What does the code above print to the console?