+ 1
Return statement in javascript
Why this code is returning value of ..a And not ...a*2 Var input=[2,6,9,0] function removeEven(input) { return input.filter(function(a){ if(a%2 !==0){ return a* 2 } }) } Console.log(removeEven(input))
5 Answers
+ 4
Riya Chawla
Simply put, the filter function returns either true or false. Since you're trying to return integers, everything will be treated as true unless it's 0. Because integers are truthy values by default in JavaScript, change that line of your code to what DavX has provided
For more information on truthy/falsy values:
https://developer.mozilla.org/en-US/docs/Glossary/Truthy#:~:text=All%20values%20are%20truthy%20unless%20they%20are%20defined,boolean%20contexts%2C%20and%20thus%20execute%20the%20if%20block%29%3A
My apologies for the lengthy link đ
+ 4
Riya Chawla
To start with you donât use !== to check ânot equalsâ. Simple use !=
I guess you are trying to remove even numbers from a list? Hereâs how you can do this:
var testInput = [2, 6, 9, 0];
function removeEven(num) {
return num % 2 != 0;
}
console.log(testIn.filter(removeEven));
This returns:
[9]
+ 2
The filter() method creates an array filled with all array elements that pass a test
What happens here is :
Input is an array with 2,6,9,0
Now u are using filter method to filter an array means u are getting the number which is noteven
Coz any number with is divisible by 2 returns 0 is odd
it will not change the original array
+ 1
Nick thanks