JS Loop Break Keyword

Hi All,

I’m confused by the solution to this problem:

  1. Log each element from rapperArray in a for loop with the iterator variable i .

  2. After the for loop, log the string "And if you don't know, now you know." to the console. Note: since there’s a single quote character, ' , in our string, we can use double quotes around the string to make sure character prints.

  3. Add a break inside your loop’s block that breaks out of the loop if the element at the current index in the rapperArray is 'Notorious B.I.G.' .

    const rapperArray = [“Lil’ Kim”, “Jay-Z”, “Notorious B.I.G.”, “Tupac”];

    // Write you code below
    for (let i = 0; i < rapperArray.length; i++){
    console.log(rapperArray[i]);
    if (rapperArray[i] === ‘Notorious B.I.G.’){
    break;
    }
    }

    console.log(“And if you don’t know, now you know.”);

I got the first little bit of code but then I had so much trouble so I clicked “View Solution.” I think the second and third question is what’s throwing me off. Thanks so much for any help you can give me!

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-loops/lessons/loops/exercises/break-keyword

1 Like

Hello!
The break keyword is used to exit a loop. So, essentially, this code loops through a range of numbers-which are also list indices. The loop logs every element of the list, then it executes a conditional. This conditional checks to see if the current element of the list the loop is on, is "Notorious B.I.G". If it is, then the break is executed, which means the loop is terminated.

I hope this helps!

3 Likes

Thank you very much!

1 Like