What does var {u,v,w} = x; mean in Javascript? [duplicate]
Asked Answered
I

3

6

I have seen this in a piece of JS code:

var {status, headers, body} = res;

What does it do?

Inescutcheon answered 4/3, 2011 at 6:26 Comment(5)
In some helma.org source code.Inescutcheon
See Destructuring assignment in JavaScript - Stack Overflow. Note that Javascript 1.7 (everything beyond 1.5, really) is effectively Mozilla-only.Indubitable
ephemient: Destructuring bind was my first thought, too, but I don't see any form that uses braces {} in the left-hand side.Kristie
To clarify what ephemient is saying: this will only work in Firefox. Chrome, Safari, & IE all don't support this.Pornocracy
I tried this in Rhino (Javascript 1.7) and, unsurprisingly, it just generates a syntax error. I don't see anything in the Javascript 1.8 or 1.8.1 release notes that looks quite like this, either.Kristie
E
1

nice method to set few variables at once from an object (open firebug and paste this to console)

var status=4;
var headers=4;
var body=4;

var res = {status:1, headers:2, body:3};
window.alert(status);
var {status, headers, body} = res;
window.alert(status);
Escarpment answered 4/3, 2011 at 6:38 Comment(0)
G
1

i read something different from your expression here . this may help u

 var { a:x, b:y } = { a:7, b:8 };
 Print(x); // prints: 7
 Print(y); // prints: 8
Gravely answered 4/3, 2011 at 6:34 Comment(0)
E
1

nice method to set few variables at once from an object (open firebug and paste this to console)

var status=4;
var headers=4;
var body=4;

var res = {status:1, headers:2, body:3};
window.alert(status);
var {status, headers, body} = res;
window.alert(status);
Escarpment answered 4/3, 2011 at 6:38 Comment(0)
G
0

Looks like a destructuring attempt on a variable named res. I've never seen that in Javascript and Chrome console suggests that it's an error:

> var res = [ 1, 2, 3 ];
> var {status, headers, body} = res;
SyntaxError: Unexpected token {

Firebug console on Firefox 4b12 doesn't complain however but the statement seems to have no effect:

> var res = [ 1, 2, 3 ];
> var {status, headers, body} = res;
> status
undefined
> headers
undefined
> body
undefined
Gilges answered 4/3, 2011 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.