Tenali Raman
Tenali Raman

Reputation: 380

understanding a Jquery snippet about Map()

i am very new to JS and Jquery and i have a small difficulty understanding a certain function , I.E. i want to understand the order of execution of a very simple function that i found in the jquery documentation , look below (the example can also be found here.)::

HTML ::

<form method="post" action="">
  <fieldset>
    <div>
      <label for="two">2</label>
      <input type="checkbox" value="2" id="two" name="number[]">
    </div>
    <div>
      <label for="four">4</label>
      <input type="checkbox" value="4" id="four" name="number[]">
    </div>
    <div>
      <label for="six">6</label>
      <input type="checkbox" value="6" id="six" name="number[]">
    </div>
    <div>
      <label for="eight">8</label>
      <input type="checkbox" value="8" id="eight" name="number[]">
    </div>
  </fieldset>
</form>

JS ::

$( ":checkbox" )
  .map(function() {
    return this.id;
  })
  .get()
  .join();

The result is ::

 "two,four,six,eight".

i understand what the indivisual functions are doing above , but can somebody tell me whats the order of execution of the above script .I.E.

is map() returning indivisual id's to get() ? or is it looping over all the checkbox's and then passing all the id's at once ?

Upvotes: 0

Views: 40

Answers (3)

Liam
Liam

Reputation: 29714

The functions are executed in turn, once they complete they hand the result onto the next function, etc.

It's the equivalent of:

var first = $( ":checkbox" ).map(function() {
    return this.id;
  });
var second = first.get();
var third = second.join();

the above is just a shorthand that doesn't require the extra varibales.

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82241

is map() returning indivisual id's to get() ? or is it looping over all the checkbox's and then passing all the id's at once

As per docs for .map(),

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values

Answer: It loops over all the elements available in object and append the id in array at a time. The array generated from .map() is jquery object. .get() converts the object into value array.

Upvotes: 2

aorfevre
aorfevre

Reputation: 5064

the order is as you read it , I mean

1-

   $( ":checkbox" )
  .map(function() {
    return this.id;
  })

2- get()

3- join()

Upvotes: 0

Related Questions