//Array From Range With Curly Braces
const numbers = arrayFromRange(-10, -4);
console.log(numbers);
function arrayFromRange(min, max) {
const arr = [];
for (let i = min; i <= max; i++) {
arr.push(i);
return arr;
}
}
//Array From Range Without Curly Braces
const numbers = arrayFromRange(-10, -4);
console.log(numbers);
function arrayFromRange(min, max) {
const arr = [];
for (let i = min; i <= max; i++) arr.push(i);
return arr;
}
Why does removing the curly braces in the second function change the output?
in the first one you push one thing to the array then return it, second one you push to the array several time’s then return it.
You can miss off the brackets if there is a just a single expression (same with if statements, or any other loops). In the second example, the only thing that happens each time the loop runs is you push
.
The brackets contain a block of code, which can have multiple expressions. In the first example, you’re doing two things (push
to array and return
array). Because you return, the loop and function finish immediately once the line of code with the return on it runs for the first time.
1 Like
Thank you, this makes a lot of sense.