OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

nullish check not working as expected when ternary is in right-hand expression [duplicate]

  • Thread starter Thread starter Millenjo
  • Start date Start date
M

Millenjo

Guest
Given this code:


Code:
const test = [1];
const test2 = 2;

const result = test.find((id) => id === 1) ?? "should not be this.";
console.log(result); // logs 1

const result2 = test.find((id) => id === 1) ?? true ? "true" : "false";
console.log(result2); // logs "true"

Why does the second log print "true" rather than 1? The left expression is not nullish so in my mind it is strange that the right hand ternary is even evaluated.

wrapping the ternary in parentheses works but it should not be needed?

<p>Given this code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const test = [1];
const test2 = 2;

const result = test.find((id) => id === 1) ?? "should not be this.";
console.log(result); // logs 1

const result2 = test.find((id) => id === 1) ?? true ? "true" : "false";
console.log(result2); // logs "true"</code></pre>
</div>
</div>
</p>
<p>Why does the second log print "true" rather than 1? The left expression is not nullish so in my mind it is strange that the right hand ternary is even evaluated.</p>
<p>wrapping the ternary in parentheses works but it should not be needed?</p>
 

Latest posts

J
Replies
0
Views
1
jbowerbir
J
Top