JavaScript I – Day 5

Geekwise Academy

 

 

Instructors:

Corey Shuman

Aaron Lurz

 

 

Slack Channel:

https://geekwise-js1.slack.com

Github:

https://github.com/coreyshuman/Geekwise-JavaScript-I

Lesson plans:

http://coreyshuman.github.io/Geekwise-JavaScript-I/html/

 


 

Today’s Topics

·         Review Assignment

·         Review topics from day 4

o   Intrinsic Objects

o   Functions

o   Truthy, Falsy

·         Do Function review task

·         New Topics

o   Arrays In-depth

o   Functions Part 2

·         Function Challenge Task


 Function Review Task

 

Write a small JS program that will:

 

 


Arrays In-Depth

 

Arrays are very useful for keeping an ordered list of "things".

Arrays don't really care what you put into them, they accept all the data types we've talked about to date, including a few we haven't.

You create a new array using the [...] syntax

Items in an array are separated with a , (comma)

Let’s try creating an array to hold a list of your favorite fruits.

Try it: in your console create a new array and store the value in a variable. Then log the variable.

    
//lets create an array
var fruits = ["apple", "banana", "cherry", "strawberry"];
 
console.log(fruits);
    

Arrays have built in ways of determining how many items they are holding, the length property.

Try it: log to the console the length of the fruits array you created previously.

    
//how many items are in the array?
console.log(fruits.length);
    

Ok, so we've got some data in our arrays, and we know how many items are in the array, now how do we get it back out?

Accessing Array Contents

Arrays are index based, so you can use a numbered index to retrieve a specific value, using the brackets to define which index you want.

    
var a = [1, 2, 3];
 
console.log(a[N]); //where N would be a numbered index you want to retrieve
 
//this works too
console.log([1, 2, 3, 4][N]);
    

 

You might have noticed something odd using the example above. Try this:

    
var a = [1, 2, 3];
var index = 2;
 
console.log(a[index]); //what does this yield?
    

Array indexes (as well as other indexes we'll discuss later) all start with 0. So in the example above, index zero would have the value 1, index 1 has the value 2, index 2 has the value 3, etc...

    
var firstFruit = fruits[0];
console.log(firstFruit); //log the first value in the array
 
var secondFruits = fruits[1];
console.log(secondFruits);
 
//etc...
 
console.log(fruits[4]); //what does a unknown index return?
    

Adding items to an array

Awesome, I can get my data back out of an array once I put it in, how do I add more things to it?

JavaScript Array's provide a function called push that allows for adding items to the end of an array.

Try it: Add a new fruit to the end of your fruits array using the fruits.push(...) function.

    
//add an item to the end of an array
fruits.push("blackberry");
    

When you add items to your array, the length property is automatically updated for you.

    
var a = [1];
console.log(a.length);
 
a.push(2);
console.log(a.length);
    

 

 

 

Arrays can also contain other arrays.

 
//create an array to hold multiple arrays
var fruitColors = [];
var cherry = ["cherry", "red"];
var banana = ["banana", "yellow"];
var apple = ["apple", "green"];
 
//add all the fruit vars into the fruitColors array
fruitColors.push(cherry);
fruitColors.push(banana);
fruitColors.push(apple);
 
console.log(fruitColors);
    

Now let’s attempt to pull out the colors only for each of the three fruits in our fruitColors array.

Try it: create a snippet that will create an array to hold multiple arrays (defined above). Then write three console logs that log only the colors of the fruits.

    
//we can access our array's based on index
console.log(fruitColors[0][1]);
console.log(fruitColors[1][1]);
console.log(fruitColors[2][1]);
    

Removing items from an array

So now we can create Arrays, access array properties, and add items to arrays, how about removing items?

Items can be removed one at a time from the end of the array, using the pop function. NOTE: This modifies the original array

    
var lastFruit = fruits.pop();
console.log(lastFruit);
console.log(fruits);
    

Another handy array function we'll talk about is the slice function. It works on arrays a little differently.

The slice function will make a copy of the specified indexes and return them in a new array.

The signature of the slice function looks like: 

fruits.slice(begin, [end])

 

The begin argument is the zero based starting index, and the end argument is the index to stop at. NOTE: The extraction does not include the end index!

Try it: Create an array with 4 strings, then slice the middle two.

    
var fruits = ["apple", "cherry", "plum", "apricot"];
console.log(fruits.slice(1, 3));
console.log(fruits); //note, it's the same as the original array.
    

One point to remember about the slice functions is that is does not modify the original array. But what if we actually did want to modify the original?

splice to the rescue! The splice function works in a similar way to the slice function, however it allows you to modify the original array.

The signature of the splice function looks like:

    
fruits.splice(begin, howManyToRemove, [additional, items, to, add]);
    

So begin is our starting index, howManyToRemove is how many items to remove from the starting index, and additional items to add are more elements that you want to add to the array (comma separated values).

Try it: Create an array with 4 elements in it. Then remove the third element. Log the array to the console.

    
var fruits = ["cherry", "apple", "banana", "plum"];
fruits.splice(2, 1);
console.log(fruits);
    

Using the same array, remove the second element and add a new second element.

    
fruits.splice(1, 1, "orange");
console.log(fruits);
    

 

We can do a lot more with arrays. Check out MDN for more info on arrays:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array


Functions Part 2

Where we left off:

function log(stuff) {
    console.log(stuff);
}
 
log("the fox jumps over the lazy dog");
    

 

Great, now we're getting somewhere, we can define our own functions that accept arguments and do something with them. It's also worth pointing out that functions can also call other functions.

Now we will try something a little more complicated, but more useful. It would be really nice if we had a way to capitalize a string, for proper names, etc... Maybe JS provides a nice way to do this:

Try it: Let’s check and see if JS provides a string capitalize function...

    
var name = "Adam";
var capped = name.capitalize();
 
console.log(capped);
 
>> TypeError: undefined is not a function
    

 

Look a little closer at that error... undefined is not a function. In our example, we are calling two functions, name.capitalize() and console.log(). Which one is likely giving us the problem?

Since we know console.log() is a real function, it's likely that JavaScript is telling us that name.capitalize is undefined, and thus when we try and call it, it's not a function.

While JS does not provide a way of capitalizing the first letter of a string, it does provide a way to upper case an entire string. It looks like "adam".toUpperCase().

Try it: Create a string (variable or directly inline) and use the toUpperCase function on it. What is your result?

    
console.log("adam".toUpperCase());
    

The result should be an entirely uppercase string. So how can we use this to our advantage if we wanted to write a function that will capitalize just the first letter?

Also, we want this function to accept a string and capitalize it, we need to be able to get that value back out of the function. This is where the return keyword is used. return will return the specified value out of the function so you can use it elsewhere.

Try it: Let’s discuss how you might tackle creating a capitalized string using methods we've discussed in the last few classes. Hint: toUpperCase, string indexes, and slice.

Remember!

In JavaScript strings are not mutable. This means that when you take any action on a string, you're actually creating a new string. So it's important to realize that since I can't actually change the string "adam" into "Adam", we can fake it by creating another string.

 
    
function capitalize(str) {
    return str[0].toUpperCase() + str.slice(1);
}
    

Handling Edge Cases

When writing functions (or any JS program, really), it's very important to consider edge cases. As a developer, it's your job to anticipate odd ways your function might be used and make sure it handles those cases. What happens if you call your capitalize function on an empty string? How can we fix that? What other edge cases might be useful to consider?

    
//this handles our case when no string is passed in (str is "falsy")
function capitalize(str) {
    if (!str) {
        return "";
    }
 
    return str[0].toUpperCase() + str.slice(1);
}
    

Notice the function now contains two return points, one for the case where we don't have a string, and one where we do. It's also important to understand that a function will stop executing any code following a return statement, so if no string is passed in, nothing past return ""; will be executed.

What about making sure that the argument passed into the function is actually a string?

The typeof operator is helpful here. typeof operator will evaluate the type of thing we are working with, and return that value as a string.

Try it: Use the typeof keyword to detect the type of thing we're dealing with.

    
var name = "adam";
console.log(typeof name);
console.log(typeof 3);
    

 

So, how can we use typeof to ensure the argument is a string?

Try it: alter your original capitalize function to ensure that a value is passed in, and that it's a string.

    
function capitalize(str) {
    if (!str || typeof str !== "string") {
        return str;
    }
 
    return str[0].toUpperCase() + str.slice(1);
}
    

 

It's often these "edge cases" that will bite you in the long run. Always begin thinking about odd ways someone might use your code and anticipate how you could handle it!

 

 

Function Challenge Tasks!

In a new JavaScript file, complete the following set of tasks:

·         Create a function that will return the square of a number (power of 2).

·         If a non-number argument is passed into the function, return NaN

·         Create a function that will capitalize the first letter of a string and add a period (.) to the end of the string if it doesn't already end with a period.

·         If a non-string argument is passed into the function, return a blank string

·         Create a string that will flip the position of the first and second half of a string. For example, the string “abcdef” would be returned as “defabc”. Hint: use substring.

·         If a non-string argument is passed into the function, return a blank string

·         If a string with less than 2 characters or an odd number of characters is passed into this function, return a blank string. Hint: use modulus (%) operator.

·         Bonus: how can this function be modified to work with odd-length strings, such as converting “abc1efg” to “efg1abc”?

·         Create a function that accepts an array of 4 numbers and returns the average

·         If a non-array is passed into the function, return NaN. Remember arrays are considered objects in JS.

·         If any of the 4 values in the array are not a number, return NaN.