Variables allow us to store and retrieve data in our programs. Since JS is dynamically typed, when we create a variable we just need to give it a variable and a name. In other languages that are instead statically typed, each variable must have a specific type associated with it.
Once again, to set a variable you type the keyword var, which says you’re declaring a variable, then the name you want to give it, then you set it equal to its value. The value can be whatever you want, like a string, number, array, mathematical expression, result of a function call etc.
To show a real use case, we’ll manipulate the color and bg color of a div using JS. document is a variable that’s built into the web page that represents it. On that we call a method getElementById that returns the element with the id listed. Then, there’s an object called style with a property called background that we can either read to see what the current background is, or write a new one.
Now, when you first try this it doesn’t work because the script tag linking the JS file is put in the markup before the div itself. If you put it after, then it will work. This let’s the whole page load before any JS interaction, which makes things load a bit faster.
We can do a similar line to change the text color.
Now, this isn’t a very good way to code. We have a lot of repeating code. Instead, let’s make a variable to take some of that out.
The names of variables should be descriptive of what their value is. If you give it a meaningless name, it will be hard to understand in the code later. Here are the rules:
Can start with A-Z a-z _ or $
Can continue with A-Z a-z 0-9 _ or $
Note that you cannot start a variable name with a number. If you have an invalid variable name in your code, you’ll see an error in the JS console.
If you use a character you shouldn’t, like a % or -, you get this. It makes sense – doesn’t work, because that’s the sign in JS for subtraction.
There are some words you can’t use as variable names because they’re reserved for other uses in the JS language. For instance, any of the JS keywords like if, else, function, continue, etc. For a complete list go here. Reserved words will be highlighted and will cause an error.
There are also some words that are reserved for possible future use, which are the black ones in the list above. There are keywords that are new features in JS, that might work in some browsers but not all.
Null and Undefined
When declaring a variable you do not actually need to give it a value right away – you can leave off the equal sign and the value. If we test this in the JS console, we get the value undefined.
undefined represents a non value that was never defined. null is another value that you can use to indicate that a variable is empty is with no value, and not empty by default. To determine if a variable is defined, you can use the typeof operator followed by the name of a variable in console.log.
To test specifically if it’s undefined, use === to compare it to the string “undefined”. Since it is in this case, this will evaluate to true. === compares and tests for equality.
Another way to test for undefined is to use === to directly compare the variable with the keyword undefined.
undefined in JS is weird as a keyword in that it’s not actually a keyword at all, but rather a variable that’s set by JS. This means it’s possible to actually overwrite the value of undefined. If you do this, apparently it will make the second line false, though that didn’t work for me. Because of this, it’s best to just use the typeof operator instead.
You can set variables to null with the null keyword. Both null and undefined are false e values, which mean if won’t execute. If we were to put in x instead of myVar it would give the same result.
Null and undefined are very similar. if we do x == null in the argument, it will evaluate to true.
However, if you were to do myVar == null, it would also evaluate to true, because == is not that strict. Since they’re so similar, it considers them to be the same and changes them to be so.
The === operator is much stricter and will not change values if they’re close to each other.
For the most part you want to use === because you don’t want it changing variables on you. Using == is good for a special use case where you just want to know if something it either undefined or null.
When you create a variable, you can’t always use that variable at any point in your code. Variables belong to a scope, and that scope determines where your variable is usable. Variables themselves are limited to where the can be used. If you create a variable in a function, you can only use that variable within that function.
Let’s create a variable called world that contains a string. Next, we’ll make a function called sayHello. Note that he’s doing this very differently then we did before where we’d define a variable and set it equal to a function. In the function we’ll define a second variable then use a console.log that combines that with the first variable. Then we’ll invoke the function by writing it’s name followed by two parentheses.
Now, note that in the function, we can access the world variable that was defined outside of it, in what’s known as the global scope, meaning it can be access anywhere, from inside any function or outside any function. You want to be careful, if you have two global variables with the same name, one will overwrite the other. This can be an issue for large amounts of code.
If we try to access the hello variable outside of the function in which it was defined, we get an Uncaught ReferenceError. This tells us hello is not defined. Because we defined hello in the function, that’s the only place we’re allowed to access that variable. This is good though, because our hello variable doesn’t interact with any variables outside of it
JS lets you create functions in functions, so let’s see how this works with that. We’ll create a new function within the hello function, and declare another variable within it called extra. We’ll then use console.log to display it. Note, that for the inner function to run we need to execute it.
Note that in the second level function, we were able to use the variables declared above it, the global world one and the hello one from the parent function it’s nested in. This is how you can tell if you’re allowed to use a variable. You can use ones on the same level or above, but not ones defined below.
What happens if you define a variable with a name that was already defined at a higher level of scope? You can do that, and it’s called shadowing a variable.
We’ll start by declaring a variable, and then using console.log to show it’s value.
Now, let’s declare a variable with the same name inside of a function. Remember we need to execute the function after we write it, which we can do by writing its name followed by ().
Now the question is, is the myColor inside the function the same variable as the one outside the function in the global scope? To test this, we can do another console.log after myFunc() is executed.
It’s still blue! This is because when we created the myColor variable in the function, we were creating a completely separate variable, and this is due to how scoping of variables works. The fact that the name is the same doesn’t matter, because we can’t access that variable outside of the function. The shadowed variable inside the function isn’t overwriting it, it’s a separate variable that’s being added that’s being used by the function instead. Because of this, we’re now unable to access the global scoped myColor variable in the function.
Now, if we were to not include the var keyword, instead of declaring a local variable with the value “yellow”, it would set a new value to the global myColor variable, changing it. You can see this in the last console.log.
Another bug you may run into: Here we’ll add a new variable myNumber to the function, and not use the var keyword. Then, we’ll do a console.log to see what it displays. You can see that from the global scope you can actually access it.
This is because from within any JS function, if we assign to (which is when you give a variable a value) a variable that doesn’t exist yet, JS by default will create a global variable with than name and assign the value to it. This can be an issue with loops where you expect a variable to be reset each time, but it will maintain its state due to being global. To fix this, make sure that you declare it with the var keyword.
In the example below we have a function with an argument that will affect whether an if block runs. First it sets the variable color to blue, then if the if block runs it changes the variable color to red.
The first console.log is what happens if the if block doesn’t run, and the second two are from when it does. While you might have expected the last one to say blue, but that’s not true, because the part where they set it to red is in the same scope level, meaning the var keyword actually isn’t even necessary since we’re not declaring a new variable, we’re just changing one.
If JS was a block scope language, the color change in the if block would shadow the variable defined outside of it, but as you can see that’s not the case here. In JS, the only time you get a new level of scope is when you create a new function.
Now, let’s say we declare a new variable named number within the if block. You may think that this variable is only declared when the if block is true and runs, but that’s not the case. When JS sees a declaration like this in the middle of a function, it does something called hoisting the variable. So, you actually don’t end up declaring the variable on this line in the function, what really happens is var number is declared at the top of the function, and when you get to its line in the code, it just assigns the value to the previously declared variable.
Actually means this:
Now, you don’t need to worry about this so long as you keep all your variable declarations at the top of your function. Because in reality that kind of happens anyway, only with hoisting you’re waisting a line of code sometimes. For global variables, you’d also want to put all those declarations at the top of your document. Besides avoided hoisting, this gives the added bonus of being able to easily see all the variables you will be declaring.
There’s a way to declare multiple variables that’s a bit easier and preferable to use. Instead of using a semicolon after your first declaration, just use a comma.
You can have and mix and match as many as you want, and even initialize variables (meaning set a value for them) with it.
If you have a lot of them, you can split them onto multiple lines. It’s not necessary to indent them, but it’s good to do so you can see they’re part of the declaration started above. Make sure they are separated by commas and that the last one ends with a semi colon.
Strings are how we represent text in JS. You can define a string with double quotes or single quotes.
For the most part they’re the same, but there are cases you’ll want to use one over another. If you want to use an apostrophe, you should use double quotes because the browser will think it’s the end of your string.
Similarly, if you want to use quotes, you should use single quotes.
But what if you need both quotes and an apostrophe? For this, use the backslash character before the character that would mess up your string. This is called an escape character.
You could do the same for the double quotes if you used double quotes for the string and wanted to put quotes inside of them.
What happens if you need a backslash in your string, for like a file pathway?
Notice how the backslashes are missing, and also the f in folder, and that in the code it’s purple, which signifies that’s the character we’re escaping. \f is a special case that removes it. To fix this, just write two backslashes.
This is because you cannot create a multiline string in JS. The closing quote must be on the same line as the opening one for it to be valid. To make it multiline, use the newline character, which is \n.
One last special character is the tab character. To insert a tab, do \t.
Concatenation is when you join two strings together. You can do this with the + operator.
Besides variables, you can also concatenate string literals.
You can do this anywhere you have a string.
Remember how we couldn’t write our multiline string on multiple lines in the code? We can do it here with three different variables and concatenation.
Same result as before. To make it more readable you can now write it like this. Make sure the plus is at the end of the line, as that lets JS know that there something more.
Methods Part 1
This will cover the different methods and properties you can call on strings. For example we can use the .length property to find out the length of the string.
Remember we can pass both in the same console.log to see them both.
If we wanted to see if World was in our string, we can use the method indexOf and call it on our string. It takes an argument, which in this case is the string we want to find inside of our main string “whole”. It gives us “6” as a result, meaning that the string “world” did appear there, and 6 is the index of where it starts in the larger string. Remember, indexes start with 0, so H would be 0, e would be 1, l would be 2, etc.
What if the string it’s looking for isn’t there? Since the method is case sensitive, if we make w capital, it will not find it, and return negative one.
Because of this, we can set up an if/else block to check if this method does or does not equal negative one and act accordingly. If “W” is in the string, it will equal its index, which will not be -1 but 6 and if will run. If it isn’t in the string, it will be -1 and else will run.
Another method is charAt, which tells you the character at the index you enter as an argument. Remember how indexes work – if you want the third character you’d enter 2, because the count starts with 0.
Methods Part 2
The substr method lets you get a smaller part of your string out of the whole. It takes two parameters, the first is the index you’re starting at, and the second is the length of the string we want to retrieve after that.
If we change the start index or string length, we get a different result:
You can use the toLowerCase method to convert a string to all lower case. We need to put parentheses at the end of it, because you need those to invoke a method.
Note that this doesn’t actually change our original string in the variable “whole”.
The toUpperCase method does what you’d expect.
You can compare strings in JS, meaning you can tell if one string is less than, greater than or equal to another string. To test equality, first we’ll need two strings, then the equals operator, aka the ===. Remember, the one with three is more strict than the one with two (==), which considers null and undefined to be the same thing.
So, the equality operator (===) keeps case in mind as well. If you wanted to compare them without having to worry about case, you can use the toUpperCase and toLowerCase methods we saw before, usually the lowercase one.
There are four other comparisons we can use: less than <, greater than >, less than or equal to <=, and greater than or equal to >=.
We’ll start by making a function that will say the two strings it’s comparing, then say if the first is less than the second. We’re plugging in for a and b here.
If we actually plug in a lowercase a and b, it comes out to true, because a comes before b in the alphabet.
However, a is NOT less than uppercase A, due to how strings are encoded and compared. The upper case version is always less than the lower case version. This is because it’s roughly based off the ASCII table. You can see A has a value of 65, while a has a value of 97.
We can compare longer strings too. It first look at the first characters to determine which is greater or lesser. It will only needs to go to subsequent letters if the first one is the same for both. In the example below, the ii in applications and the e in apples are what is compared.
What about if one string is a substring of the other? Whatever one runs out of letters first is the smaller one.