Nested loops and conditionals
When we use loops inside loops or conditionals inside conditionals, this is called nesting. Let's see a few examples below:
Nested conditionals
Suppose our page receives two pieces of information about a person, her age and membership status (member / not a member). Then we need to show the price of a product based on the following rules:
We can start testing if age >= 65 or if the person is a member, in this case the product is free. If not, we then need to start another conditional because we still have two price possibilities.
var isMember = false;
var age = 25;
if (isMember == true || age >= 65) {
console.log('Free');
} else {
if (age < 18) {
console.log('$ 6.00');
} else {
console.log('$ 12.00');
}
}
// The console will show: $ 12.00'
Nested Loops
When dealing with multidimensional arrays and objects, it is fairly common to use nested loops.
Let's use an employees list as an example.
var employees = [
{
'name': 'Charles Silva',
'age': 45,
'children': ['Andrew Silva', 'Maria Silva']
},
{
'name': 'Elizabeth Green',
'age': 32,
'children': ['Peter Green']
},
{
'name': 'George Banks',
'age': 39,
'children': ['Philipp Banks', 'Rose Banks', 'Tara Banks']
}
];
<p>
List of Employees' Children:
<ul id="children">
</ul>
</p>
Can you send the list of all employees' children to the list above?
document.getElementById("children").innerHTML = "";
for (var a = 0; a < employees.length; a++) {
var childrenList = employees[a].children;
for (var b = 0; b < childrenList.length; b++) {
var child = childrenList[b];
document.getElementById("children").innerHTML += "" + child + " ";
}
}
List of Employees' Children:
- Print the names inside these li's