Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js for loops

// Sample Data:
const days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]

// Samle Data which has undefined items:
const days = ["Monday","Tuesday",,"Thursday",,"Saturday","Sunday"]

// This Post might be a good read, to see a few caveats and advantages:
// https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea

//Classic For Loop using 3 expressions iterates all array indexes:
for (let i=0; i<days.length; i++){
    console.log("Day: "+days[i])
}

//for..in iterates defined array indexes:
for (let day in days){
    console.log("Day: ", days[day]);
}

//for..of iterates all array items:
for (let day of days){
    console.log("Day: ", day);
}

//using array methods might be more suitable depending on the scenario:
days.forEach(function(day){
    console.log("Day: ", day);
});
//available methods:
days.forEach()
days.map()
days.filter()
days.reduce()
days.every()
days.some() //this one is neat imo
...
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #js #loops
ADD COMMENT
Topic
Name
9+3 =