When working with variables, you have to think about the data types you want. While you don’t have to define the data types for any of your variables, it’s always good to know what data type your variable is.
What are data types?
In programming, all data you create can be categorized into what kind of data it is. Is it a string, integer, boolean, or an object? There are different kinds of data types. Here is what they are.
- String – a variable that can store a set of characters. Characters are basically the keys on your keyboard. Every letter, number, and special characters are considered all characters. A string is a group of these characters.
- Numbers – Any number from negatives to positives and decimals are also numbers.
- Boolean – Boolean variables are values that are either true or false.
- Undefined – A variable that isn’t defined or has no value at all.
- Null – A variable that is empty and is meant to be empty.
This can be a bit confusing so let’s see what they look like. Open up your script.js file and replace it with this bit of code.
var ex_1 = 'This is a string'; // This is a string.
var ex_2 = 15; // This is a number.
var ex_3 = -3.5; // This is a number.
var ex_4 = true; // This is a boolean.
var ex_5; // This is undefined.
var ex_6 = null; // This is a null
Boolean values are either true of false. You use these kinds of values when you need to do conditional checks. You’ll see boolean values in action when we discuss conditional statements in a future tutorial.
Dynamic Data Types
Variables don’t have to be a certain data type forever. You can overwrite a variable’s data type and value. Here’s how you would do that. Add this bit of code in your script.js file.
var ex_7 = 5; // This is a number.
ex_7 = 'Overwritting this value'; // This is a string now.
Knowing what data type your variables are is important. We’ll be using all the data types in this tutorial series. There are actually more data types such as arrays and objects, but those are a bit advance. We will be discussing what those are and how to use them in future tutorials. If you don’t fully understand how to use these data types, then don’t worry. We’ll be practicing with them a lot and you will understand their purpose in our programs.