3

I've noticed a weird behavior with .some() array method and a ternary operator.

It behaves differently when the integer(count) has to be incremented on each true case with and without the curly brackets.

Although, the console.log shows correct truthy on each iteration.

Any thoughts?

> let arr = ['011','202','3300']
undefined
> let count = 0;
undefined
> arr.some(k => k.includes('0') ? count++ : null);
true
> count;
2 // is not correct
> count = 0;
0
> arr.some(k => {k.includes('0') ? count++ : null});
false
> count;
3 // correct 
>
> arr.some(k => {k.includes('0') ? console.log('true') : null});
true
true
true
false
> arr.some(k => k.includes('0') ? console.log('true') : null);
true
true
true
false
Sgryt
  • 290
  • 3
  • 13
  • You need to know about fat arrow.... That is your issue. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions And some() is the wrong thing to be using here.... some() is checking to see if one thing is true.... again, read the documentation for some() – epascarello Mar 08 '19 at 02:40
  • Possible duplicate of [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces) – david Mar 08 '19 at 02:46

1 Answers1

3

Let's understand this

Why this one is giving output 2

arr.some(k => k.includes('0') ? count++ : null);

let count = 0;
let arr = ['011','202','3300']
arr.some(k => k.includes('0') ? count++ : null);

console.log(count)
  • So on first iteration count++ will return 0 and than increment value by 1. ( since it is post increment )

  • On second iteration it will return value as 1 which is true and than increment by 1. ( since you found one true value some will stop iteration )

Why this one is giving output 3

arr.some(k => {k.includes('0') ? console.log('true') : null});

let count = 0;
let arr = ['011','202','3300']
arr.some(k => {k.includes('0') ? count++ : null});

console.log(count)
  • Here you're not utilizing implicit return of arrow function so on each iteration you're eventually returning undefined. so your some will iterate through all the elements and you get output as 3.

Just add a return statement and see the changes.

let count = 0;
let arr = ['011','202','3300']
arr.some(k => { return k.includes('0') ? count++ : null});

console.log(count)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 1
    Could add that within `{}` nothing is being returned, hence always `false`. Apparently you read minds since you just added that – Neil Lunn Mar 08 '19 at 02:45