Day 9 of learning JavaScript: for-loops and return value
Today I learned about for-loops and also how to return a value. A for-loop is used to repeat a specific block of code a known number of times:
for(let i = 0; i<array.length; i++){//i++ is the same as i += 1
// initialisation, condition, iteration
}
// First I set the new variable i to 0. after that i set the condition.
// As long as i is less than the length of the array (you can use any value here)
// -> repeat loop and after each repetition increase i by 1.
I used this to make sure all cards were displayed. At the beginning of the renderGame() function I added this:
cardsEl.textContent = "Cards: " //Cards: shouldn't be missing
sumEl.textContent = sum
for(let i = 0; i<cards.length; i++){ //loop ends when array ends
cardsEl.textContent += cards[i] //iterates through the array and adds every card
}
After that, I also learned how to return values from functions. You need to return a value from a function if you have to use that value elsewhere outside the function.
let firstRace = 102
let secondRace = 110
function getFastestRaceTime(){
if(firstRace < secondRace){
return firstRace //if you execute this function, there will be the value of firstRace as the returned value
}
else if(secondRace < firstRace){
return secondRace
}
else{
return firstRace
}
}
let fastestRace = getFastestRaceTime() //will have the value 102, because the function returns tha value 102
console.log(fastestRace) //logs out "102"
This is a very important concept in JavaScript. I hope you learned something valuable