xxxxxxxxxx
1 files failed to upload
File(s) public_html.zip failed to load:
Failed to open part of a file
For Loop
xxxxxxxxxx
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Example of For Loop
xxxxxxxxxx
for(let i = 0; i < arr.length; i++){
// code block to be executed
}
For In Loop
xxxxxxxxxx
for (key in object) {
// code block to be executed
}
Example of For In Loop
xxxxxxxxxx
for (let x in arr) {
// code block to be executed
}
For Of Loop
xxxxxxxxxx
for (variable of iterable) {
// code block to be executed
}
Example of For Of Loop
xxxxxxxxxx
for (let x of arr) {
// code block to be executed
}
While Loop
xxxxxxxxxx
while (condition) {
// code block to be executed
}
Example of While Loop
xxxxxxxxxx
while (i < 10) {
// code block to be executed
i++;
}
xxxxxxxxxx
// Arrow function
forEach((element) => { } )
forEach((element, index) => { } )
forEach((element, index, array) => { } )
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function callbackFn(element) { })
forEach(function callbackFn(element, index) { })
forEach(function callbackFn(element, index, array){ })
forEach(function callbackFn(element, index, array) { }, thisArg)
xxxxxxxxxx
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
xxxxxxxxxx
const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });
xxxxxxxxxx
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic for loop example improved</title>
<style>
</style>
</head>
<body>
<p></p>
<script>
const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
let info = 'My cats are called ';
const para = document.querySelector('p');
for(let i = 0; i < cats.length; i++) {
if(i === cats.length - 1) {
info += 'and ' + cats[i] + '.';
} else {
info += cats[i] + ', ';
}
}
para.textContent = info;
</script>
</body>
</html>