Javascript Refactor Newbie ..... Need Help

I don’t know much about the refactor concept in the javascript as i have read less about it . Can anyone explain how to refactor the javascript code:
var list = document.querySelectorAll(‘.list li’);
function logContent() {
for (var i = 0; i < list.length; i++) {
list[i].addEventListener(‘click’, logContent, false);

Help is appreciated and thanks in advance.

No need to refactor yet, it’s used when you have a larger amount of js and then you can come back and remove duplication, simplify etc.

Two things though, if you save the logContent function to a variable it becomes easier to follow how it’s passed as an argument into addEventListener.
The only other thing is to init the for loop with the length at the start, so it doesn’t look up the length each time through the loop.

var list = document.querySelectorAll('.list li');
var logContent = function() {
for (var i = 0, ii = list.length; i < ii; i++) {
  list[i].addEventListener('click', logContent, false);

You can also use forEach which has much nicer semantics

list.forEach(function(item) {
  item.addEventListener('click', logContent, false);
1 Like

Thanks a lot @markbrown4 … You made it bro … Thankew :innocent:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.