Skip to content

code does not what you think! Or am I the only one? #190

Answered by elxris
L2L2L asked this question in WTF Questions
Discussion options

You must be logged in to vote

You are not writting equivalent code, because in the first you are using the =! operator and store it in num variable. Then you use the ternary operator, and in the false condition of the operator you are using another ternary operator, but, if you are reaching the false side of the first operator you are always running ++n wich is leads something like false + 1 => 0 + 1 => 1.
This is the actual rewrite of the first function:

function okayJS2() {
  let num, num2, els, len, el, el2;
  els = arr;
  len = els.length;
  num = Math.floor(Math.random()*len);
  el = els[num];
  num2 = Math.floor(Math.random()*len);
  num =! num2 // This is an assigment operator and coerces the value to boolean
 …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by denysdovhan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #76 on February 05, 2021 14:55.