function evensOnly(arr) {
// your code here
const arrEven = arr.filter((arr) => {
if (arr % 2 === 0) {
return arr;
}
console.log(arrEven);
});
}
// test
console.log(evensOnly([3, 6, 8, 2])); /// [6, 8, 2]
I got error that ‘cannot access "arrEven" before initializtion’
SyntaxError: Missing initializer in const declaration
4
Answers
you need to declare the
arrEven
variable before using it inside thefilter
methodIn JavaScript, when you use
const
to declare a variable, it must be initialized (assigned a value) at the time of declaration. In the original code,arrEven
was being used inside thefilter
method before declaring it, which caused the "Missing initializer in const declaration" error. By declaringarrEven
before thefilter
method, the error is resolved, and the code works as expected.The
console.log()
call shouldn’t be inside the filter callback function. The variable isn’t assigned untilfilter()
returns.You also shouldn’t be calling
console.log()
in the function at all. Your code expectsevensOnly
to return the filtered array, which is logged by the caller.You shouldn’t return the array element. The callback function is supposed to return a boolean value. If the array contains
0
,return arr
will return this, but0
is treated asfalse
, nottrue
, so it won’t be included in the result. The comparison returns a boolean, so just return that.And it’s confusing to use the same variable for the array being filtered and the parameter of the callback function. Use different names.
The error you’re encountering, "cannot access ‘arrEven’ before initialization," is because you’re trying to access the arrEven variable inside the filter callback function before it has been properly initialized. To fix this issue, move the console.log(arrEven) statement outside the filter callback function.
Others have correctly identified the primary issue with your code, which is that you’re attempting to access a variable within its declaration.
Furthermore, since
0
is falsy, you can simplify this a bit further with:I.e., you don’t need to capture the results of your
.filter()
in a temporaryarrEven
variable, and you also don’t need to explicitly compare with=== 0
.