Look at the 3 lines of code within this Javascript function. Assume that y will always be a String:
function example(x, y) {
var s = {};
s[y] = x;
return s;
}
Bearing in mind the following:
- Without wrapping it further within a function
- Without using
;
Is it possible to condense the 3 lines of code into one?
Yes, with a little ugly code:
The extra parameter
sis not passed into the function, it’s only there to be declared as a variable, so you don’t need the extra linevar s;. (If you don’t declare it locally it becomes a global variable, which is bad practice.)The value of the assignment
s = {}is what’s assigned, so you can make the assignment and then continue using the value in the expression.The comma operator returns the last value, e.g.
(1,2)returns the value2. That way you can add, sto the expression to make it returns.Edit:
Another variation is using
sas a variable in aforloop, and exit out of the loop: