blob
blob

Reputation: 21

javascript: Cannot distinguish between 'true' and 'false' with array.every()

The script below encapsulates my non-understanding of .every(). Both outputs are "T", when I would have expected "F". Note that the only difference is that the array entries are strings in the first and numbers in the second. I have not had the same problem with .some(). Can someone explain please? Thanks.

let isNegative = curr => curr = "-1";
let isPositive = curr => curr = "+1";

let out1 = ["+1", "-1", "+1"].every(isPositive) ? "T" : "F";
console.log(out1); //->"T" instead of "F"

let out2 = [1, -1, 1].every(isPositive) ? "T" : "F";
console.log(out2); //->"T" instead of "F"

Upvotes: 0

Views: 52

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

you are using = (assignment operator), Because of this you getting the cur as return value. You should return a boolean value in every callback method.

const isNegative = curr => curr < 0;
const isPositive = curr => curr > 0;

const out1 = ["+1", "-1", "+1"].every(isPositive) ? "T" : "F";
console.log(out1); 

const out2 = [1, -1, 1].every(isPositive) ? "T" : "F";
console.log(out2);

const out3 = [1, "+1", 1].every(isPositive) ? "T" : "F";
console.log(out3);

Update: Here is more details on my above comments.

let isPositive = curr => curr = "+1";

// This method will be working like below
let isPositive2 = curr => {
  curr = "+1";
  return curr;  // Which is always "+1", which is truthy value
}


let out1 = ["+1", "-1", "+1"].every(isPositive2) ? "T" : "F";

// Here, Each every callback `isPositive2` will return "+1"
// Which means Boolean("+1") is true, So ["+1", "-1", "+1"].every(isPositive2) will return true irrespective of what ever the values of array.
// Event [false, 0].every(isPositive2) will return true

console.log(out1); 

console.log([false, 0].every(isPositive))
console.log([false, 0].every(isPositive2))

Upvotes: 1

Ravi
Ravi

Reputation: 2281

It should be == or ===

let isNegative = curr => curr == "-1";
let isPositive = curr => curr == "+1";

let out1 = ["+1", "-1", "+1"].every(isPositive) ? "T" : "F";
console.log(out1); //->"T" instead of "F"

let out2 = [1, -1, 1].every(isPositive) ? "T" : "F";
console.log(out2); //->"T" instead of "F"

Upvotes: 4

Related Questions