JavaScript loops and string concatenation:
- The
for
loop is used when the number of iterations is known beforehand. - Syntax:
for (initialization; condition; increment/decrement) { // code to be executed }
- Example:
for (let i = 0; i < 5; i++) { console.log("Iteration: " + i); }
- Explanation:
The loop starts with initialization, checks the condition, and executes the block if the condition is true. Then it performs the increment/decrement operation and repeats the process.
- The
for/in
loop is used to iterate over the properties (keys) of an object. - Syntax:
for (key in object) { // code to be executed }
- Example:
const person = {name: "Alice", age: 25, city: "New York"}; for (let key in person) { console.log(key + ": " + person[key]); }
- Explanation:
This loop iterates over each property in theperson
object and prints the key-value pairs.
- The
for/of
loop is used to iterate over iterable objects like arrays, strings, or other collection types. - Syntax:
for (variable of iterable) { // code to be executed }
- Example:
const fruits = ["apple", "banana", "cherry"]; for (let fruit of fruits) { console.log(fruit); }
- Explanation:
This loop iterates over each element in thefruits
array and prints the element.
- The
while
loop is used when the number of iterations is not known, and the loop continues as long as the condition is true. - Syntax:
while (condition) { // code to be executed }
- Example:
let i = 0; while (i < 5) { console.log("Iteration: " + i); i++; }
- Explanation:
The loop checks the condition before executing the block. If the condition is true, the code is executed, and the process is repeated until the condition becomes false.
- The
do/while
loop is similar to thewhile
loop, but it guarantees that the code block is executed at least once. - Syntax:
do { // code to be executed } while (condition);
- Example:
let i = 0; do { console.log("Iteration: " + i); i++; } while (i < 5);
- Explanation:
The code block is executed first, and then the condition is checked. If the condition is true, the loop continues.
- Using
console.log
:- You can concatenate strings and variables using the
+
operator. - Example:
let name = "Alice"; console.log("Hello, " + name + "!");
- You can concatenate strings and variables using the
- Using Template Literals (Backticks):
- Template literals allow embedding variables and expressions within strings using
${}
inside backticks (`
). - Example:
let name = "Alice"; console.log(`Hello, ${name}!`);
- Template literals allow embedding variables and expressions within strings using
- Explanation:
Template literals provide a more readable way to concatenate strings and variables, especially when dealing with multiple variables or expressions.