JavaScript: Swapping string variables without temporary variables - javascript

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

Related

Why am I allowed to use variable as property name in javascript object creation without using ES6 bracket notation? [duplicate]

The question I have is best given by way of this jsfiddle, the code for which is below:
var a = 1, b = 'x', c = true;
var d = {a: a, b: b, c: c}; // <--- object literal
var e = [a, b, c]; // <--- array
var f = {a, b, c}; // <--- what exactly is this??
// these all give the same output:
alert(d.a + ', ' + d.b + ', ' + d.c );
alert(e[0] + ', ' + e[1] + ', ' + e[2]);
alert(f.a + ', ' + f.b + ', ' + f.c );
What sort of a data structure is f? Is it just a shorthand for d?
var f = {a, b, c};
It came with ES6 (ECMAScript 2015) and means exactly the same as:
var f = {a: a, b: b, c: c};
It is called Object Literal Property Value Shorthands (or simply property value shorthand, shorthand properties).
You can also combine shorthands with classical initialization:
var f = {a: 1, b, c};
For more information see Property definitions in Object initializer.
It is an Object Initializer Property Shorthand in ES6.
var f = {a, b, c, d:1}; // Will be equal to {a:a, b:b, c:c, d:1}
This works because the property value has the same name as the property identifier. This a new addition to the syntax of Object Initialiser (section 11.1.5) in the latest ECMAScript 6 draft Rev 13. And of course, just like the limitations set from ECMAScript 3, you can’t use a reserved word as your property name.
Such a shorthand won’t dramatically change your code, it only makes everything a little bit sweeter!
function createCar(name, brand, speed) {
return { type: 'Car', name: name, brand: brand, speed: speed };
}
// With the new shorthand form
function createSweetCar(name, brand, speed) {
return { type: 'Car', name, brand, speed }; // Yes it looks sweet.
}
Please see the compatibility table for support for these notations. In non-supporting environments, these notations will lead to syntax errors.
This shorthand notation offers object matching pretty nicely:
In ECMAScript5 what we used to do:
var tmp = getData();
var op = tmp.op;
var lhs = tmp.lhs;
var rhs = tmp.rhs;
Can be done in ECMAScript6 with a single line of code:
var { op, lhs, rhs } = getData();
var f = {a, b, c}; // <--- what exactly is this??
It defines an object in JavaScript using the new ECMAScript 2015 notation:
As per Mozilla Developer Network:
"Objects can be initialized using new Object(), Object.create(), or using the literal notation (initializer notation). An object initializer is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({})."
var a = "foo",
b = 42,
c = {};
// Shorthand property names (ES6)
var o = { a, b, c };
is equivalent to:
var a = "foo",
b = 42,
c = {};
var o = {
a: a,
b: b,
c: c
};

Destructing assignment to swap the values in ES6

I am revising JavaScript and came to following ES6 example.
let a = 8, b = 6;
// change code below this line
[a,b] = [b,a];
// change code above this line
console.log(a); // a is 6
console.log(b); // b is 8
Not able to figure out how this is working, as we have assignment operator with both side arrays.
Destructuring basically separates an array or an object into separate variables. That is what happens on the left side. Exemple:
var foo = [1, 2]
var [a, b] = foo; // creates new variables a and b with values from the array foo
console.log(a); // prints "1"
console.log(b); // prints "2"
On the right side, you are creating an array with the values [b, a] which will be destructured. As a result, the two variables are switched.

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 [b][b = a,0] swap between a and b?

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);

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