Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Arno Welzel Newsgroups: comp.lang.javascript Subject: Re: Understanding && Date: Mon, 19 Apr 2021 13:41:09 +0200 Lines: 68 Message-ID: References: <87wnt2e06e.fsf@bsb.me.uk> <87mttydm95.fsf@bsb.me.uk> <87lf9ga4gz.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit X-Trace: individual.net iAr9pkQo9xCiEQHYktYGfgLeH3Pvc61ucQrBKt4neNb0dcf+ki Cancel-Lock: sha1:Q+2dL1eLq9scwK2QxcJx2UM1upU= In-Reply-To: <87lf9ga4gz.fsf@bsb.me.uk> Xref: csiph.com comp.lang.javascript:39982 Ben Bacarisse: > Arno Welzel writes: [...] >> x = a && b; >> >> Nobody would expect that this *expression* will cause parts of the code >> to get executed or not > > Hmm... Everyone should expect that since that's what && means. Do you > mean && (as defined) should simply not exist is programming languages? No. It is just what I said - "a && b" is an expression which will not change anything in a or b because there is no additional code getting executed which might change a or b depending on the value of a. [...] >> The ??= operator was *intentionally* designed to work this way. > > That's a new one to me. I thought the 11th edition was the latest, and > it's not in there. I maybe got ??= from another language, I can't remember where I looked this up when I mentioned it, sorry. Just forget it. > That aside, I think && and || were intentionally designed to work as > they do, so intentional design can't justification enough in your mind. Ok, I need to clarify this: For an expression like "a && b" or "a || b" there is no obvious way how it will get evaluated. It's just a convetion that the evaluation will stop at the point where the remaining part does not *need* to be evaluated. a && b will evualate "a" first and stop, if a is false a || b will evualate "a" first and stop, if a is true But this is something one needs to know besides the fact that "&&" means "logical and" and "||" means "logical or". Therefore I call i at least bad style to rely on this fact and create code like return statement1 && statement2 && statement3 && statement4; instead of if (!statement1) { return false; } if (!statement2) { return false; } if (!statement3) { return false; } return statement 4; Yes, the latter one needs more lines but is obvious what the code does even if you don't remember that "&&" is evaluated from left to right and that the the evaluation stops at the first statement which returns false. -- Arno Welzel https://arnowelzel.de