New terms from treehouse – Javascript Foundations Part 1 – Variables and Strings

Variables

Basics

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.

Screen Shot 2014-07-09 at 11.11.45 AM

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.

Screen Shot 2014-07-09 at 11.18.18 AM Screen Shot 2014-07-09 at 11.18.11 AM

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.

Screen Shot 2014-07-09 at 11.17.02 AM Screen Shot 2014-07-09 at 11.16.46 AM

We can do a similar line to change the text color.

Screen Shot 2014-07-09 at 11.19.17 AM Screen Shot 2014-07-09 at 11.19.13 AM

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.

Screen Shot 2014-07-09 at 11.21.40 AM


Naming Rules

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.

Screen Shot 2014-07-09 at 11.41.32 AM Screen Shot 2014-07-09 at 11.41.24 AM

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.

Screen Shot 2014-07-09 at 11.43.26 AM Screen Shot 2014-07-09 at 11.43.31 AM

Screen Shot 2014-07-09 at 11.44.33 AM Screen Shot 2014-07-09 at 11.44.41 AM

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.Screen Shot 2014-07-09 at 11.48.40 AMScreen Shot 2014-07-09 at 11.50.28 AM Screen Shot 2014-07-09 at 11.51.54 AM

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.

Screen Shot 2014-07-09 at 11.54.27 AM


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.

Screen Shot 2014-07-09 at 2.27.22 PM Screen Shot 2014-07-09 at 2.28.05 PM

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.

Screen Shot 2014-07-09 at 2.32.00 PM Screen Shot 2014-07-09 at 2.32.05 PM

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.

Screen Shot 2014-07-09 at 2.33.56 PM Screen Shot 2014-07-09 at 2.34.06 PM

Another way to test for undefined is to use === to directly compare the variable with the keyword undefined.

Screen Shot 2014-07-09 at 2.36.12 PM Screen Shot 2014-07-09 at 2.36.18 PM

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.

Screen Shot 2014-07-09 at 2.39.55 PM Screen Shot 2014-07-09 at 2.40.09 PM

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.

Screen Shot 2014-07-09 at 2.42.55 PM Screen Shot 2014-07-09 at 2.43.02 PM

Null and undefined are very similar. if we do x == null in the argument, it will evaluate to true.

Screen Shot 2014-07-09 at 2.45.58 PM Screen Shot 2014-07-09 at 2.46.02 PM

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.

Screen Shot 2014-07-09 at 2.47.47 PM

The === operator is much stricter and will not change values if they’re close to each other.

Screen Shot 2014-07-09 at 2.48.49 PM

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.


Scope

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.

Screen Shot 2014-07-10 at 9.58.48 AM Screen Shot 2014-07-10 at 9.58.56 AM

 

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

Screen Shot 2014-07-10 at 10.05.38 AM Screen Shot 2014-07-10 at 10.05.32 AM

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.

Screen Shot 2014-07-10 at 10.12.07 AM 1 Screen Shot 2014-07-10 at 10.12.25 AM

 

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.


Shadowing

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.

Screen Shot 2014-07-10 at 10.32.39 AM Screen Shot 2014-07-10 at 10.31.45 AM

 

 

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 ().

Screen Shot 2014-07-10 at 10.39.25 AMScreen Shot 2014-07-10 at 10.39.51 AM

 

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.

Screen Shot 2014-07-10 at 10.47.59 AM Screen Shot 2014-07-10 at 10.44.52 AM

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.

Screen Shot 2014-07-10 at 10.54.33 AMScreen Shot 2014-07-10 at 10.54.41 AM

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.

Screen Shot 2014-07-10 at 10.58.19 AM Screen Shot 2014-07-10 at 10.58.11 AM

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.

Screen Shot 2014-07-10 at 11.00.27 AMScreen Shot 2014-07-10 at 11.00.33 AM


Hoisting

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.

 Screen Shot 2014-07-14 at 1.26.57 PM Screen Shot 2014-07-14 at 1.25.12 PM

 

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.

Screen Shot 2014-07-14 at 1.25.04 PM

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.

So this:

Screen Shot 2014-07-14 at 1.32.57 PM

Actually means this:

Screen Shot 2014-07-14 at 1.34.16 PM

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.

So this:

Screen Shot 2014-07-14 at 1.39.22 PM

Equals this:

Screen Shot 2014-07-14 at 1.39.37 PM

You can have and mix and match as many as you want, and even initialize variables (meaning set a value for them) with it.

Screen Shot 2014-07-14 at 1.40.45 PM

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.

Screen Shot 2014-07-14 at 1.42.17 PM


Strings

Basics

Strings are how we represent text in JS.  You can define a string with double quotes or single quotes.

Screen Shot 2014-07-16 at 2.17.46 PM Screen Shot 2014-07-16 at 2.17.55 PM

 

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.

Screen Shot 2014-07-16 at 2.19.44 PM Screen Shot 2014-07-16 at 2.21.07 PM

Similarly, if you want to use quotes, you should use single quotes.

Screen Shot 2014-07-16 at 2.22.41 PM

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.

Screen Shot 2014-07-16 at 2.26.23 PMScreen Shot 2014-07-16 at 2.26.35 PM

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.


Escape characters

What happens if you need a backslash in your string, for like a file pathway?

Screen Shot 2014-07-16 at 2.30.51 PM Screen Shot 2014-07-16 at 2.31.02 PM

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.

Screen Shot 2014-07-16 at 2.34.44 PM Screen Shot 2014-07-16 at 2.34.48 PM

 

Now, what about a string with multiple lines? If we try this we get an error.Screen Shot 2014-07-16 at 2.37.17 PM Screen Shot 2014-07-16 at 2.37.43 PM

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.

Screen Shot 2014-07-16 at 2.39.50 PMScreen Shot 2014-07-16 at 2.39.55 PM

One last special character is the tab character. To insert a tab, do \t.

Screen Shot 2014-07-16 at 2.41.49 PMScreen Shot 2014-07-16 at 2.41.55 PM


Concatenation

Concatenation is when you join two strings together. You can do this with the + operator.

Screen Shot 2014-07-16 at 2.46.43 PM Screen Shot 2014-07-16 at 2.46.37 PM

Besides variables, you can also concatenate string literals.

Screen Shot 2014-07-16 at 2.48.09 PM Screen Shot 2014-07-16 at 2.46.37 PM

You can do this anywhere you have a string.

Screen Shot 2014-07-16 at 2.49.02 PM Screen Shot 2014-07-16 at 2.49.07 PM

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.

Screen Shot 2014-07-16 at 2.50.47 PMScreen Shot 2014-07-16 at 2.50.57 PM

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.

Screen Shot 2014-07-16 at 2.52.35 PM


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.

Screen Shot 2014-07-22 at 1.15.19 PM Screen Shot 2014-07-22 at 1.15.03 PM

 

Remember we can pass both in the same console.log to see them both.

Screen Shot 2014-07-22 at 1.17.48 PM Screen Shot 2014-07-22 at 1.17.24 PM

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.

Screen Shot 2014-07-22 at 1.23.08 PM Screen Shot 2014-07-22 at 1.23.03 PM

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.

Screen Shot 2014-07-22 at 1.26.05 PM Screen Shot 2014-07-22 at 1.26.38 PM

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.

Screen Shot 2014-07-22 at 1.29.36 PM Screen Shot 2014-07-22 at 1.29.46 PM

 

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.

Screen Shot 2014-07-22 at 1.36.04 PM Screen Shot 2014-07-22 at 1.35.30 PM


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.

Screen Shot 2014-07-22 at 1.41.10 PM Screen Shot 2014-07-22 at 1.41.05 PM

 

If we change the start index or string length, we get a different result:

Screen Shot 2014-07-22 at 1.42.18 PM Screen Shot 2014-07-22 at 1.42.26 PM

 

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.

Screen Shot 2014-07-22 at 1.45.02 PM Screen Shot 2014-07-22 at 1.44.58 PM

Note that this doesn’t actually change our original string in the variable “whole”.

Screen Shot 2014-07-22 at 1.46.00 PM Screen Shot 2014-07-22 at 1.46.10 PM

 

The toUpperCase method does what you’d expect.

Screen Shot 2014-07-22 at 1.47.04 PM Screen Shot 2014-07-22 at 1.47.11 PM


Comparing Strings

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.

Screen Shot 2014-07-22 at 1.56.27 PM Screen Shot 2014-07-22 at 1.56.34 PM

 

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.

Screen Shot 2014-07-22 at 1.58.53 PM Screen Shot 2014-07-22 at 1.59.01 PM

 

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.

Screen Shot 2014-07-22 at 2.04.29 PM Screen Shot 2014-07-22 at 2.04.25 PM

 

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.

Screen Shot 2014-07-22 at 2.05.59 PM Screen Shot 2014-07-22 at 2.05.53 PM

Screen Shot 2014-07-22 at 2.07.00 PMWe 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.

Screen Shot 2014-07-22 at 2.10.15 PM Screen Shot 2014-07-22 at 2.10.38 PM

 

What about if one string is a substring of the other? Whatever one runs out of letters first is the smaller one.

Screen Shot 2014-07-22 at 2.12.28 PM Screen Shot 2014-07-22 at 2.12.10 PM

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s