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

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