Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Created January 2, 2019 00:22
Show Gist options
  • Save joe-oli/8cb319e92d783ef0005df80e479d9fa3 to your computer and use it in GitHub Desktop.
Save joe-oli/8cb319e92d783ef0005df80e479d9fa3 to your computer and use it in GitHub Desktop.
test breaking out of loops
/*
break out of loops
---------------------
test in node with:
>node loops-breakout
*/
//+++++ use for -loop; +++++++++++++++
console.log('starting for -loop...');
let selectedRows = {};
//add props(or keys) to object.
selectedRows.pk1 = false;
selectedRows.pk2 = false;
selectedRows.pk3 = true; //<==
selectedRows.pk4 = false;
selectedRows.pk5 = false;
for(var prop in selectedRows) {
console.log(prop); //logs the key name. i.e. pk1, pk2, etc...
console.log(selectedRows[prop]); //logs the key value i.e. false, false, etc...
if (selectedRows.hasOwnProperty(prop) && selectedRows[prop] ) { //own-prop not relevant here.. as those are the only props, but may be relevant in other cases.
break; //exits the for-loop, does not iterate to pk4,pk5 !!
//return; <-- you can also return, but note it returns from the whole script / module; does not continue below unless you wrap the loop in its own fn.
}
}
console.log('End for -loop.================');
console.log();
//+++++ use .some() -loop; +++++++++++++++
console.log('starting Array.some() loop...');
let myArray = [1,2,3,4,5,6];
myArray.some( function(item) { //use some instead of forEach;
console.log(item);
if (item === 3)
return true;
});
console.log('End .some() loop.================')
console.log();
//+++++ use .every() -loop; +++++++++++++++
console.log('starting Array.every() loop...');
let myArray2 = [1,2,3,4,5,6];
myArray2.every( function(item) { //forEach
console.log(item);
if (item > 3)
return false; //exit on the 4th-iterations; i.e. bypass below, and stop further iterations!
console.log('do stuff here...', item);
return true; //put this last to keep the iteration going; if you dont return anything, loop will stop after one iteration!
});
console.log('End .every() loop.================')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment