Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign multiple variables at once in JavaScript?

Is there any way to perform multiple assignment in JavaScript like this:

var a, b = "one", "two";

which would be equivalent to this:

var a = "one";
var b = "two";
like image 920
mlibre Avatar asked Jul 16 '16 13:07

mlibre


2 Answers

In ES6 you can do it this way:

var [a, b] = ["one", "two"];

The above code is ES6 notation and is called array destructuring/object destructuring (if it's an object).

You provide the array on the right-hand side of the expression and you have comma-separated variables surrounded by square brackets on the left-hand side.

The first variable maps to the first array value and so on.

like image 114
Piyush.kapoor Avatar answered Oct 22 '22 20:10

Piyush.kapoor


While you cannot do var a, b = "one", "two";, and get them assigned to each variable in the respective order, you can do: var a, b; to initialize these variables as undefined.

You can also do var a, b = 'foo'; to assign b to 'foo', while initializing 'a' as undefined.

var a, b;

> a
--> undefined
> b
--> undefined
> var d, e;

> e
--> undefined

> f 
--> Uncaught ReferenceError: f is not defined

> var c, g = 'foo';

> c
--> undefined
> g
--> "foo"

Object destructuring

looks like:

const user = {
  id: 42,
  is_verified: true
};

const {id, is_verified} = user;

console.log(id); // 42
console.log(is_verified); // true 

You will also see this in JavaScript to import members of a module:

Import multiple exports from module. This inserts both foo and bar into the current scope.

import {foo, bar} from '/modules/my-module.js';
like image 36
Danny Avatar answered Oct 22 '22 21:10

Danny