Skip to content Skip to sidebar Skip to footer

Unfamiliar Use Of Square Brackets During Multiple Variable Declaration In Javascript

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 v

Solution 1:

But what goes on under the hood?

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

// Split method help you to divide the string value according with the//indicated separator, in this examle the commavar [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

Solution 2:

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

Post a Comment for "Unfamiliar Use Of Square Brackets During Multiple Variable Declaration In Javascript"