Splitting return values using destructuring

Question | Feb 3, 2016 | hkumar 

If you have been writing Javascript code for sometime chances are you came across a situation where you had to split an array (or object) returned by a function to scaler primitive variables. Let's look at some examples.

Split output of custom function:

function geoLocation() {
    //... stuff ....
    return [40.712, -74.005];
}

// To get the location co-ordinates in 2 variables 
var loc = geoLocation();
var longitude = loc[0], latitude = loc[1];

// ES6 way with destructuring
var [longitude, latitude] = geoLocation();

Javascript itself has some builtin functions like - String.split() - that return arrays. Here is how you split a name in ES6:

var [firstName, lastName] = 'Mark Twain'.split(' ');

Use it with regular expressions to give meaningful names to captured data:

var [, year, month, day ] = /^(\d+)-(\d+)-(\d+)$/.exec('2016-01-29');

Note that while destructuring, any target variable declared in left side that is not found in right side source object or array is set to undefined. For example b would set to undefined below:

var [a,b] = [3]; // a => 3, b => undefined

Let's go for a question. Look at below code and answer the following question:

var name = 'Eric Arthur Blair';
var [first, second, third] = name.split(' ');

if(typeof(third) != 'undefined')
 console.log('First:' + first + '|Middle:' + second + '|Last:' + third);
else
 console.log('First:' + first + '|Last:' + second);

What would be logged above?

2015 nextptr