Differencebetween for and Foreach

What's the difference between 'for' and 'foreach' in Perl?

There is no difference. From perldoc perlsyn:

The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

JavaScript: Difference between .forEach() and .map()

They are not one and the same. Let me explain the difference.

forEach: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database) and does not return anything.

map: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase). It does not mutate the array on which it is called (although the callback function may do so).

References

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN

For Loop vs Foreach Loop

The for loop is a construct that says "perform this operation n.times".

Example -

int n = 5; // You can assign any preferred value  
for(int i=0; i<n; i++){
(your operation); // it will be in 5 times
}

The foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"

Example -

List<string> names= new List<string>();

names.Add("Tom");
names.Add("Denver");
names.Add("Nash");
names.Add("Cheruu");
names.Add("Amy");

foreach(string name in names)
{
Console.WriteLine(name);
}

You can find more details from here.

Difference between forEach and for loop in javascript

forEach is a method on the Array prototype. It iterates through each element of an array and passes it to a callback function.

So basically, forEach is a shorthand method for the use-case "pass each element of an array to a function". Here is a common example where I think Array.forEach is quite useful, compared to a for loop:

// shortcut for document.querySelectorAll
function $$(expr, con) {
return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}

// hide an element
function hide(el) {
el.style.display = 'none';
}

// hide all divs via forEach
$$('div').forEach(hide);

// hide all divs via for
for (var divs = $$('div'), i = 0; i < divs.length; i++) {
hide(divs[i])
}

As you can see, the readability of the forEach statement is improved compared to a for loop.

On the other hand, a for statement is more flexible: it does not necessarily involve an array. The performance of a normal for loop is slightly better, because there is no function call for each element involved. Despite of this, it is recommended to avoid for loops when it can be written as a forEach statement.

Differences between for and foreach in JavaScript 5

The for keyword is a language construct, this is the fastest and most "raw" way to iterate over things. It has three styles:

  1. The C-style for: for ( initializer; condition; iterator ) { code... } - this one is the most flexible and time-tested version. To iterate over a list, you start going over all list indexes from 0 to the list's length. You can also
    go over every other, third etc element. Most of the time, this is good enough.

  2. The Javascript for-in for (var key in object) { code ... } - this one is a good way to go over every key in an object, for example, to output all values of a JSON object.

  3. (ES2015) The Javascript for-of: for (var item of collection) { code ... } - this one is new and available in modern browsers. It lets you skip the indexes and counters, and lets you walk over every item of a collection. (Say, every object in a products list.) It does the same thing as the C-style for, but is easier to use.

However, the forEach function is specific to Array objects in Javascript, and lets you run a function for every item in an array. It's good if you have an utility function that does all the work for you.

Here's how to use all of the above kinds of iteration:

// most plain kind of array with a length of 7
var myArray = [1, 2, 3, 4, 5, 6, undefined];
// a weird kind of array with no values between index 3 and 100
// its length is 102
var mySparseArray = [1, 2, 3, 4];
mySparseArray[100] = 5;
mySparseArray[101] = 6;

// 1. C-style for
// ** can control how index is incremented
// ** needs an extra variable to iterate with
for (var i = 0; i < myArray.length; i += 1) {
console.log(myArray[i]);
// logs 1, 2, 3, 4, 5, 6, undefined
}

for (var i = 0; i < mySparseArray.length; i += 1) {
console.log(myArray[i]);
// logs 1, 2, 3, 4, undefined, undefined, ... (up to index 100), 5, 6
}

// 2. for..in
// ** keys are iterated over in non-guaranteed order
// (you might get 2, "length", 1, 0, 3)
// ** all enumerable keys are included, that might include things other than indexes.
for (var key in myArray) {
console.log(myArray[key]);
// logs 1, 2, 3, 4, 5, 6
}

for (var key in mySparseArray) {
console.log(mySparseArray[key]);
// logs 1, 2, 3, 4, 5, 6
// this for-loop "thinks" the array is an object with numbers for keys
}

// 3. for..of
// ** only available in browsers with ES2015 support
// ** supports many other things than Arrays - TypedArrays, Iterators...
for (var item of myArray) {
console.log(item);
}

for (var item of mySparseArray) {
console.log(item);
// logs 1, 2, 3, 4, undefined, undefined, ... (up to index 100), 5, 6
}

// 4. forEach
// ** calls a function for each element (considered slow)
// ** supports only Arrays (unless you call it with Array.prototype.forEach.call)
function myCallback(element) {
console.log(element);
}
myArray.forEach(myCallback); // logs 1, 2, 3, 4, 5, 6
mySparseArray.forEach(myCallback); // logs 1, 2, 3, 4, 5, 6

Make sure to try these out in your browser's developer console! You can see each of the above pieces of code in action.

Make sure to check out the MDN reference on iterations.

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

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"

for..in - 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 for..in 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.

What's the difference between for and foreach in respect to closure

This is the result of an unfortunate decision that was later regretted by the C# team. A breaking change introduced by C# 5 finally changed that behavior. Quoting Eric Lippert:

In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

Before C# 5, the closures all referenced the same variable binding. Therefore, the output was the same for all invocations because they were all accessing the latest value of the same variable.

Starting with C# 5, however, a new variable binding is created for each iteration. This is the behavior that was most likely intended by the programmer.

Difference between foreach and forelse in Laravel

I believe the answer to your question is that, essentially, ForElse is a ForEach loop, but with extra handling for empty array.

From the Laravel 5 docs on Blade Templates, an example illustrating both loops with the same list of Users as Input:

@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse

Now if we compare this to the source code for the Laravel Framework to see how the loops are compiled (all Blades constructs are compiled into HTML when being rendered by PHP on the web page):

   /**
* Compile the for-each statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileForeach($expression)
{
preg_match('/\( *(.*) +as *(.*)\)$/is', $expression, $matches);

$iteratee = trim($matches[1]);

$iteration = trim($matches[2]);

$initLoop = "\$__currentLoopData = {$iteratee}; \$__env->addLoop(\$__currentLoopData);";

$iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();';

return "<?php {$initLoop} foreach(\$__currentLoopData as {$iteration}): {$iterateLoop} ?>";
}

/**
* Compile the for-else statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileForelse($expression)
{
$empty = '$__empty_'.++$this->forElseCounter;

preg_match('/\( *(.*) +as *(.*)\)$/is', $expression, $matches);

$iteratee = trim($matches[1]);

$iteration = trim($matches[2]);

$initLoop = "\$__currentLoopData = {$iteratee}; \$__env->addLoop(\$__currentLoopData);";

$iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();';

return "<?php {$empty} = true; {$initLoop} foreach(\$__currentLoopData as {$iteration}): {$iterateLoop} {$empty} = false; ?>";
}

Essentially, the ForElse loop has a built-in code and compile check for an empty input, in which case it optionally outputs an alternate display template for the empty input.

I would imagine you can use a ForEach loop in every case that you might use a ForElse loop, adding that you include and empty checks that ForElse might catch for you.


Links for reference:

  1. Blade Templates
  2. Blade View Compile Functions


Related Topics



Leave a reply



Submit