Reputation: 5103
I came upon this piece of code let [a,,b] = [1, 2, 3];
javascript at the babel compiler website and it has made me curious. What is it doing exactly? How and where can I use it in a useful way?
Upvotes: 3
Views: 3500
Reputation: 602
It names: Destructuring. It is super useful for handling objects ands arrays.
I will try to give you a real example usage:
Imagine you are working with a form, where you have to pass some fileds of information through it, and save it in your database.
//Form:
Name: Donald
City: USA
Age: 45
You will need to pass this data, in some object called 'formData':
const formData = {name:'donald', city:'USA',age:45}
If you need to handle each object's element, you will have to write everytime:
console.log(formData.name) // => donald
console.log(formData.city) // => USA
console.log(formData.age) // => 45
With destructuring, you can rename this elements in variables:
const {name, city, age} = formData
You are assigning for each formData element a constant variable, easier to write and read it:
console.log(name) // => Donald
console.log(city) // => USA
console.log(age) // => 45
In your case, element between commas, it will be skkiped:
const array = [1,2,3]
const a,,c} = array;
console.log(a) // => 1
// b position will be skipped
console.log(c) // => 3
There is another feature part of destructuring: rest pattern (as @VLAZ said)
const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const [red,, yellow, ...otherColors] = rainbow;
console.log(otherColors); // ['green', 'blue', 'indigo', 'violet']
Check more examples and possible cases:
Upvotes: 1
Reputation: 5566
This is a concept known as destructuring, and you can read more about it here. The code you are asking about simply obtains the first and last items of an array, ignoring the one in the middle. It is used when you just don't care about a specific position in an array so you don't bother saving it to a variable (see the Ignoring some returned values section in the link above).
Upvotes: 1
Reputation: 34586
let [a,,b] = [1, 2, 3]
This is part of something called destructuring assignment.
The double comma denotes that a value (on the right side of the operation) should be skipped.
Ergo, a
will have the value 1 and b
will have 3. Nothing will be assigned the value 2.
Upvotes: 4