Knowing data types and which one to use is an important aspect of programming. Javascript has five different, basic types: numbers, strings, booleans, objects, functions and symbols. Functions, in Javascript, are a special kind of object, as are undefined, null and the Date object. If you would like to learn more, you can find a list of links under the ‘Resources’ headline. What about arrays? Well, arrays are actually objects in Javascript.
The MDN, or Mozilla Developer’s Network, is a great tool that you can use if you would like to learn more about Javascript. In this post, we will take a look at how we can check the value of the variable and the data type that it belongs to.
Checking the Data Type
We should learn (or re-learn) how to check the data type of a variable and the value contained within. Let’s bring up the Console first. You can do this in Chrome, Firefox and Safari by right-clicking on the page and choosing the ‘Inspect Element’ option:
This is what the Chrome ins
You have two ways to access the console, you can click on the tab located in the toolbar:
Or you can press the ESC key to bring it up in the Elements section.
Checking the Value
If we would like to check the value contained within a variable, then we can use the console.log() method to print to the console. You should
var hello = "Hello World"; console.log(hello); // output: "Hello World"
In the console:
Check the Data Type
If you would like to check for the data type that a variable belongs to, then you can use the typeof operator.
var hello = "Hello World"; console.log(typeof hello); //outputs "string"
Here are some examples of the code in the console.
Another example:
Important: Javascript can actually change the data type behind the scenes, so make sure to check, or even double-check, your variables and the data type that they belong to. Instead of reporting an error when Javascript has come across an unexpected data type, it will convert the value to another data type instead.
Truthy vs. Falsy
In Javascript, there are truthy and falsy values that can produce unique and interesting results. This is one of the “gotchas” that you might seem confusing at first. In order to learn more about these values, you should read Sitepoint’s Truthy and Falsy: When All is Not Equal in Javascript.