Isetty Ravitejakumar Isetty Ravitejakumar - 23 days ago 6
Javascript Question

difference between javascript foreach loop, and angular forEach loop.?

Iam new to angular framework. when i want to iterate json object in angular, i used javascript


Later i came to know that angular itself has a
loop to iterate objects.

How can i compare performance of
with javascript

Why we should use
instead of javascript

Please give me some examples and reasons to use it, which shows the performance.

Thanks :)


Angular forEach - Invokes the iterator function once for each item in obj collection, which can be either an object or an array.

var values = {name: 'misko', gender: 'male'};
angular.forEach(values, function(value, key) {
  console.log(key + ': ' + value);

// Output:
// "name: misko"
// "gender: male" - iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

var obj = {a:1, b:2, c:3};

for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

forEach - method executes a provided function once per array element.

// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(function (element, index, array) {
  console.log('a[' + index + '] = ' + element);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

In terms of performance it depends on the data structure you're working with, if it's an Array I will suggest using Angular.forEach or native forEach, if it's an Object will be the best, however it seems Angular.forEach handles object pretty well too. Depending on the amount of data you working with. If it's enormous I will suggest you use libraries like Lodash or Underscore, they handle data manipulation well.