In JavaScript, a loop is a control flow statement that allows you to execute a block of code repeatedly until a certain condition is met. There are several types of loops in JavaScript, including `for`, `while`, and `do-while`.
Here is an example of a `for` loop that counts from `1` to `5`:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
On the other hand, a function is a block of code that can be defined and executed by calling its name. Functions can take zero or more arguments, and they can return a value.
Here is an example of a function that takes a single argument `x` and returns the value of `x` multiplied by `2`:
function double(x) {
return x * 2;
}
console.log(double(4)); // Output: 8
In general, loops are used to execute a block of code multiple times, while functions are used to organize and reuse code. Loops are often used to iterate over arrays or perform some action a specific number of times, while functions are used to perform a specific task or calculate a value.
Comments (0)