Active Learning Example: Filtering Greeting Messages - Help interpreting the solution code

Hello,

I’m a couple of weeks into learning Javascript and am struggling to understand code in multiple lines, so I decided to go back to the start with the MDN learning web development pathway. I’m currently working through the filtering messages active learning example. I’ve had to jump to the solution and want to check that I’m reading it correctly. I’ve commented on the code below to say what I think is happening.

const list = document.querySelector(’.output ul’);
list.innerHTML = ‘’;
let greetings = [‘Happy Birthday!’,
‘Merry Christmas my love’,
‘A happy Christmas to all the family’,
‘You’re all I want for Christmas’,
‘Get well soon’];

*** I understand the for loop here is looping through each item in the array and then a variable is created called ‘input’ that is equal to the greeting message at array position ‘i’.***
for (let i = 0; i < greetings.length; i++) {
let input = greetings[i];
*** The if statement is looking for anything in the list that is not equal to not containing the substring ‘Christmas’. and therefore will find anything that does include that substring. A variable of ‘result’ is created that is equal to ‘input’ - the greeting at position ‘i’ in the loop. ***
if (greetings[i].indexOf(‘Christmas’) !== -1) {
let result = input;
*** A variable is created that will create a list item within the html document, the content of which will be equal to ‘result’ - the greeting at position ‘i’ in the loop. This list item is then added to the list through ‘appendChild’. ***
let listItem = document.createElement(‘li’);
listItem.textContent = result;
list.appendChild(listItem);
}
}

Have I read the code correctly?
Why do we have the same string content being used with different variables - ‘greetings[i]’, ‘input’ and ‘result’? Would the code otherwise break?
Finally, is ‘list.appendChild(listItem)’ talking to the ‘list’ element within the html document?

Thank you for your help - I’m sure I’ll get there in the end but I’m finding it hard to work through the logic and syntax at the moment.

Many thanks

Richard

1 Like

Hello @richardanlezarklee ,
your below sentence helps me much in understanding the “not equal to not containing” concept or methodology of the !== -1. Likely the best description of it I’ve found yet, at least for me anyway.

The if statement is looking for anything in the list that is not equal to not containing the substring ‘Christmas’. and therefore will find anything that does include that substring.

Here’s a link to another thread and example on this exercise.
Active learning example: Filtering greeting messages - Question

Thanks! :vulcan_salute:

No worries. I’m glad my brain workings can help someone understand things better!