Hello, I have a question about curly braces, especially when to use them.
const array = [null,'',1,2,3]
console.log(countTruthy(array));
function countTruthy(array){
let count = 0;
for (let value of array)
if (value) count++;
return count;
}
In this case, it will return 3, which is correct, the array has 3 truthy.
However, if I put curly braces after for(let value of array), like below, it returns 0.
const array = [null,'',1,2,3]
console.log(countTruthy(array));
function countTruthy(array){
let count = 0;
for (let value of array){
if (value) count++;
return count;
}
}
OR
const array = [null,'',1,2,3]
console.log(countTruthy(array));
function countTruthy(array){
for (let value of array){
let count = 0;
if (value) count++;
return count;
}
}
Another example, there are curly braces after for (let i = 0; i<=limit; i++), it shows the result correctly with all the numbers and the even/odd message.
showNumbers(10);
function showNumbers(limit){
for (let i = 0; i<=limit; i++){
const message = (i % 2 === 0) ? 'EVEN' : 'ODD';
console.log(i,message);
}
}
However, if I remove the curly braces like below, it will return error message: unexpected token ‘const’.
showNumbers(10);
function showNumbers(limit){
for (let i = 0; i<=limit; i++)
const message = (i % 2 === 0) ? 'EVEN' : 'ODD';
console.log(i,message);
}
Why is it?