This is the first week of the Command Shift JavaScript basics module and oh boy has the difficulty spiked a bit. I've touched on JS in the past on FreeCodeCamp and done a few small projects but it's never really stuck with me. Something about it just doesn't click, though I am sure it will eventually. I thought I'd post about some of the issues I've come across and how I fixed them and what I learned along the way. Let's dive in!
Problem 1: Numbers
The first one was a simple fix but took a long time to figure out. Let's have a look at the code below:
const quotient = (a, b) => {
// your code here
}
We had to return the quotient of the number that is passed through the function.
After googling some options I found that the Math.trunc() method was what we wanted to use. It looked like this next:
const quotient = (a, b) => {
return Math.trunc()
}
Math.trunc() returns the integer part of the number and shaves off any of the decimal places that might exist when the sum is calculated. Now I thought this was the one to solve this test, however it wouldn't pass at all. After walking away from it and coming back the next day it took me 10 minutes to solve this issue! I needed to pass how Math.trunc() was calculating the numbers being passed through. Did it want to be multiplied or divided? So to solve it, it needed to look like this:
const quotient = (a, b) => {
return Math.trunc(a / b);
}
Now it knows to return a divide b and to Math.trunc() to remove any decimal places.
Again, it was staring me in the face but sometimes you just need to walk away and come back to it to see if it's been solved. This was the last kata I had to solve which mean I could move on to strings.
Problem 2: Strings
There weren't many issues that I came up against with Strings. What I did learn was about Template Literals and how to use them. Template Literals are strings that use ` ` instead of ' ' and we can pass an expression through the string to generate some text. Let's have a look at the code:
const string = 'world';
const sayHello(string) {
return 'Hello, ' + string + '!'
}
// returns Hello, world!
The above uses concatenation to produce the text Hello, world! However, we can make this look a little neater.
const string = 'world';
const sayHello(string) {
return `Hello, ${string}!`
}
//returns Hello, world!
Using the $ symbol yields the same results in a much cleaner way and especially when you have long strings with multiple lines, it can make the code more readable for everyone. Going to be taking advantage of these moving forward. Moving on to the next section, we've got Booleans, logic and comparators.
Problem 3: Booleans
Yep, this is where it started to get a little tricky. Booleans have only two values: True or False. When we want to find out the values of something we use comparison operators. I'm not listing off all the operators below, as there are a lot! However, I will link a list of them here MDN operators.
Let's look at a problem I struggled with a lot during this one.
function containsVowels(string){
// returns true if your string contains vowels. Otherwise returns False
}
Seems quite straightforward. Does my string contain vowels or not? For this, I googled around and found the includes() method. The method shows us if a string contains a specified string, and I struggled to figure out how to get it to show the vowels themselves. I enquired with the tutors on this after I'd been stuck on it for a few days. Let's take it to step by step:
function containsVowels(string){
string = string.toLowerCase() // this is converting our string to lowercase, as the includes() method is case sensitive
}
Includes() being case-sensitive was the first part we had to solve. We could either convert the string to be entirely lowercase or include in our array(shown below) all the vowels capitalized as well. We chose lowercase as it looked much neater.
function containsVowels(string){
string = string.toLowerCase()
const vowels = ['a', 'e', 'i', 'o', 'u'] // created a variable to show what exatcly we're looking for
let count = 0 // this allows us to store the value of how many variables are in the string. We use let so it can be changed later on
}
With the above, we're listing the exact values we want to search for and also creating a place to store that value which is the variable count. Now we need to loop through each string and see if they have the vowels included. For this, we use a forEach() loop
function containsVowels(string) {
string = string.toLowerCase()
const vowels = ['a', 'e', 'i', 'o', 'u',]
let count = 0;
vowels.forEach(vowel => {
if(string.includes(vowel)){
count++ // We start by looping through the strings passed and check to see if they include any of the vowels. If they do, our if statment then causes the count variable to increment by 1 for each vowel found.
}
})
if(count > 0){
return true; // if the count variable is greater than 0, then we return true
}
return false; // if there are no vowels, then we return false
}
This is where we ended up at the end of trying to solve this. Thanks to Matt and Cora for helping with this one! We used a lot of methods we haven't touched on yet to solve this and it was great to work alongside the tutors to figure this one out. Next, we're on to Arrays.
Problem 4: Arrays
Arrays pushed the difficulty for me. Some were relatively easy and a few others were not. I'm starting to realise that there are multiple ways to solve a problem. People are finding lots of different ways of getting these tests to pass and it's interesting to see. Let's take a look at the array challenge from the tests.
The task was to remove an element at the n position, without modifying the original array.
const removeNthElement2 = (index, array) => {
const result = [] // creates a new array to hold the result
}
So what do we need to start with? Firstly, I thought we need to create a new array for the result to be stored in. This way we're creating an array with the correct result without editing the previous array. I then thought, 'how do I check for what needs to be removed?' and I found that a for loop would be perfect for this.
const removeNthElement2 = (index, array) => {
const result = []
//for loop to loop through the current array
for(let i = 0; i < array.length; i++){
}
}
Then we'd require an if statement to check for the position of n in the array, and to not include it in the result array.
const removeNthElement2 = (index, array) => {
const result = []
for(let i = 0; i < array.length; i++){
// skips the nth element in the array
if (i !== index){
result.push(array[i])}
}
return result //return the above result array without the n element
}
Using the inequality operator, we're asking the if statement to push each element from the array that doesn't match index into the array. The i++ then moves it on to the next value and it checks again. Once it's cycled through the array, we're returning result which will have our new array with all the n elements not included in it. Overall, I was pretty pleased with this one as it does use a lot of things we've not touched on a lot in the course so far. Now on to the last part of the foundation's JS, Objects.
Problem 5: Objects
For the last section of this intro to JS, we are tackling objects. The problem I've chosen isn't a super complex one, however, it is one that I stumbled upon quite a bit and managed to correct. I will include what I started with, where I went wrong and how I fixed it. So, let's dive right in.
The idea of this challenge was to return an array with the age values of each object. To start, we need to create an empty array for the age values to be put into.
const getAges = people => {
const ages = []
}
Next, I had to think about how I wanted to extract the values and return them into an array. I've come to understand For loops and their uses and this seemed like the perfect place to implement one.
const getAges = people => {
const ages = []
for (i = 0; i < people.length; i++) //loops through the array each time and stops when it reaches the end of people.
}
Now we need to have an if statement. This will allow us to set a condition and then return something when the condition is met. For this, we want to push each age value when the for loop finds it. This is where I started to go wrong
const getAges = people => {
const ages = [];
for (i = 0; i < people.length; i++){
if(people[i].age === age) {
ages.push(ages[i].people)
}
return false;
}
}
Can you see where I went wrong? There are 3 mistakes here that took me some time to figure out. See if you can spot them before reading on!
First off, people is being compared to age which isn't a defined variable. I'm trying to compare it to something that does not exist. What I need to do is to remove the strict equality operator here and just have (people[i].age). What this does is use dot notation to retrieve each value associated with the age key from the people object.
Next, I realised then that the push method is instantly incorrect and needed changing to the new people[i].age syntax. So it will now look like this:
ages.push(people[i].age) pushing the result of the if statement and the loop into the new array.
Finally, I wasn't returning the new array! Completely blanked on this one. It should be return ages, not return false. Below is the final result:
const getAges = people => {
const ages = [];
for (i = 0; i < people.length; i++) {
if (people[i].age) {
ages.push(people[i].age);
}
}
return ages;
};
This passed the test straight away. I felt really smart when doing the first one and was quickly humbled by the mistakes I'd made but that's how we learn. Still getting used to using dot notation to pull the values from objects, and knowing when to use bracket notation as well.
That's A Wrap
So that's the end of the intro to JS basics and covering it. Overall it has been difficult but I feel a lot more confident with writing the syntax, as well as reading other people's and trying to make sense of it. I am more confident with how to approach a problem, deconstruct and try and figure out a solution, and this is only after doing it for just over a week! It has been a lot of fun, but also frustrating to say the least!
As always, check out the Command Shift website for info on the course or feel free to reach out to me on Twitter. Thanks for reading!