Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!news2.arglkargh.de!news.swapon.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: John-Paul Stewart Newsgroups: comp.lang.javascript Subject: Re: Why does (a,b,c) return only c? Date: Mon, 25 May 2015 13:58:39 -0400 Lines: 52 Message-ID: References: <55630af5$0$13000$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net 0f4ZQ7w94DGwl8OmXiJfFgLW0SAcfudOAyPZ0LWeelN1pRom1C X-Orig-Path: mail.binaryfoundry.ca!not-for-mail Cancel-Lock: sha1:lhRdZpuR59y7F5MEzObMowhCkpk= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Icedove/31.7.0 In-Reply-To: <55630af5$0$13000$c3e8da3$5496439d@news.astraweb.com> Xref: csiph.com comp.lang.javascript:27871 On 25/05/15 07:43 AM, Steven D'Aprano wrote: > Consider: > > js> var x = (1,2,3); > js> x > 3 > > > I expected an error, or an array, or something other than just 3. What's the > explanation for only the last value being returned? I presume it's a > deliberate design feature. Yes, it's a design feature. See, for example: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator "The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand." > Under what circumstances would I use it? > > I came across this trying to swap two variables. This was my first attempt, > but I'm afraid that I don't understand what is happening here: > > js> var a = 1; > js> var b = 3; > js> a, b = b, a; // swap a and b around > 1 > js> print(a, b); > 1 3 > > > On the swap line, if the right hand side evaluates as only a single value, I > expected any of these behaviours: > > (1) an error (can't assign two targets on the left to one on the right); > > (2) the "a," on the left gets dropped, and the "b," on the right gets > dropped, so we end up with "b = a" only; > > (3) a gets assigned to undefined, and b to 1; > > (4) or a to 1 and b to undefined. > > Obviously all of my guesses are wrong. What is actually happening there? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence If you read up on operator precedence, you'll see the comma has the lowest precedence of all operators. So your attempt at swapping is actually parsed as 3 statements: "a", "b = b", "a". That should make it clear why the values don't change and why there's no error.