Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

So your most likely going to be iterating through an array or an object, we'll start with an array;

var array = [1,2,3,4,5]; //your array

for(var i = 0; i<array.lengh; i++){

the only issue with that is that you are checking the length of the array every time, so instead you could do

for(var i = 0, len = array.length; i<len; i++){

note the comma, technically var i = a; var b; var c = whatever; is equivalent to var i = a,b,c = whatever;

lastly modern browsers have new way to modify an array in place like this, the previous two examples are equivalent to


yeah that was easy

now if you wanted the results of it like say the function

function doStuff(v){
return v;
for(var i = 0, len = array.length, out=[]; i<len; i++){

now out = [2, 3, 4, 5, 6];/on modern browsers you can use map so that is equivalent to; which btw you can also write an anonymous function{return v+1;});

now for objects say you have an object var obj = {a:1,b:2,c:3,d:4,e:5}; there is a shortcut

for(var key in obj){
    console.log(key+": "+obj[key])

this is the equivalent of

var keyz = keys(obj);

avoid doing var keys = keys(obj) as that overwrites the function, though keys(object) is actually a shortcut to Object.keys(object);

for(var i = 0, len = keyz.length;i<len;i++){
   console.log(keyz[i]+": "+obj[keyz[i]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment