here is the code :
const str = "asdfcvb";
const result = str.split("").every((e) => {
return e==='a'||'b'});
console.log(result);
I expect str.split("") returns an array, and every method check if every element in the array equals to 'a' or 'b', which should return false, but it returns true
CodePudding user response:
Because
e==='a'||'b' means ((e==='a')||'b')
When the e !== 'a' case, it will return 'b' which is truthy in Javascript, so every method got truthy value from each term and then the result will be true.
You may use the follow to achieve what you want
const result = str.split("").every((e) => {
return (e==='a') || (e==='b')
});
CodePudding user response:
You can't omit the === from the second part of your condition. Right now what you're saying is either return e === 'a' or 'b'. When e is not equal to 'a' it returns 'b'. Which is truthy and when turned into a boolean it becomes true. Run this in the browser:
'a' === 'b' || 'c'
If you run it you see that it returns 'c'. The same happens in your callback. You have to change your return statement to this for it to work:
return e === 'a' || e === 'b'
CodePudding user response:
Everything seems correct. The problem is in the way you compared the strings
you should compare those like e === "a" || e === "b"
and the working code
const str = "asdfcvb";
const result = str.split("").every((e) => {
return (e === "a" || e === "b")});
console.log(result);
Explanation:
return e==='a'||'b'
running the test for the first item which is "a" will return true as now e is "a" here, which is equal to "a".
now if it gets to second item which is "s" and obviously not equal to "a" so return e==='a'||'b' becomes return false||'b' and now when you evaluate this the returned value will be "b"
and putting "b" as a condition is similar to true cause it is not undefined or null
this can be tested as follows
if("b") return true; // returns true
Thus it returns true for every item thereby returning true at last
