Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #14: forEach

$
0
0

After discussing how to create a range in the last post, we will discuss some of the array methods and how to use them to make your code more readable and concise.

First of all, I want to add that every array method uses the callback pattern. We’ll do a post on this pattern later, when discussing Asynchronous JavaScript, but for now you need to know that callbacks in these functions are called for every item in the array.

The easiest array method is called forEach and will just iterate over every item in the array.

	[1, 2, 3].forEach(function (item) { console.log(item); });

Most people will recognize this method. It iterates over every item and does nothing with the return value you provide. What most programmers don’t know is that you have some additional features in forEach.

	[1, 2, 3].forEach(function (item, index, array) { this.log(item);  }, console);

The forEach function lets you set the functions context (= this, more later) as well. In the previous example I injected console as the ‘this’ value in callback function.

But beware:

	function hasNumber (arr, number) {
		arr.forEach(function (item) { 
			if (item === number) return true; 
		});
	}

While this code might look okay, you must know that JavaScript’s forEach is still a callback function. Returning the value true inside the callback won’t result in the global function (hasNumber) to return true. You should refactor this code to

	function hasNumber (arr, number) {
		var found = false;
		arr.forEach(function (item){ if (item === number) found = true; });
		return found;
	}

By using the some-method you will get an even easier result, but more about that in a future post.



Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images