-1

Why is the console displaying arrayNew? I'm hoping a condition where if the array includes the elements 'a' and 'b' only then the console displays arrayNew.Can someone help me there?

var arrayNew = ['a'];
if(arrayNew.includes('b' && 'a'))
  console.log(arrayNew);
  • 2
    Have you tried to check what `'b' && 'd'` yields? None of the conditions check whether two strings are part of that array, but whether the **evaluated** value of AND is part of that array – Nico Haase Jun 29 '21 at 10:25
  • 2
    Javascript isn't English. Your condition does not literally mean "arrayNew includes b and d"… – deceze Jun 29 '21 at 10:27

2 Answers2

2

&& evaluates as the left-hand value if that value is falsy and the right-hand value otherwise.

Since 'b' is a true value, 'b' && 'd' evaluates as 'd'. The array doesn't include that so arrayNew.includes('d') is false.

Since 'd' is a true value, 'd' && 'b' evaluates as 'b'. The array does include that so arrayNew.includes('b') is true.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Because 'b' && 'd' === 'd', the array doesn't include 'd', so the first if is false.

The second if is true because 'd' && 'b' === 'b' and 'b' is in the array.

If you want to know if it includes both values you must do

if (arr.includes('a') && arr.includes('b'))
deceze
  • 510,633
  • 85
  • 743
  • 889
Jazz
  • 341
  • 1
  • 6