How does [b][b = a,0] swap between a and b? - javascript

As gdoron pointed out,
var a = "a";
var b = "b";
a = [b][b = a,0];
Will swap a and b, and although it looks a bit of hacky, it has triggered my curiosity and I am very curious at how it works. It doesn't make any sense to me.

var a = "a";
var b = "b";
a = [b][b = a, 0];
Let's break the last line into pieces:
[b] // Puts b in an array - a safe place for the swap.
[b = a] // Assign a in b
[b = a,0] // Assign a in b and return the later expression - 0 with the comma operator.
so finally it is a =[b][0] - the first object in the [b] array => b assigned to a
Live DEMO
read #am not I am comments in this question:
When is the comma operator useful?
It's his code...

It might help (or hinder) to think of it terms of the semantically equivalent lambda construction (here, parameter c takes the place of element 0):
a = (function(c) { b = a; return c; })(b);

Related

What is the correct way to assign the same value to several variables

The following code produces the same result in both options (Chrome & Firefox).
// short option
var a = b = c = d = e = 1;
console.log(a,b,c,d,e)
// long option
var a = 1, b = 1, c = 1, d = 1, e = 1;
console.log(a,b,c,d,e)
Perhaps the question for some seems obvious or silly but which of these two options is the correct one or should I use and why?
The "short option" is almost certainly the wrong one to use, because it will either implicitly create global variables, or throw an error in strict mode:
'use strict';
var a = b = c = d = e = 1;
console.log(a, b, c, d, e)
Better to use the longer version.
But usually, in a situation like this, where you have multiple variables with somewhat similar purposes, it'd be more appropriate to use an array or object, rather than to have lots of separate identifiers. (Not always, but often)

JavaScript: Swapping string variables without temporary variables

I know it's possible in JavaScript to swap two integer values with the XOR option, thus eliminating the need of a temporary variable:
a = 14; b = 27; a^=b; b^=a; a^=b;
// a == 27 and b == 14
But is there a similar no-temp technique in JavaScript for swapping strings?
Alternative swapping methods
ES6 only
ES6's new destructuring assignment syntax:
[a, b] = [b, a]
ES5 compatible
There is an universal single line swapping method that doesn't involve creating new temp variables, and uses only an "on-the-fly" array, here it is:
var a = "world", b = "hello";
b = [a, a = b][0];
console.log(a, b); // Hello world
Explanation:
a=b assigns the old value of b to a and yelds it, therefore [a, a=b] will be [a, b]
the [0] operator yelds the first element of the array, which is a, so now b = [a,b][0] turns into b = a
Then, for strings only, you can also do this:
var a = "world", b = "hello";
a = b + (b = a, "");
console.log(a, b); // Hello world
You can replace the "" with a 0 if you want to do this with numbers.
Explanation:
(b = a, "") assigns the old value of a to b and yelds an empty string
now you have a = b + "", and since that b + "" === b, the old value of b is assigned to a
Performance benchmarks
At this page you can find and run a benchmark of different swapping methods. The result of course varies between browser and JS engine versions.
Here comes a ES6 solution
We can do the Destructuring Assignment and swap like a boss.
var a = "Hello", b = "World!";
console.log(a, b); // Hello World!
[a, b] = [b, a]; //
console.log(a, b); // World! Hello
We can use string replace() method to achieve this!
By using regular expression: "/(\w+)\s(\w+)/"
const name = "Akash Barsagadey";
const swapName = name.replace(/(\w+)\s(\w+)/, "$2 $1");
console.log(swapName); //Barsagadey Akash

In javascript, what do multiple equal signs mean? [duplicate]

This question already has answers here:
Javascript a=b=c statements
(6 answers)
Closed 9 years ago.
I saw this code somewhere, but what does it mean? (all a, b, c are defined previously)
var a = b = c;
It quickly assigns multiple variables to a single value.
In your example, a and b are now equal set to the value of c.
It's also often used for a mass assign of null to clean up.
a = b = c = d = null;
Assign c to b.
Assign b to a.
So if I say var a = b = 1;
>>> var a = b = 1;
undefined
>>> a
1
>>> b
1
This means a, b and c are the same reference.
For example:
var c = {hello: "world"};
var a = b = c;
// now all three variables are the same object
It's a shorthand for:
var a;
var b;
b=c;
a=b;
It's meant as a combination of assigning the same value to two or more other variables, and declaring these variables in local scope at the same time.
You can also use this syntax independently of the var declaration:
var a;
var b;
a=b=c;

how does this two varibles exchange using one line? [duplicate]

This question already has answers here:
How does [b][b = a,0] swap between a and b?
(2 answers)
Closed 9 years ago.
I do not know how to learn demo 2,because it's difficult for me.
//demo1.js
var a = 1;
var b = 2;
var c;
c = b;
b = a;
a = c;
log(a); // a = 2
log(b); // b = 1 I can read this one.
//demo 2.js
var a = 1, b = 2;
a = [b][b = a, 0]; // why? '0' is a varible?
console.log(a,b) //output a = 2, b =1
// v---- 1. v---- 3.
a = [b][b = a, 0];
// ^---^-- 2.
Put the value of the b variable in a new Array.
The next set of square brackets is the member operator used for getting the index. In this case, that space is being used to reassign the value of the a variable to the b variable. This can be done because the original value of b is safely in the Array (from step 1.).
Separated by comma operator, the 0 index is then used as the actual value of the Array being retrieved, which if you'll recall is the original b value. This is then assigned to a via the first = assignment on the line.
So to summarize, b is put in the Array, and is retrieved via the 0 index and assigned to a on the left, but not before a is assigned to b (borrowing the space of the [] member operator).
This could also be written like this:
a = [b, b = a][0];
Only difference now is that the second index of the Array is used to do the assignment. Probably a little clearer like this.
The comma operator in Javascript evaluates its left operand, throws it away and returns its right operand after evaluating. Its only use is when the left operand has a side-effect (like modifying a variable's value) but you don't want its result.
[b] defines an array containing b.
[b = a, 0] evaluates b = a - so b now contains the value of a. Then it throws it away. Then it takes the element at index 0 of [b] - returning b. a now contains the value of b that was stored there, rather than the up-to-date value of b, so our swap is successful (albeit obfuscated).

Brackets in variable initialization

I've made an experiment in JavaScript:
var x=[ "1","2","3","4","5","6"];
c=(b = x)[2] ; //<--- what is this syntax?
alert(b ); // 1,2,3,4,5,6
alert(c ); // 3
I figured it out how it works. It saves me a line of equalization. Still, I was wondering about this strange syntax. How is it called and where can I read about it?
= operator returns a value being assigned so (b = x) returns value of x. That results in x[2] being assigned to c.
(note: "returns x" changed to "returns value of x" according to comments)
See below
b=x assigning the data of x to b and hence you are getting alert as 1,2,3,4,5,6
c=(b=x)[2] is displaying the second content of array i.e. 3.
Below is how c=(b=x)[2] works
c=(b=x)[2]
b=x
c=b[2]
let me know if you need further details...
this happens because of an assigment operator returns value in java script.
Think about it like this:
You make an assignment:
b = x;
Now in object oriented terms, its like invoking a method = on b with an x as an argument
b.=(x)
Here the '=' is like a method name
Now if its the method, why it can't return a value (its return type is other than void)?
Here you can find some additional explanation about this:
Link1
Link2
Hope this helps
var x = ["1","2","3","4","5","6"];
c=(b = x)[2]; // b = x; -> shallow copy of the array
// b -> now hods the array of x
// b[2] -> get the second element of the array
alert(b ); // b is pointing to the array
alert(c ); // c has the 3-rd element (array counting is from 0 - 0,1,2)
b.push("7"); // we add a new item to the array
alert(b); // 1,2,3,4,5,6
alert(x); //1,2,3,4,5,6,7 !
The same code can be written as:
var x = b = ["1","2","3","4","5","6"], c = b[2];
console.log(b); //=> 1,2,3,4,5,6
console.log(c); //=> 3
Or even:
var c = (x = b = ["1","2","3","4","5","6"])[2];
console.log(b); //=> 1,2,3,4,5,6
console.log(c); //=> 3
In var c = (b=x)[2], the parentheses force b=x to execute first. In both cases anyhow, when for example used within a function scope, the statement would create variable b in the global scope, so I would consider it bad practice.

Categories

Resources