New terms from treehouse – Javascript Foundations Part 2 – Numbers and Arrays

Numbers

Creating Numbers Part 1

The basic way is to literally type a number 0-9. Type negative numbers with a minus sign. Fun trick: you can call a variable in the console to see its value. The examples below are whole numbers. Notice how we declared two different variables using one keyword with the comma between them.

Screen Shot 2014-07-23 at 10.40.00 AM Screen Shot 2014-07-23 at 10.38.40 AM

You can use decimals as well to create floating point numbers.

Screen Shot 2014-07-23 at 10.41.36 AM Screen Shot 2014-07-23 at 10.41.32 AM

An important point to consider when comparing whole and floating point numbers is that they’re different, which matters for certain languages. Whole numbers might be considered an integer, while the decimals are floating point. In JS though there is only one kind of number – floating point. So 11 is really 11.0. In a language where you have integers, if you divide two integers, even if there is a remainder it will be rounded up or down into another integer.

There is an error you need to watch out for in JS because all numbers are floating point though. Let’s say we want to multiply two variables together, which are .1 and .2. You’d expect .02, but you really get: 0.020000000000000004, which is a rounding error. This is a result of how numbers are stored on the computer. Because each number has a very small amount of space to store its representation on a computer, there’s an infinite amount of numbers that could be represented using this decimal notation, some rounding has to occur, and usually you can see this when you multiply numbers like 0.1 and 0.2 together. You get a result that’s very close to what you’d expect, but not quite.

This doesn’t happen with whole numbers as much though.

Screen Shot 2014-07-23 at 10.56.11 AM Screen Shot 2014-07-23 at 10.55.37 AM

To get around this, you can either manually round your results, or, if you’re doing currency with cents, you can represent money in cents rather than dollars and cents. So 1050 cents instead of 10.50.


Creating Numbers Part 2

You can create numbers using a different kind of literal, and this is useful for large numbers. To write 1 million, we can write 1000000.

Screen Shot 2014-07-23 at 11.06.38 AM

But this sucks, that’s a lot of zeroes to manage. Instead, we can write an exponential representation of this number. Simply put E then the number of zeroes you want. 1E6 is a million. You can do other numbers, for example 123E6 is 123 million. 1.23E6 would be 1.23 times ten to the 6 power, giving you 1,230,000.

Screen Shot 2014-07-23 at 11.09.35 AM Screen Shot 2014-07-23 at 11.09.31 AM

This lets us create very large literals in our code. It’s great because it’s easier to read, and less error prone in our code.

Screen Shot 2014-07-23 at 11.11.53 AM Screen Shot 2014-07-23 at 11.12.00 AM

Now, what if we write 012?

Screen Shot 2014-07-23 at 11.14.36 AM Screen Shot 2014-07-23 at 11.14.24 AM

You’d think it’d end up being 12, but it actually ends up being 10. Because our JS literal began with the number 0, it’s being interpreted as an octal number. Normally we think of numbers in the base 10 decimal system, which goes from 0-9, then when you go above 9 you put a 1 in front and start again. In octal, each place instead represents and power of 8, so it uses the numbers 0-7, so when you go above 7, it adds a one and then a 0, like in base ten when you go above 9. Even though it’d look like 10, it would mean 8.

So in the 012 example above, the 1 actually means 8, and the 2 means 2, and 8 plus 2 equals ten. Avoid typing the 0 first, it changes the base and this can mess you up.

Now, if you wrote 019 it gets even worse because 9 is not in the octal notation. The result it gives you is 19 though because JS recognizes that 9 is an illegal octal character, so it just auto assumes you mean decimal/base 10 and gives you that.

Screen Shot 2014-07-23 at 11.20.20 AM Screen Shot 2014-07-23 at 11.20.27 AM

JS can also handle hexadecimal numbers, which are base 16. We know these from color values for CSS. ff for example would represent 256, because each one goes from 0-f, meaning 16 possible options, and 16 x 16 = 255 and not 256 because you need to remember 0 is a number too.

To write in hex, start with 0x, then write the hex value after. Remember, because it’s base 16, 10 in hex = 16.

Screen Shot 2014-07-23 at 11.27.23 AM Screen Shot 2014-07-23 at 11.27.19 AM


Parsing Numbers from Strings

Let’s say you have the string “197” – if you wanted to get a real number out of it for calculations and stuff, you could the method parseInt(). You then put the string inside of it and it will give you an integer back.

You can also do parseFloat(), which will return you a number with the floating point decimal.

Screen Shot 2014-07-23 at 2.39.26 PM Screen Shot 2014-07-23 at 2.41.14 PM

Calling k now gives us a number that we can use for calculations.

Screen Shot 2014-07-23 at 2.42.22 PM

If we do parseInt(“012”) we get 12, even though we wrote it in octal notation. This is because modern browsers assume you wanted the base 10 notation. To help clarify which notation you want, add the radix, which is the base of the number system we want to parse. For example, if you wrote 10, it would be base 10.

Screen Shot 2014-07-23 at 2.46.09 PM Screen Shot 2014-07-23 at 2.46.03 PM

So, anytime you use parseInt, make sure to specify the second argument for base 10. Older browsers won’t auto set it to base 10 for you, so do this just to be safe.

You can parse binary as well, just set the radix to base 2. Keep in mind this means you can only use 0 and 1.

Screen Shot 2014-07-23 at 2.51.02 PM Screen Shot 2014-07-23 at 2.51.30 PM

Now, what if the string we’re parsing has words in it? So long as it starts with numbers we’re good, but if the numbers are in the middle we’ll get NaN (Not a Number).

Screen Shot 2014-07-23 at 2.55.34 PM Screen Shot 2014-07-23 at 2.55.42 PM

If you try and do any kind of mathematical operation (addition, subtraction, etc) with NaN you’ll still end up with NaN.

To check for NaN, if we try console.log(ll === NaN) we’d expect true, but we actually get false. This is because NaN has the curious property of not being equal to itself.

Screen Shot 2014-07-23 at 2.58.57 PM Screen Shot 2014-07-23 at 2.59.26 PM

What you need to do instead is use a function called isNaN. It takes a parameter in its parentheses, which it will then check to see if it is NaN.

Screen Shot 2014-07-23 at 3.01.28 PM Screen Shot 2014-07-23 at 3.01.33 PM

The parseFloat() function acts just like parseInt.  Like before, it will work in a string with words, so long as the string starts with the number and not the words, otherwise it will return NaN.

Screen Shot 2014-07-23 at 3.03.15 PM Screen Shot 2014-07-23 at 3.03.08 PM

It’s worth noting though, you don’t need to specify the radix for this, as it will auto assume base 10.


Operators

We can add numbers and/or variables together.  You can also mix and match integer and floating point numbers.

Screen Shot 2014-07-23 at 3.12.59 PM Screen Shot 2014-07-23 at 3.12.47 PM

Subtraction (-) works exactly how you’d expect, as does multiplication (*) and division (/). Note how multiplying floating point numbers gives us that weird issue where it’s slightly off.

Screen Shot 2014-07-23 at 3.16.29 PM Screen Shot 2014-07-23 at 3.16.46 PM

 

When we divide numbers and they don’t come out evenly, a couple things could happen depending on the language. Luckily, as mentioned, in JS they’re all floating point numbers, so 15/10 gives you 1.5.

The modulo (%) operator (called mod for short) gives you the remainder of a devision. So, 15 % 10 gives you 5.

Screen Shot 2014-07-23 at 3.20.28 PM Screen Shot 2014-07-23 at 3.20.36 PM

 

16 % 10 would give us 6, etc. 30 % 10 would give us 0, because 10 divides evenly into 30 with no remainder.

What about if there are multiple operators in a line? It goes based on the order of operations. First is multiplication and division, then addition and subtraction.  In the example below, first we’d multiply 2 time 3, then divide that by 4, then add 1 to it.

Screen Shot 2014-07-23 at 3.24.29 PM Screen Shot 2014-07-23 at 3.24.41 PM

 

To bypass that order, use parentheses, which will make that section be evaluated first. Below, it goes 1 plus 2, then times that by 3, then divides that by four.

Screen Shot 2014-07-23 at 3.25.56 PM Screen Shot 2014-07-23 at 3.26.05 PM

 

(1 + 2) * (3 / 4) would do the addition, then the division, then the multiplication, giving us 2.25 once again.

If you’re not sure how the order will go, check the operator precedence table.


Comparisons

Like we saw before with strings, we can compare numbers with >, <, >=, and <= operators. If we type 1 < 2 in a console.log, it will evaluate to true.

Screen Shot 2014-07-25 at 10.03.46 AM Screen Shot 2014-07-25 at 10.03.51 AM

 

We can also use == and ===. But we prefer the === because == can be weird when comparing numbers and strings. == just checks the values are the same. === checks that, but also that they’re the same type.

Screen Shot 2014-07-25 at 10.06.54 AM Screen Shot 2014-07-25 at 10.06.45 AM

 

Even so, you usually don’t want to compare a number to a string, so you should use parseInt or something to get them to be the same type of value.

Screen Shot 2014-07-25 at 10.09.49 AM Screen Shot 2014-07-25 at 10.09.45 AM

There’s also the !== is the bang equals equals operator, and means not equal. It is the opposite of ===. != is the opposite of ==.

Screen Shot 2014-07-25 at 10.11.51 AM Screen Shot 2014-07-25 at 10.11.59 AM

 

We can use these comparisons in our code for if/else blocks and other stuff.

Screen Shot 2014-07-25 at 10.14.26 AM Screen Shot 2014-07-25 at 10.14.31 AM


The Math Object

JS provides a lot of constants and functions for doing math, like rounding numbers, square roots, sin, cosine, etc. The Math object lets us do those. It has a properties and methods. The random(); method, which you need to write () to call because it’s a method, gives you a random number between 0 and 1. Note you need to refresh the page for it to generate a new number, because otherwise the script wouldn’t run again (which makes sense).

Screen Shot 2014-07-25 at 11.17.37 AM Screen Shot 2014-07-25 at 11.17.32 AM

What if you wanted a number between a different range, like 0 to 10? You would simply multiply it by 10.

Screen Shot 2014-07-25 at 11.17.37 AM Screen Shot 2014-07-25 at 11.18.56 AM

What if we wanted it to be a whole number? We could round the outcome using the .round() method.

Screen Shot 2014-07-25 at 11.21.07 AM Screen Shot 2014-07-25 at 11.21.03 AM

I did a quick example to show the before and after. All by myself too! Good job me.

Screen Shot 2014-07-25 at 11.25.31 AM Screen Shot 2014-07-25 at 11.25.27 AM

.round() rounds < .5 and >= .5 up. If you always want to round down, you can use the .floor() method. If you always want to round up, you can use the ceil() method.

Screen Shot 2014-07-25 at 11.29.09 AM Screen Shot 2014-07-25 at 11.29.03 AM

To take the power of something, use the pow() method, which takes two arguments, the base and the exponent. So if we want 2 to the 5th power, we’d write:

Screen Shot 2014-07-25 at 11.31.00 AM Screen Shot 2014-07-25 at 11.30.58 AM

To get the square root? Use the .sqrt() method, which takes one argument.

Screen Shot 2014-07-25 at 11.40.45 AM Screen Shot 2014-07-25 at 11.40.41 AM

If you ever want to see the Math methods available, just type “Math” into the console. Note that at the top it gives you constants like pi.

Screen Shot 2014-07-25 at 11.49.58 AM

Another example are the min() and max() methods, which tell you the minimum or maximum number passed as an argument in them.

Screen Shot 2014-07-25 at 11.53.25 AM

The abs() method returns the absolute value.

Screen Shot 2014-07-25 at 11.56.03 AM


Arrays

Creating Arrays

Arrays let you store more than one value in a variable, putting a list of ordered values into a single value. One variable lets you store as many objects as you’d like. Declare a variable like you normally would, then make an array using square brackets, and by separating the values with commas. Each object in there is called an element of the array.

Screen Shot 2014-07-29 at 11.12.34 AM Screen Shot 2014-07-29 at 11.12.26 AM

 

If we use .length, it will tell us how many elements exist inside of our array.

Screen Shot 2014-07-29 at 11.13.56 AM Screen Shot 2014-07-29 at 11.13.52 AM

If we were to change the number of values in our array, .length would change accordingly.

You can mix and match the types of values in your array.

Screen Shot 2014-07-29 at 11.17.49 AM Screen Shot 2014-07-29 at 11.18.20 AM

You can also add arrays inside of arrays.

Screen Shot 2014-07-29 at 11.27.29 AMScreen Shot 2014-07-29 at 11.27.49 AM

Note that using .length on y now would only return 5, as it doesn’t count the elements in any subarray.

You can also create empty arrays.

Screen Shot 2014-07-29 at 11.30.44 AM Screen Shot 2014-07-29 at 11.30.59 AM

This is the standard way to make literal arrays, which mean we use a special syntax in JS to define the array and the elements inside of it. An alternative way to create an array is with the array constructor, although this way is not recommended. It creates a new array with a given length, filled with undefined. The length is defined in the parentheses.

Screen Shot 2014-07-29 at 11.35.46 AM Screen Shot 2014-07-29 at 11.35.42 AM

You really shouldn’t use this unless you need the length to be set to something. The length will automatically increase and decrease as you add and remove elements.


Getting and Setting

We’ll start with this array.

Screen Shot 2014-07-29 at 2.45.26 PM Screen Shot 2014-07-29 at 2.45.22 PM

Arrays are accessed by their index, which is how far from the beginning of the array the element is, starting with zero. To get “hello” above, we’d use index 0. We declare a new variable and set it equal to the variable containing the array, then use square brackets to specify the index.

Screen Shot 2014-07-29 at 2.49.11 PM Screen Shot 2014-07-29 at 2.49.20 PM Screen Shot 2014-07-29 at 2.50.25 PM Screen Shot 2014-07-29 at 2.50.22 PM

This works for functions as well. We can declare a variable and pull the function from the array, then pass an argument through the new variable to use the function.

Screen Shot 2014-07-29 at 2.52.20 PM Screen Shot 2014-07-29 at 2.52.28 PM

What if we try retrieving a value that’s not in the array, by calling an index higher than values there are? We get undefined, meaning there is no value defined for index 4. This is nice, because in other languages if you did this you might get an error.

Screen Shot 2014-07-29 at 2.54.45 PM

How to set values in an array: Write the arrays name, use the square brackets to select the index of the value you want to change, then set it equal to its new value.

Screen Shot 2014-07-29 at 2.57.59 PM Screen Shot 2014-07-29 at 2.58.31 PM

But what happened to our “answer” variable from before that we set to my_array[1]? It is still set to 42, because it happened earlier in the code before we changed my_array[1]’s value. Basically answer is now what my_array[1] equaled at that time.

Screen Shot 2014-07-29 at 2.59.55 PM

What is we assign to an index that doesn’t currently have a value? Works just fine.

Screen Shot 2014-07-29 at 3.03.07 PMScreen Shot 2014-07-29 at 3.03.39 PM

But what if we used an index that was higher, meaning there were indexes between it and the starting indices? It inserts the undefined values for you.

Screen Shot 2014-07-29 at 3.05.58 PM Screen Shot 2014-07-29 at 3.05.37 PM

Neat trick – to add to the end of your array, use .length. In the example above, we added it to the 4th index. Prior to doing that, then length of the array was 4 elements. .length tells you how may elements there are, so if we used it on the array’s name it would auto add it to the end of the array, regardless of its length. So we can add to the end of it without having to know what the index would actually be.

Screen Shot 2014-07-29 at 3.09.10 PM Screen Shot 2014-07-29 at 3.09.05 PM

Screen Shot 2014-07-29 at 3.11.32 PMScreen Shot 2014-07-29 at 3.11.45 PM


Array Methods 1

The push() method lets you push a value (which is considered an argument) onto the end of an array (like how we did with my_array.length above). You put the new value you want in the parentheses. Let’s start by making an array and use the toString() method, which makes a string out of the array. Then we’ll use the push method, and see that it adds the value we passed through it, 5, to the end.

Screen Shot 2014-07-30 at 9.08.11 AM Screen Shot 2014-07-30 at 9.08.17 AM

Note that we use the .toString method because console.log happens to have a quick and would have shown us the value of the array as it ended, so both console.logs would have shown the 5.

Screen Shot 2014-07-30 at 9.11.34 AM

pop() is another method. It doesn’t actually take an argument, it instead removes and returns the last value of the array. See below how it removed the 5 from the array.

Screen Shot 2014-07-30 at 9.14.50 AM Screen Shot 2014-07-30 at 9.14.45 AM

You can continue to pop off values as much as you’d like.

Screen Shot 2014-07-30 at 9.16.17 AM Screen Shot 2014-07-30 at 9.15.49 AM

unshift() and shift() are two methods that are similar to push and pop in that they add and remove things to the list, the difference being that they work on the beginning of the list, rather than the end like push and pop. unshift() adds (prepends) a value to the beginning of the list, while shift() removes and returns it. Remember which is which by the name – unshift and push both have a u, pop and shift do not.

Screen Shot 2014-07-30 at 9.19.51 AM Screen Shot 2014-07-30 at 9.19.57 AM

Screen Shot 2014-07-30 at 9.20.56 AM Screen Shot 2014-07-30 at 9.21.03 AM


Array Methods 2

This will cover methods that let you order and sort arrays. The sort() method sorts the values within the array, changing the array. Notice how this doesn’t give us a normal numerical sort, but instead sorts as though they were strings, with it looking at the first character. It doesn’t realize that our strings are numbers and needed to be sorted numerically.

Screen Shot 2014-07-30 at 9.36.50 AM Screen Shot 2014-07-30 at 9.37.00 AM

You can change this by providing a comparator function. my_array.sort(compareFunction) sorts an array to determine its order. We pass a function to the .sort method, and that function takes to arguments from the array, represented by a and b. If a – b gives you a positive number, like 10 – 5, you know a was bigger and should comes second.. If a – b gives you a negative number, like 5 – 10, you know b was bigger and should come second. If a – b is zero, you know a = b and the order they appear doesn’t matter.

To be honest though I don’t 100% understand how writing return a – b does that. Maybe it only works for this sort method? I think it goes off of whether the result is negative, positive or 0.

Screen Shot 2014-07-30 at 9.45.39 AM Screen Shot 2014-07-30 at 9.44.57 AM

To randomize the order of the elements in the function, we can use the Math.random() method we discussed earlier, which always returns a number from 0 to 1. However, it will always give us a positive number, so to change that we can subtract -0.5, which would give us a range of -.5 to .5, so half the time we’ll get a negative number and half the time a positive number. Now, the function won’t use a and b at all for comparisons, as the result will randomly be negative or positive.

Screen Shot 2014-07-30 at 9.52.42 AM Screen Shot 2014-07-30 at 9.53.48 AM

The reverse() method simply reverses the order of elements inside of an array, changing the array.

Screen Shot 2014-07-30 at 9.56.04 AM Screen Shot 2014-07-30 at 9.56.00 AM


Array Methods 3

The methods we looked at prior actually changed the values in the array (like their order). These will not change their values, but instead will return a new array or some other value. Therefore, they’re considered “safe methods”. To join two arrays together, we use the .concat() method, which takes an argument that is the variable for the second array. So below, we call it on x, then pass in y, and it concatenates them together. You can pass multiple arguments, just separate them by commas and spaces.

Below, we create a brand new array combing the elements from x and y. Note that x and y aren’t affected in any way.

Screen Shot 2014-07-30 at 12.35.59 PM Screen Shot 2014-07-30 at 12.36.11 PM

Rather than passing a variable, we could have just written in another array as the argument, which is basically the same thing.

Screen Shot 2014-07-30 at 12.38.27 PM

You can even put non arrays in there, and they will still be added as though it were an array. Below, instead of passing one parameter, an array like above, we’re passing three separate number values. You get the same result.

Screen Shot 2014-07-30 at 12.40.37 PM

We can have arrays and numbers, and it will still add each as an element. It won’t make a sub array.

Screen Shot 2014-07-30 at 12.41.57 PM Screen Shot 2014-07-30 at 12.41.53 PM

The slice() method allows you to pull out a slice of your array, based on the start index and end index. It takes two arguments, on for each. myArray.slice(start, end). So if we wanted to pull out the 1-3 values below, we’d need to enter 1 and 4 for the indices. This is because each index is technically before the value. So if we want the fourth value, we need to call the fourth index.

Screen Shot 2014-07-30 at 12.48.45 PM Screen Shot 2014-07-30 at 12.48.51 PM

If we started at index 2, the result would change accordingly.

Screen Shot 2014-07-30 at 12.50.26 PM Screen Shot 2014-07-30 at 12.50.32 PM

If the ending index is outside the ending value of our array, it simply won’t return anything.

Screen Shot 2014-07-30 at 12.51.47 PM Screen Shot 2014-07-30 at 12.51.52 PM

The join() method returns a string containing all elements an array joined with the string separator. myArray.join(separator). So, they’ll be joined with whatever we pass into the method. You can use a space here, or anything. Or nothing, as seen in the last example.

Screen Shot 2014-07-30 at 12.57.34 PM Screen Shot 2014-07-30 at 12.57.26 PM

Now, what if we try this when there’s a non-string value? It will simply auto apply the toString() method to it, which is shown typed into the console below. It will do the same thing to numbers and functions.

Screen Shot 2014-07-30 at 1.00.38 PM Screen Shot 2014-07-30 at 1.00.34 PM

Screen Shot 2014-07-30 at 1.03.13 PM Screen Shot 2014-07-30 at 1.02.50 PM


Splice

splice is one of the most powerful array methods. Lets say we wanted to delete the number 2 in our array below. How could we do that? We can use the special delete JS keyword,

Screen Shot 2014-07-31 at 3.17.34 PM Screen Shot 2014-07-31 at 3.17.19 PM

That value is now undefined. But, what if we wanted to remove 2 and have all the elements after it move forward one index? You can use the power method splice, which you should note is different than the slice method used earlier. The first argument it takes is the index you want to operate on. The second is how many many elements after that starting index we want to operate on as well. Since we only want to remove the number 2, we’ll set the starting index as 2 and then the length as 1.

Screen Shot 2014-07-31 at 3.22.30 PM Screen Shot 2014-07-31 at 3.22.34 PM

 

Splice is commonly used to just remove one element, but you can remove more.

Screen Shot 2014-07-31 at 3.23.54 PM Screen Shot 2014-07-31 at 3.23.48 PM

splice can also be used to add things in. Let’s say we want to add “two” to the 2, without removing it. We can set the second argument to zero, since that will mean we start as the second index but then move nowhere. Now, anything we enter for the third argument will be entered at the index we specified in the first argument.

Screen Shot 2014-07-31 at 3.27.05 PM Screen Shot 2014-07-31 at 3.27.00 PM

If we wanted to replace 2 with two, we’d simply have to change the second argument and tell it take up one space.

Screen Shot 2014-07-31 at 3.28.59 PM Screen Shot 2014-07-31 at 3.28.55 PM

Now this wouldn’t be used too often because we could just change the value like this:

Screen Shot 2014-07-31 at 3.30.35 PM Screen Shot 2014-07-31 at 3.30.28 PM

Though it would be useful if you needed to insert multiple values/elements, as the above method wouldn’t work, but splice would.

Screen Shot 2014-07-31 at 3.33.02 PM Screen Shot 2014-07-31 at 3.32.56 PM

Think of splice as two steps. The first two arguments are for removing things, and anything after them will be inserted into the array.

And that’s it, onto the next thing. In more ways than one.

Advertisements

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