Background
The first three weeks of my time at Flatiron School have been a very hectic time. Having to juggle my new sleep schedule, a nearly two-hour commute, and all the course material has proven to be quite the struggle. Nonetheless, it is my third week here and I can confidently say that I have adjusted to my new routine and prefer it to my old one. Each phase at Flatiron is split into three weeks: a learning week, a review/testing week, and a project week. During week 1, we learned about an interesting concept: the forEach() method in JavaScript.
What is the forEach method?
Put simply, the forEach method goes through an array and does something for each of the objects in that array. A simple example of this would be if I wanted to log each element in my array. The iterative way to code this would be as such:
const myArray = [1, 2, 3, 4, 5, 6];
//Create a for loop that loops through the array and
// stops at the length of the array
for(let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
As we can see, this method works but, it can get very repetitive quickly if we have multiple different arrays that we want to work with.
//Arrays of different lengths
const myArray = [1, 2, 3, 4, 5, 6];
const myArray2 = [1, 546, 22, 27, 27, 272, 2, 42, 54, 6];
const myArray3 = [0, 9, 8];
for(let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
for(let i = 0; i < myArray2.length; i++) {
console.log(myArray2[i]);
}
for(let i = 0; i < myArray3.length; i++) {
console.log(myArray3[i]);
}
// Expected output:
// 1
// 2
// 3
//etc...
Thankfully, JavaScript has a useful tool to make this code much simpler to write and read:
//Same arrays as before
const myArray = [1, 2, 3, 4, 5, 6];
const myArray2 = [1, 546, 22, 27, 27, 272, 2, 42, 54, 6];
const myArray3 = [0, 9, 8];
myArray.forEach(element => console.log(element));
myArray2.forEach(element => console.log(element));
myArray3.forEach(element => console.log(element));
// Expected output:
// 1
// 2
// 3
//etc...
Look how much more concise our code is now! Why do I mention this relatively easy topic you might ask? Well, I struggled to use this method for a while until I understood that this method only works for arrays and when working with JSON files we oftentimes also work with objects. I would constantly try to use the forEach method on objects that were returned through my JSON to try and parse through the object's properties. This led me down another rabbit hole of trying to find out how to loop through an object.
for...in()
Originally, I didn't even realize that there was a different method to parse through objects in javascript. What led me to find the for...in method was just how many times I was getting error messages with the forEach method. When I looked up why I was getting these errors, I found multiple articles stating that if I wanted a method to loop through objects, I should be using for...in.
for...in is very similar in both style and function to forEach:
const object = { apple: 1, banana: 2, carrot: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// Expected output:
// "apple: 1"
// "banana: 2"
// "carrot: 3"
Where the for...in method comes extremely in handy is when you have a dictionary that relates many different keys and values and you need to find a specific one to do something with. Let's take for example leetcode problem 12 (integer to roman).
The premise is that you will be given an integer value and must convert it into a string given these rules:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Seems simple enough right? Well actually no. Without using a dictionary of some sort, we would need to check if our number was:
Divisible by the value
If so, how many times it is divisible
Use a loop to print whichever letter corresponds to that value
We can do this for one value pretty easily actually:
//Default values for new string to return and our divide counter
let string = ""
let times = 1;
var intToRoman = function (num) {
if (num - 1000 >= 0) {
times = Math.floor(num / 1000)
for (let i = 0; i < times; i++) {
string += "M"
}
num -= times * 1000
}
}
Note: the Math.floor method is built into JavaScript and simply rounds whatever value down. We use it in this case as we cannot divide our number by a decimal.
The problem occurs when we need to repeat this for every value in the table above. Our solution could easily end up with over 100 lines of code. However, using a dictionary and the for...in method, we can solve it in under 20.
First, we want to establish our dictionary that lists all the pairs of data that we will work with:
const dict = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
}
Next, it is just a matter of looping through our dictionary and making the same logic checks as our if statement in our first solution.
let string = ""
let times = 1;
var intToRoman = function (num) {
for (let key in dict) {
const value = dict[key]
if (num - value >= 0){
times = Math.floor(num / value);
for(let i = 0; i < times; i++){
string += key;
}
num -= value * times
}
}
//Don't forget to return the string once done!
return string;
}
All our code is doing here is looping through each key in our object and comparing the number passed in the parameter with the corresponding value in our dictionary.
Boom! That's all the code we need for the problem to be solved! We effectively reduced our lines of code by about 80%! That was this week's shallow dive into JavaScript's forEach and for...in methods!
TLDR (ChatGPT)
During the initial weeks at Flatiron School, adapting to a new routine was challenging but rewarding. Among the lessons learned, the forEach()
method in JavaScript stood out as an invaluable tool for iterating over arrays, simplifying repetitive tasks. While forEach()
is effective for arrays, when it comes to objects, the for...in
loop is the go-to method. This distinction became especially evident while solving a coding challenge to convert integers into Roman numerals. By using a dictionary and the for...in
method, the solution became more concise and efficient, reducing the code length by approximately 80%. This week's lessons served as an insightful introduction to two crucial JavaScript methods.