4

I'm a beginner to Javascript and encountered this syntax usage(simplified):

var testString ="firstName, lastName";
var [a,b] = testString.split(", ");

My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.

But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.

Theo
  • 55
  • 4
  • 3
    It's a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), an ES6 feature. – Spencer Wieczorek Oct 20 '17 at 03:10

2 Answers2

4

But what goes on under the hood?

// You declare a string variable
var testString = "firstName, lastName";

// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Since the split function returns an array, with the var [a,b] = array you are assigning the value in index order, in the example:

console.log(a); // 'firstName'
console.log(b); // 'lastName'

And they are simple string variables. You may want to vist the links below:

Destructuring asignation

split function

Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post

ricardoorellana
  • 1,846
  • 19
  • 30
  • Thanks for the informative breakdown and links. Interesting that no eventual array was created in the process but only a & b as string primitives. – Theo Oct 20 '17 at 03:36
  • Yes it is, also you can use the rest operator `var [a, b, ...c] = [1, 2, 3, 4];` what value do you think is going to hold the variable `c`? – ricardoorellana Oct 20 '17 at 03:46
  • `c` contains an array (The rest values that were not assigned "individually") – ricardoorellana Oct 20 '17 at 03:53
  • Thanks Ricardo, I learnt something new about the **... rest operator** too. I've actually been starting to read the You don't know Js by Kyle Simpson, but some parts are abit hard to comprehend at once, so I'll probably have to do more exercises and re-read the chapters again. – Theo Oct 20 '17 at 06:23
1

This is destructuring assignment. It resembles the pattern-matching found in many functional languages.

Ryan Plant
  • 967
  • 1
  • 9
  • 18