For each javascript

For each javasript instruction, there are a multitude of ways in javascript to make loops (for) to browse variables or objects. We will take a closer look at some of these ways, through the simple for(), by the each method of jQuery and to finish on the new loop for..

let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
});
// one
// two
// three
// four


var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});




var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});

let names = ['josh', 'joe', 'ben', 'dylan'];
// index and sourceArr are optional, sourceArr == ['josh', 'joe', 'ben', 'dylan']
names.forEach((name, index, sourceArr) => {
	console.log(color, idx, sourceArr)
});

// josh 0 ['josh', 'joe', 'ben', 'dylan']
// joe 1 ['josh', 'joe', 'ben', 'dylan']
// ben 2 ['josh', 'joe', 'ben', 'dylan']
// dylan 3 ['josh', 'joe', 'ben', 'dylan']

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);

Edit sept 2019: some methods like and introduced by EcmaScript 5 seemed interesting but little used (or even unknown) so I decided to add them extra.some()every()

the javascript for loop

Here’s a quick and simple reminder on the for loop:

You’ve probably already used one for the front loop. It’s the most basic loop in JavaScript and it’s very versatile. Here are the basics of loop syntax:

for (i = 0; i < 666; i++) { 
  // do something
}

Our for loop consists of three instructions, one that is executed before our loop starts (i-0), one that defines how long our loop should work (i’lt; 10), and one that is executed after each loop (i- ).

In this example, we set i -0 before the start of our loop. We will continue to close as long as i’lt; 10, and each iteration of the loop will increase i by one. Finally, in parentheses is the code that will be executed with each iteration of the loop.

  • A for loop can be interrupted using the statement break
  • We can move on to the next iteration using the keyword continue

This instruction allows us to do many things; it is very versatile so but not super practical when it comes to working with paintings or objects …

Let’s see if we can find better

The loop for.. in javascript

The instruction for.. Javab in-iteration allows you to iterate on all the listable properties of an object:

let student = { name:"Mark", age: 69, degree: "Masters" };
for (var item in student) {
   alert(student[item])
}
// result :
// Mark
// 69
// Masters

This instruction also allows you to iterate on the tables, but it can have unexpected behaviors. In fact, the statement allows you to iterate on the properties added manually in addition to the elements of the table which could be confusing.

The .for Each method

Introduced in ES5, the forEach method allows you to iterate on the properties of a painting

const list = ['Z', 'E', 'R']
list.forEach((item, index) => {
  console.log(item) //value
  console.log(index) //index
})

//index is optional
list.forEach(item => console.log(item))

Be careful though, the method does not use a copy of the painting when called, it manipulates the painting directly. So if we change the table along the way then the loops can be impacted. There are also several other nice methods to iterate on the tables (like some or every)

let words= ["ONE", "TWO", "THREE", "FOUR"];
words.forEach((WORD) => {
  console.log(WORD);
  if (WORD=== "TWO") {
    words.shift();
  }
});
// one
// two
// four

On the other hand, the interruption of the loop with break or continuous is not possible unless you lift an exception

JQuery’s methods each

The .each method on a jQuery object

If you use jQuery then there is a handy method for iterating on all the properties of a jQuery object. When called, iterates on the DOM elements that are part of the jQuery object. Each time the reminder runs, it is switched to the current iteration, starting at 0. More importantly, the callback function is triggered in the context of the current DOM element, so that the keyword refers to the item.this

<ul>
  <li>footer</li>
  <li>header</li>
</ul>
....
$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});
....
// footer
// header

Iterations can be stopped in the callback function by flipping false

The generic iterator jQuery.each()

jQuery.each() (or) is a generic iterator function, which can be used to iterate seamlessly on both objects and tables. Tables and table-type objects with a length property (such as the object arguments of a function) are iterated by numerical index, from 0 to length-1. Other objects are iterated through their named properties.$.each()

The function is not the same as , which is used to iter, exclusively, on a jQuery object. The feature can be used to iterate on any collection, be it an object or a painting. In the case of a table, the reminder is transmitted each time a table index and a corresponding table value. (The value can also be accessed by the keyword, but Javascript will always wrap that value as an object even if it’s a simple string of characters or a numerical value.) The method returns its first argument, the object that was iterated.$.each()$(selector).each()$.each()this

$.each([ 72, 37 ], function( index, value ) { alert( index + “: ” + value ); }); // 72 // 37
let obj = {
  "flammable": "inflammable",
  "duh": "no duh"
};
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});
// flammable: inflammable
// duh: no duh

Here too iterations can be stopped by returning to the callback functionfalse

The instruction for.. of ES6

ES6 introduced the loop for.. of which combines forEach’s brevity with the ability to stop iterations. It works on all iterable objects (including Array, Map, Object…)

//iterate over the value
for (const value of ['A', 'B', 'C']) {
  console.log(value) //value
}

//get the index as well, using `entries()`
for (const [index, value] of ['A', 'B', 'C'].entries()) {
  console.log(index) //index
  console.log(value) //value
}

Note the use of . This loop creates a new scope with each iteration, so we can use it safely instead of the keyword.constlet

The difference with the for. it is that the latter browses the names of the properties while the loop for.. itery on property values. In addition, manual additions are not taken into account in the for. of (unlike the for.loop. In)

let arr = [33, 55, 77];
arr.toto = "coucou";

for (let i in arr) {
  console.log(i); // displays 0, 1, 2, "foo" in the console
}

for (const i of arr) {
  console.log(i); // displays 33, 55, 77 in the console
}

As a bonus, some table methods introduced by ES5

The javascript method some()

Introduced in 2009 with EcmaScript 5, the method determines whether at least one element of the table matches the given predicate. It returns false only if none of the elements of the table meet the condition.some()

With the introduction of arrow functions in ECMAScript 2015, we can integrate the predicate function while maintaining legibility:

let arrs = [33, 55, 77];

console.log(arrs.some(x => x > 77)); // Display false
console.log(arrs.some(x => x > 55)); // Display true

Note that stops the iteration on the board as soon as it finds an item that matches the predicate. In this case, it returns immediately without inspecting the remaining items. some()true

The javascript method every()

The method is used to check a condition on all items in the table (or specified items) and returns if all items validate the condition and an item does not match that condition.every()truefalse

As before we can use the arrow functions for a shorter code while maintaining legibility:

let arr = [33, 55, 77];

console.log(arr.every(x => x > 33)); // Display false
console.log(arr.every(x => x > 22)); // Display true

In the same way as with , as soon as finds an element of table that does not correspond to the condition, it returns and does not iterate on the other elements.some()every()false

Conclusion

There are many ways to make javascript loops. We didn’t talk here about the while and do. while that are not really used (if you would ask me and I will be happy to add instructions in the article). I also didn’t mention the javascript map() method or the filter method() (but I did another article or I dissect and re-write these functions to better understand them; you can go and take a look if you’re curious)

Some bookstores like jQuery give us access to methods that made it easier to manage loops and iterations, but EcmaScript is evolving very quickly and it is no longer necessary to add external bookstores to create simple and readable code. (Some other bookstores such as time.js for date management remain unavoidable)

If you have any questions or additions to make, please let me know by leaving a comment