Ali Amini
Ali Amini

Reputation: 192

What is the best way for defining functions in loops? - JavaScript

I want to know which way for defining functions in loops is better? I always use the first way. Is it correct? or there is another way for this case?

Please guide me, I use the first way a lot in my codes, I wonder if it is true?

$('.elements').each(function(){
  // elements
  var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');

  // variables
  var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');

  function doSomething(){
    $t.width($anotherEl.width() + $anotherEl2.width());
    // other codes ...
  }
  doSomething();
  $(window).resize(doSomething);
});

or

function doSomething(par1, par2, par3, par4){
  var $t = par1 , $anotherEl = par2, $anotherEl2 = par3;
  $t.width($anotherEl.width() + $anotherEl2.width());
  // other codes ...
}

$('.elements').each(function(){
  // elements
  var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');

  // variables
  var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');

  doSomething($t, $anotherEl, $anotherEl2, isLand);
  $(window).resize(function(){
    doSomething($t, $anotherEl, $anotherEl2, isLand);
  });
});

Thanks for advance.

Upvotes: 0

Views: 58

Answers (1)

Jai
Jai

Reputation: 74738

Why doing this in loops? As this can be done without using loops like:

function doSomething(){
    $('.elements').each(function(){
         // elements
         var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
         // variables
         var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
         // now do something with the vars here.
    });
}

$(window).resize(doSomething).resize(); // <---trailing .resize() triggers on dom ready.

Problems i see with your approach are:

  1. Using .each() loop defining same function again and again, executing same function and binding resize event in each iteration.
  2. Second one seems a bit better but partially because of .resize bindings.

Upvotes: 3

Related Questions