Now that we’ve talked about variables, let’s talk about what types of data those variables can hold. First, lets talk about typeof. typeof is an operator — like +, -, or =. 2 + 2 returns 4. typeof returns the type of the value we ask it about. What does that mean? It’s a lot less confusing than it looks:
// -> 'number'
For those of you in doubt, 2 is indeed a number. Thanks, typeof.
Open your console and try it out. We’re going to be using typeof throughout this lesson so get familiar with it now.
🚩Q: Why is typeof a word and not a symbol? Aren’t most operators symbols?
A: Because all the cool keyboard symbols were already taken. Probably.
// -> "number"
// -> 9007199254740991
That’s the largest number the Number data type can hold. If it’s below 9,007,199,254,740,991, or 9 quadrillion, you should be fine. If you need to use larger numbers, use BigInt. I won’t go further into that though; for most of our purposes Number is fine.
var bigNumber = 100;
But what happens if we want a variable to be equal to a word? Let’s try it out:
var favoriteAnimal = fish;
// -> fish is not defined
var favoriteAnimal = "fish"
// -> undefinedfavoriteAnimal;
// -> "fish"
And what’s the typeof “fish”?
// -> "string"
It’s a string. And notice the word “string” is surrounded by quotation marks; typeof’s return value is also a string! A string can includes spaces and other characters:
var sentenceString = "This is a string. It can include numbers: 1, 2,3; and symbols: _ + ^ *. It can be as long as you want.";
// -> undefinedsentenceString;
// -> "This is a string. It can include numbers: 1, 2,3; and symbols: _ + ^ *. It can be as long as you want."
You can also use single quotation marks:
var singleQuotationMarks = 'This works too.';
What happens if you need to use quotation marks inside of a string? You have a few choices, but I recommend for now you use the opposite of what you want to use on the inside:
var thisIsFine = "You can use single 'quotation marks' inside of double quotation marks, and vice-versa";
🚩Note: numbers in strings are not numbers, but rather characters. Don’t use them like real numbers or weird things may happen:
"2" + 2;
//-> "22" (!?)
We’ll talk about why later.
// -> "boolean"
Null & Undefined
Null is the intentional absence of a value. Undefined is the value of a variable that has not been assigned another value. They are different, but I won’t go over the differences here. Just remember to assign your variables values and you’ll be good:
var undefinedVariable;typeof undefinedVariable;
// -> "undefined"undefinedVariable = "this value is now defined. Unfortunately, the variable's name is now confusing";typeof undefinedVariable;
// -> "string"var nullVariable = null;typeof nullVariable;
//-> "object" (!?)
Most of the above code should make sense. But what about that last line? That’s for next time, where we’ll learn about objects and arrays.