Last active
July 29, 2018 16:38
-
-
Save andrelandgraf/c1c9888fdeb74b15494ebd1cd4a28aba to your computer and use it in GitHub Desktop.
working over arrays with for loops in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summarized and added comments, original source: https://es6.io/ course by Wes Bos | |
// messing with the prototype | |
Array.prototype.myFunction = function(){ | |
// add some array functionality | |
}; | |
// initialising our array | |
const names = ["Alice", "Foo", "Bar", "Jon Doe"]; | |
// adding some further properties | |
names.furtherProperty = "Madness"; | |
// normal for loop | |
// + : works as expected | |
// - : old school :P | |
for(let i = 0; i < names.length; i++){ | |
console.log(names[i]); | |
} | |
/* | |
* Output => | |
* Alice | |
* Foo | |
* Bar | |
* Jon Doe | |
*/ | |
// foreach callback loop | |
// + : works as expected | |
// - : you cannot call break; or continue; like you would in a for loop (callback function, no real loop) | |
names.forEach(value => { | |
console.log(value); | |
}); | |
/* | |
* Output => | |
* Alice | |
* Foo | |
* Bar | |
* Jon Doe | |
*/ | |
// for in loop | |
// + : nice syntactic sugar | |
// - : does iterate over content of array, added prototype functions and further properties | |
for(const i in names){ | |
console.log(names[i]); | |
} | |
/* | |
* Output => | |
* Alice | |
* Foo | |
* Bar | |
* Jon Doe | |
* Madness | |
* [Function] | |
*/ | |
// for of loop | |
// + : nice syntactic sugar | |
// + : allows break; and continue; | |
// + : works as expected | |
for(const name of names){ | |
console.log(name); | |
} | |
/* | |
* Output => | |
* Alice | |
* Foo | |
* Bar | |
* Jon Doe | |
*/ | |
// additionally, we can also access the index like that: | |
for ( const [i, name] of names.entries()){ | |
// we are iterating over the ArrayIterator | |
console.log(name); | |
console.log(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment