Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #32374

Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)"

From Ben Bacarisse <ben.usenet@bsb.me.uk>
Newsgroups comp.lang.javascript
Subject Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)"
Date 2017-01-27 11:36 +0000
Organization A noiseless patient Spider
Message-ID <878tpwzqct.fsf@bsb.me.uk> (permalink)
References <o6eo1r$ifl$1@shakotay.alphanet.ch>

Show all headers | View raw


Une Bévue <unbewusst.sein@fai.invalid> writes:

> The expression :
> ws && ~[2, 3].indexOf(ws.readyState)
<snip>
> i did some tests :
>
> ~[2, 3].indexOf(1); // gives 0
> ~[2, 3].indexOf(2); // gives -1
> ~[2, 3].indexOf(3); // gives -2
<snip>
> ~[2, 3].indexOf(ws.readyState) equals 0 (logical false) when WebSocket
> is in ready state.
>
> then clearly the test is false when ws.readyState = 1, no attempt to
> reconnect using init(...).
>
> however when ws.readyState is of 2 or 3 what is the logical value of
> -1 
> or -2 ?
>
> does negative numbers have an equivalent logical value of false ?

Any non-zero number (other than NaN) is considered to be true in a
Boolean context.

The test ~[2, 3].indexOf(n) is a tricky way of testing if n is 2 or 3.
All the valid indexes (0 and 1) have bit-negations that are non-zero and
hence "true".  The return that indicates that n is not present (-1)
bit-negates to 0 which is taken to be false.

I'd write n == 2 || n == 3 but if there were lots of values to consider
I'd probably write [2, 3, 8, 9, 77, 102].indexOf(n) >= 0 instead.

-- 
Ben.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Une Bévue <unbewusst.sein@fai.invalid> - 2017-01-27 07:06 +0100
  Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-01-27 11:36 +0000
    Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2017-01-27 13:04 +0100
    Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Une Bévue <unbewusst.sein@fai.invalid> - 2017-01-27 18:00 +0100
      Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2017-01-28 10:41 +0100
        Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-01-28 15:33 +0000
    Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Une Bévue <unbewusst.sein@fai.invalid> - 2017-01-29 09:12 +0100

csiph-web