Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: understanding the expression "ws && ~[2, 3].indexOf(ws.readyState)" Date: Fri, 27 Jan 2017 11:36:50 +0000 Organization: A noiseless patient Spider Lines: 36 Message-ID: <878tpwzqct.fsf@bsb.me.uk> References: Mime-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="3b591314b8affd39d0054b2ccd164f7b"; logging-data="17052"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19W4saor+JfunDnY23DDfRXgQmFZmfQ/qE=" Cancel-Lock: sha1:w+sMYyzb/ZwOonh6UUkXShr9JqQ= sha1:5C/z0lvf7/GPuMqUs9hWjgY6n1I= X-BSB-Auth: 1.0f3cbef48d672f3ebb68.20170127113650GMT.878tpwzqct.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:32374 Une Bévue writes: > The expression : > ws && ~[2, 3].indexOf(ws.readyState) > i did some tests : > > ~[2, 3].indexOf(1); // gives 0 > ~[2, 3].indexOf(2); // gives -1 > ~[2, 3].indexOf(3); // gives -2 > ~[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.