# 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.

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

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.

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

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.  Now, what if we write 012?

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

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.

Calling k now gives us a number that we can use for calculations. 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.  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.  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).  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.  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.  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.

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.

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

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.

There’s also the !== is the bang equals equals operator, and means not equal. It is the opposite of ===. != is the opposite of ==.  We can use these comparisons in our code for if/else blocks and other stuff.  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).

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

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

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

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

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:

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

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. Another example are the min() and max() methods, which tell you the minimum or maximum number passed as an argument in them. The abs() method returns the absolute value. ### 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.

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

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.

You can also add arrays inside of arrays.  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.  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.

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

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.

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

But what happened to our “answer” variable from before that we set to my_array? It is still set to 42, because it happened earlier in the code before we changed my_array’s value. Basically answer is now what my_array equaled at that time. What is we assign to an index that doesn’t currently have a value? Works just fine.  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.

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

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

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

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.  The reverse() method simply reverses the order of elements inside of an array, changing the array.

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.  Rather than passing a variable, we could have just written in another array as the argument, which is basically the same thing. 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. We can have arrays and numbers, and it will still add each as an element. It won’t make a sub array.

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.  If we started at index 2, the result would change accordingly.  If the ending index is outside the ending value of our array, it simply won’t return anything.  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.

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.

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,

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.  Splice is commonly used to just remove one element, but you can remove more.

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.

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

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

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

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.