CodeNewbie Community ðŸŒ±

Janet Webster

Posted on • Updated on

Commit2 //JavaScript Fundamentals [Arrays & Loops]

Enjoy this picture of my porky lil puppy.

I am learning with Skillcrush. Please check them out and consider signing up if you're looking to break into tech! Receive \$250 off your course by using the link above.
NOTE: this discount is for Break Into Tech + Get Hired package exclusively. It's the same program I am participating in!

The Array Data Type - Video Introduction

I'm excited to jump into this because I think that this is our lead-in to combining mass datapoints into javascript.

In the intro video it covers some pre-defined arrays and how to make them loop. It also covers how to "pop" and "push" them... I'm not sure I understand those functions quite yet.

I like the forEach method to give an indexed list of all the values.

Definitely will be returning to watch this video again when I read through the lessons explaining Arrays & Loops.

Writing Arrays

OK, so reviewing the lesson. push(element) adds to the end of an array and pop() removes the last element within an array. No need to fill anything out in the parenthesis.

I was also calling elements values before. Not sure if that's correct or not, but I am making note to call them elements. Looks like they are calling them elements, items, and values in the lesson.

REWATCH:
The values in the array are known as [elements].
The square brackets indicate when the array starts and ends.
This can include more data types than just numbers.
It can also include "strings".

Index - position of the [elements] in the array (Indices)

Elements: [2, 4, 6, 8]
Index: 0,1,2,3

To logout an array element:

console.log(dressSizes[4]);
// 8

To change an array element:

dressSizes[4] = "large";

pop() - To remove an element from the end of an array:

dressSizes.pop();
console.log(dressSizes);
// (6) [8, 16, 2, 24, "small", "x-large"];

push(element) - To add an element to the end of an array:

dressSizes.push(12);
console.log(dressSizes);
// (8) [8, 16, 2, 24, "small", "x-large", "medium", 12];

pop() and push(element) are known as methods

/-----------------------------------------------------------/
Tell you what, learning about all of this is making my last job working in a GovTech SaaS make a lot more sense! I was doing QA using some of these methods without even knowing it.
/-----------------------------------------------------------/

length property - to quickly isolate the number of elements in an array

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
console.log(timeOfDay.length);
// 6

To get an index of all the elements in an array,
simply log out the timeOfDay variable.

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
console.log(timeOfDay);
//(6) [6, "noon", 8, "morning", "evening", 12]
// 0: 6
// 1: "noon"
// 2: 8
// 3: "morning"
// 4: "evening"
// 5: 12

You can also find the element in an index position,
simply put the index number in square[] brackets.

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
console.log(timeOfDay[4]);
// evening

Replacing Array Elements

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
timeOfDay[4] = 5;
console.log(timeOfDay[4]);
console.log(timeOfDay);
//(6) [6, "noon", 8, "morning", 5, 12]
//0: 6
//1: "noon"
//2: 8
//3: "morning"
//4: 5
//5: 12

â€‹
Array Methods:
includes(), pop(), push(), splice(), and indexOf()

includes(element) is pretty straight forward.
example:

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
console.log(timeOfDay.includes("morning")); //true
console.log(timeOfDay.includes(11)); //false

push(element) & pop()
this is to add or remove an element at the end
examples:

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
timeOfDay.push("midnight");
console.log(timeOfDay);
// (7) [6, "noon", 8, "morning", "evening", 12, "midnight"]
var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
timeOfDay.pop();
console.log(timeOfDay);
// (5) [6, "noon", 8, "morning", "evening"]

splice(element)
With splice you can remove, replace, or add elements.
To remove example:

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];

timeOfDay.splice(0, 2);
console.log(timeOfDay);
// (4) [8, "morning", "evening", 12]

To replace example:

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];

timeOfDay.splice(0, 2, "mid-afternoon", 7);
console.log(timeOfDay);
// (6) ["mid-afternoon", 7, 8, "morning", "evening", 12]

To add via splice, first placement is where you want the elements added, second placement must hold (0) to not remove any elements:

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];

timeOfDay.splice(6, 0, "twilight", 5, 9);
console.log(timeOfDay);
//(9) [6, "noon", 8, "morning", "evening", 12, "twilight", 5, 9]
//0: 6
//1: "noon"
//2: 8
//3: "morning"
//4: "evening"
//5: 12
//6: "twilight"
//7: 5
//8: 9

indexOf() tells us where the element is in the index of an array.

var employeeAge = [15, 36, 78, 17, 42, 19, 18];

var age = employeeAge.indexOf(42);
console.log(age);
// placement is 4

If the element does not exist, it will display as -1.

var employeeAge = [15, 36, 78, 17, 42, 19, 18];

var age = employeeAge.indexOf(37);
console.log(age);
// element does not exist, so it is -1

I definitely feel more confident in understanding writing arrays after going through this the second and third time. Cheers to learning how to study!

GitHub Repo for Writing Arrays

Loopy with Loops

For...Of Loops I'm not really getting on the initial read through. I plan to review the video again and then do the code along after the initial read through.

forEach() I'm not really understanding the first time around either!

filter() now that makes sense to me. Probably because we used a lot of equal/greater to/less than filtering in the databases I used to work in. includes() also makes sense because again, just filtering.

REWATCH:
Loop - A statement that lets you repeat code multiple times
Each time the code is repeated, it's called an iteration.

Two techniques of looping through arrays:
for...of loops
forEach() method

for...of you need to declare a variable to represent each element as you loop through the array.

for (var size of dressSizes) {
console.log(`This dress is size \${size}.`);
}
// This dress is size 2
// This dress is size 4
// This dress is size 6
// This dress is size 8

forEach() can be used to loop through the elements and indices(index).

dressSizes.forEach(function (size, index) {
console.log(`\${index}. Size \${size}`);
});
// 0. Size 2
// 1. Size 4
// 2. Size 6
// 3. Size 8

This one I'm less sure on how it works.
It may be because I still don't have a firm grasp on functions,
so throwing (size) parameter in there establishes it?
I almost feel like it should be declared somewhere else, but maybe not.

Then with (index) I'm guessing this is just intuitive to the programming language.

Since indices begin at 0,
here is how they recommend fixing it in this scenario:

dressSizes.forEach(function (size, index) {
console.log(`\${index + 1}. Size \${size}`);
});
// 1. Size 2
// 2. Size 4
// 3. Size 6
// 4. Size 8

This way the index begins at 1,
by adding the + 1 to the console log.

/-----------------------------------------------------------/
Time to review lessons 1-3 and I'll make some annotations of clarifications I find along the way.
/-----------------------------------------------------------/
As you can see above, I feel like I picked up a fair amount by re-watching the video.
Now I'm going to go head and proceed with the code-along portion of the two reading lessons.

/-----------------------------------------------------------/

for...of loop has a body just like functions.
Here is a written example:

var timeOfDay = [6, "noon", 8, "morning", "evening", 12];
for (var time of timeOfDay) {
console.log(`It is \${time}.`);
}
// It is 6.
// It is noon.
// It is 8.
// It is morning.
// It is evening.
// It is 12.

So this code is iterating through the array, stating each element option with the console log message.

forEach() method iterates through elements in an array and executes a function for each element.

It accesses the element and the index.
Here is a written example:

timeOfDay.forEach(function (time, index) {
console.log(`The \${time} element is at position \${index}.`);
});
// The 6 element is at position 0.
// The noon element is at position 1.
// The 8 element is at position 2.
// The morning element is at position 3.
// The evening element is at position 4.
// The 12 element is at position 5.

I think I'm beginning to understand how the parameter is kind of like a type of variable, so you can use it in the console log.

filter() method will return a new array with elements from the original array that pass the specific filter condition.
Here is a written example:

var employeeAges = [15, 36, 78, 25, 17, 42, 19, 18];
var adultAges = employeeAges.filter(function (item) {
return item >= 18;
});
// (6) [36, 78, 25, 42, 19, 18]

This makes a lot of sense to me having dealt with data management in my previous work. Now it's just about knowing how to do it when needed. I think the one thing I'm unsure of is the (item) in function. That's probably from a previous lesson in functions that I didn't quite grasp.

filter() + .includes() to filter elements that match a string.
Here is a written example:

var lastName = [
"Chambers",
"Chamberlain",
"Chamberlin",
"Jones",
"Webster",
"Willits"
];
var chamberName = lastName.filter(function (item) {
return item.includes("Chamber");
});
console.log(chamberName);
//(3) ["Chambers", "Chamberlain", "Chamberlin"]

A couple easter egg names in there for folks who know me.
This all makes pretty good sense to me. Now it's just about remember how to write these array functions.

GitHub Repo for Loopy with Loops

Practice Quiz

I felt pretty good doing my quiz and I was able to lookup or google things I didn't immediately recognize.

Basically I needed to fully review the cheatsheet given prior to the quiz so I would know a couple of the questions that I had to look up.

1. spread operators (...) - this would/could be an alternative to .concat(), which is another operator I haven't heard of, so that you can basically combine elements together into one array.
2. .concat() - might as well go here, since this one is new too. simply this is to join two arrays. make sense, since we concatenate at other times in programming languages as well.
3. .shift() - to remove an element from the beginning of an array
4. .unshift() - add one or more element(s) to the beginning of an array
5. .map - to return an array with all elements modified by the callback function. like to multiply the elements. or to return them in their own sentence. I feel like there's a different operator for that though.

There are a lot more on the cheatsheet, but I will leave it as that for now. I think I have the basics down with arrays & loops so far, so I will continue on to the next lesson.

Working with Arrays

Time to do a code along. If I come up against any difficulties, I'll write about them here. Otherwise, I'll just drop the final product.

Here's the code!

var hobbies = [
"Roller Derby",
"Yoga",
"Meditating",
"Indoor Plants",
"Lifting Weights"
];

//hobbies - create & modifying an array
console.log(hobbies.length);
hobbies.push("Volunteering");
console.log(hobbies[2]);
hobbies.pop();
hobbies.splice(2, 0, "Volunteering", "Coaching");
hobbies.shift();
hobbies.unshift("Roller Skating");

console.log(hobbies);

//goals - create a new array & combine arrays
var goals = ["learning JavaScript", "learning JS React", "learning SQL"];
var allTheThings = hobbies.concat(goals);
var thing = allTheThings.indexOf("Lifting Weights");
allTheThings.splice(7, 1);

console.log(allTheThings);

//plans - map over an array
var plans = allTheThings.map(function (item) {
return `I can't wait to begin \${item}!`;
});
console.log(plans);

I'm really proud of how I did. Of course I referenced the cheat sheet plenty, but I felt like I knew what I was doing.

GitHub Repo for Working with Arrays

## Looping Arrays
Another code-along. I'll come here with any revelations or perplexities.

The only part that took me a bit to figure out what how to make the languages list as toUpperCase. I basically needed to add () to make it function.

GitHub Repo for Looping Arrays

Generate a Grocery Shopping List

I am having to do a fair amount of looking things up to accomplish this one.

I did end up having to resort to looking at the solution code. There were a few sentences where I just did not understand what they were asking me to do. Once looking at the code I can piece it together, but I'm just not able to do that level of interpretation at this point.

GitHub for Generate Grocery Shopping List

Practice Exercises: Arrays & Loops

Now for a few exercises put together.

These practices are much harder. I don't really understand what they are requesting of me, so I'll throw the code in here with some of my attempts and then the answers.

var stuff = [
"cars",
"blankets",
"sunflowers",
"sky",
"yellow",
"code",
"perfume",
"coffee",
"books"
];

stuff.forEach(function (item, index) {
if (index % 2 === 0) {
console.log(`\${index + 1}: \${item}`);
}
// my first attempt at writing the code:
//console.log(`\${item} - \${index % 2 === 0}`);
//this gave true/false statements
});

var removeItem = function (array, item) {
//this was my first attempt to code it, obviously I'm way off.
// stuff.splice(7, 1);
// console.log(stuff);
var index = array.indexOf(item);
if (index === -1) {
console.log(`Sorry, that item does not exist inthis array.`);
} else {
array.splice(index, 1);
console.log(`Removing \${item}`);
}
};

removeItem(stuff, "perfume");
console.log(stuff);
removeItem(stuff, "tea");
console.log(stuff);

//this was my first attempt at filtering out.
//I didn't see the part about making it a for...of loop.
//So this is obviously wrong.
//It did not work either.
// var sFilter = stuff.filter(function (item) {
//   return item.includes("s");
// });
// console.log(stuff);

//first approach - of...loop
var onlyS = [];

for (let item of stuff) {
if (item.includes("s")) {
onlyS.push(item);
}
}
console.log(onlyS);
//this method obviously worked.

//filter method - so my first attempt wasn't far off!
var filteredOnlyS = stuff.filter(function (item) {
return item.includes("s");
});

console.log(filteredOnlyS);

GitHub Repo for Practice Exercises

Summary

The new study habits I implemented by @taurist and her team at SkillCrush really helped me heading into Arrays & Loops. It definitely has me already wanting to redo my earlier lessons in JS, but I think I will carry on and then do a full review once I have completed my Vanilla JS course.

I need to be gentle with myself that this is part of the journey and there will be a myriad of things that do not click immediately.

<3

Tauri StClaire

You are kicking so much butt, Janet!!

We put a lot of pressure on ourselves to get something the first time, and that's just not how any complex ideas really unfurl in the mind!

I'm so glad you've been dialing into the study groove that works best for you! You are tenacious and a fantastic problem solver, and both those qualities will take you far in tech and development!

Janet Webster

Thank you! â™¥wâ™¥