+ 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))

14th Sep 2021, 5:51 PM
Riya Chawla
Riya Chawla - avatar
4 Antworten
+ 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 😉
14th Sep 2021, 6:46 PM
Tim
Tim - avatar
+ 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]
14th Sep 2021, 6:17 PM
DavX
DavX - avatar
+ 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
14th Sep 2021, 6:22 PM
Pariket Thakur
Pariket Thakur - avatar
+ 1
Nick thanks
14th Sep 2021, 7:16 PM
Riya Chawla
Riya Chawla - avatar