For loops, explained.
Another one of the absolute basic programming concepts are "loops".
The for
loop is one of the most common types of it.
So what is it and how does it work?
Let's explain:
A for
loop is basically a way of saying:
Here's a list of stuff, grab each one and do something specific with each one of them
This could be something like:
Here's a list of names, grab each one of them and display them on the screen
Or
Here's a list of text strings, check each one is under 5 characters long
"For" and "for each" loops are created for this very purpose. For example, in Python this is how you'd say:
Here's a list of names, grab each one of them and display them on the screen
names = ["Savvas", "Alice", "Bob"]
for name in names:
print(name)
In Javascript, there are two ways to do it.
With a "for" loop:
let names = ["Savvas", "Alice", "Bob"]
for(let i = 0 ; i < names.length ; i++){
console.log(names[i])
}
Or with a "for each" loop:
let names = ["Savvas", "Alice", "Bob"]
names.forEach((name) => {
console.log(name)
})
And to say:
"Here's a list of text strings, check each one is under 5 characters long",
in Javascript we could do:
let textStrings = ["a", "bbb", "cccccc"]
names.forEach((text) => {
if(text.length < 5){
console.log("The text is under 5 characters long")
}
else{
console.log("The text is NOT under 5 characters long")
}
})
In conclusion, "for" and "for each" loops are a straightforward ways to perform an action for each element in an array of strings, numbers or objects.
Dev, Explained (43 part series)
- Javascript Scopes, explained.
- Javascript Promises, explained.
- Accessibility, explained.
- React, explained
- Should I use forEach() or map()?
- Should I use Flexbox or CSS Grid?
- Docker, explained.
- Unit testing, explained
- Git, explained.
- Typescript, explained.
- async/await, explained.
- The DOM, explained.
- Regular expressions, explained
- GraphQL, explained.
- Vue, explained.
- Svelte, explained.
- API, explained.
- Javascript Hoisting, explained.
- Immediately Invoked Function Expressions (IIFE), explained.
- ARIA roles, explained.
- Test-driven Development, explained.
- ARIA live regions, explained.
- aria-label in accessibility, explained.
- Type coercion in Javascript, explained.
- Variables, explained.
- if statements, explained.
- Arrays, explained.
- Currying in Javascript, explained.
- Memoization, explained.
- For loops, explained.
- Javascript Prototypes, explained.
- React Hooks, explained.
- Graph databases, explained.
- MongoDB, explained.
- Serverless, explained.
- Javascript Callback functions, explained.
- HTML, explained.
- CSS, explained.
- Responsive design, explained.
- Javascript, explained.
- The CSS Box Model, explained.
- CSS Flexbox, explained.
- CSS Grid, explained.