Lab work 8 - ENTERING THE SECOND REALM - JavaScript in Plain Language (2015)

JavaScript in Plain Language (2015)

PART II: ENTERING THE SECOND REALM

2.10 Lab work 8

Let’s do some programming to cement our understanding of the array creation, addition of items, and traversing the array with a for loop.

Please fire up your JavaScript Console and let’s get our hands dirty!!

· Try doing this exercises yourself by following the next 7 steps, or jump to the guided exercise that follows in order to do it as I explain the concepts.

NOTE: These seven steps are not a project. Each step is an independent exercise to see how each implementation is done.

Preliminary project

1- Create an empty array assigned to a variable named misc
(short for miscellaneous).

2- Create another array assigned to a variable named greekLetters, and with the following items: "alpha", "beta", "gamma", "delta"

3- Assign the number 99 to the first position in array misc,
assign the word "bottles" to the second position in array misc,
and assign the word "beers" to the ninth position in array misc.

4- Print to screen the length of array greekLetters.

5- Print to screen the length of array misc.

Using push and unshift

6- Add a new item "epsilon" to the end of array greekLetters.

7- Add a new item "folk song" to the beginning of array misc.

(See my answers on the next page)

(Guided exercise) Preliminary project

1- Create an empty array assigned to a variable named misc
(short for miscellaneous)
var misc = [ ];

2- Create another array assigned to a variable named greekLetters, and with the following items: "alpha", "beta", "gamma", "delta"
var greekLetters = ["alpha", "beta", "gamma", "delta"];

3- Assign the number 99 to the first position in array misc,
assign the word "bottles" to the second position in array misc,
and assign the word "beers" to the ninth position in array misc.
misc[0] = 99; (no quotes for number)
misc[1] = "bottles";
misc[8] = "beers";

4- Print to screen the length of array greekLetters.
console.log(greekLetters.length); <-- results in 4

5- Print to screen the length of array misc.
console.log(misc.length); <-- results in 9

Did you notice how we were able to add a ninth position to the array misc?

Did you also notice how the array misc now has 9 items, which means that 6 items are reserved with the placeholder value of undefined?

Using push and unshift

6- Add a new item "epsilon" to the end of array greekLetters.
greekLetters.push("epsilon");

7- Add a new item "folk song" to the beginning of array misc.
misc.unshift("folk song");

Practicing is the only way to get good at it.

Let’s practice with for loops on arrays by wrapping functionality in functions and use some if else conditionals in the mix. These projects will cover important concepts that can be used often.

Creating a method to add items into an array

Ready for a simple challenge?

We are going to create a function that automatically adds an item into the array when the function is called. This will allow us to practice with array.length as an alternate solution for push.

· Use your editor first before pasting onto the Console. Try doing this exercise by yourself first by following the next 5 steps, or jump to the guided exercise in order to do it as I explain the concepts:

1- Declare an empty array assigned to the variable x.

2- Create a function named addMe that automatically adds an item to array x:

a) Use one input parameter called item.

b) In the function body assign the input item to the first empty position in the array, based on x.length.

x.length is always one more number than the address of the last item. By assigning an item to location [x.length] it will always match the next position available in the array. Give it some thought and then look at my answer if you are unsure on how to do it.

c) Also inside of the function, create a console.log to print out the whole array in its raw display form (no loops yet).

3- Paste the script in the Console and
Call the function by passing in "grape" as an input item.

4- Then Call the function again and pass in "apple" as an input item.

5- Do the same for "banana".

(See the answer on the next page).

(Guided exercise) Create a method to add items into an array

1- Declare an empty array assigned to the variable x.
var x = [];

2- Create a function named addMe that automatically adds an item to array x.

d) Use one input parameter called item.

e) In the function body assign the input item to the first empty position in the array, based on x.length.

f) Also inside of the function create a console.log to print out the whole array in its raw display form (no loops yet).

Fig 12

On line 1 the array x was declared.

On line 3 a function addMe with item as an input parameter was declared.

On line 4 whatever data is passed in when we call the function, the data gets assigned to the maximum length of array x. As you know, the length of an array always shows the number of items in existence. It so happens that the number of items is always 1 more than the last location of the last item. Therefore, the length of the array always corresponds to the next position after the last existing location. So we can use this number to calculate the next location available. This is actually what push() would do automatically but here we are doing it manually in order to understand a bit more about arrays.

On line 5 we print the array x to screen in its new raw form.

3- Paste your script on the Console and
Call the function by passing in "grape" as an input item.
Then Call the function and pass in "apple" as an input item.
Do the same for "banana".

addMe("grape");
addMe("apple");
addMe("banana");

The final result is: ["grape", "apple", "banana"].

Great!

Whenever you’re ready, please move on to the next page. We are going to create a method that prints out the items of an array, any array. Coding generically is an important goal as programmers.

Create a generic method to print out the contents of an array

Generic is synonymous with portable. In programming scripts should be made as portable as possible. It leads to reusability and memory efficiency. By creating a portable array method we can use it with any array, not just the one we are programming at the moment.

1- Create a method (a method is a function mechanism) named printArray that takes an input parameter arbitrarily named inputArray

2- Then inside of the function create a for loop that initializes i to zero and runs as long as i is less than the length of the array given to inputArray.

3- In the body of the loop, console.log the inputArray[i], this will correspond to each item location of the given array, one at a time.

4- Close the loop, close the function. You’re done.

Testing...

5- If you still have array y on the console, print array y. If not, add array y as shown below:
var y = ["grape", "apple", "banana"];

6- Print array y by calling the function printArray() and pass y as an argument.

7- Create several other arrays and use the generic printArray() method to print them.

(See my answer and a link to file on the next page).

(Guided exercise)
Create a generic method to print out the contents of an array

1- Create a method (a method is a function mechanism) named printArray that takes an input parameter arbitrarily named inputArray.

function printArray(inputArray) {

2- Then, inside of the function create a for loop that initializes i to zero; and runs as long as i is less than the length of the array given to inputArray.

for(var i = 0; i< inputArray.length; i++){

3- In the body of the loop, console.log inputArray[i], this will correspond to each item of the given array, one at a time.

console.log(inputArray[i]);

4- Close the loop, close the function. You’re done.
}
}

5- If you still have array y on the console, print array y. If not, add array y as shown below and print it:

var y = ["grape", "apple", "banana"];

6- Print array y by calling the function printArray() and pass y as an argument.
printArray(y);

7- Create several other arrays and use the generic printArray() method to print them.
See my file: forum. (bit.ly/1rdSRuA).

Discussion

Generic methods are very useful. It is always a good idea to save them for future use. However, since you are practicing, saving code for a future copy/paste might not be as beneficial to you yet. Code snippets act like recipes for cooking. There are many cookbooks for programmers out there and although they may not help you at this moment, they may come handy in the future. (Personally I don’t own any of those books since I enjoy creating my own stuff but in a professional environment they can be useful, especially when it comes to more advanced, time consuming implementations).

The inputArray parameter serves as a placeholder for whatever array name you pass in when you call the function printArray. Instead of printing the array to screen with a console.log() we could have done something else with the array, like for example sorting it. We will get there when I introduce more properties and array methods from the internal JavaScript library.

Remember, this book is about learning how to use JavaScript, it is not a dictionary of methods. You can always refer to my other eBook for that purpose, but only after you finish this one.

Extra bonus: Create a generic method to add items into an array

To do this exercise, go back to the first exercise of this lab work (on Fig 12), and recreate it in a way that we could add items to any array, not just the array x as the original example shows.

1- You need to add two input parameters to the function I’m calling addMe2:

a) One input for the array name
( I will call it inputArray),

b) and one input for the item you want to add to the array
( I will call it inputItem).

2- Then in the function body, create a script that assigns the location inputArray.length to the new item (inputItem):

inputArray[inputArray.length] = inputItem;

Note: Since the script gets a bit more complicated than the original one, I am using names that make sense to humans in order to help them understand what the script does. Even if we code for our own use (as opposed to other people), we will not remember what it is when we return tomorrow.

3- If you wish, add a console.log(inputArray); to the function body in order to monitor the output.

4- Finally, create some empty arrays outside of the function, and then add items to each one of them by calling the function.

Whenever you’re ready, please refer to my own script:
forum board. | bit.ly/1pnR5S8

END OF LAB