How to destructure only the first index of an array

Viewed 3562

ESLint gives an error for link = link.split("?")[0]. It says to use array destructuring. But if i use array destructuring, then the code will be

let [ temp ] = link.split("?");
link = temp;

This results in the use of an extra variable. Is there another way to do it without creating an extra variable and avoiding the ESLint error. Thank You.

4 Answers

But if i use array destructuring, then the code will be...

You can destructure into an existing variable, you don't have to declare a new one. So instead, it would be:

[link] = link.split("?");

Live Example:

let link = "testing?one?two";
[link] = link.split("?");
console.log(link);

On occasion (for instance, when using object destructuring), you need parentheses to avoid parsing confusion:

let link;
let obj = {
    link: "example"
};
({link} = obj);
console.log(link);

Other times, if you like to rely on Automatic Semicolon Insertion rather than typing semicolons where they're required, you'll need the ; when doing array destructuring without a declaration. This is an error:

// Hazard if relying on ASI
let link = "testing?one?two?"
console.log("hi there")
[link] = link.split("?")
console.log(link)

Typically, the no-semicolon folks use a leading ; in this situation, e.g.:

;[link] = link.split("?")

You can do like this

With the help of array de-structuring.

let link = "hello?hahah";
[link] = link.split('?');
console.log(link);

[link] = link.split("?");

T.J.'s answer is the what you are looking for,

but mutating variables is not the best way of writing code. On the other hand destructing is just a clean way of writing code. If you see the transpiled code for the destructing part, you will find that a new variable is being set.

on a side note, eslint can't force you to do anything, if you are that concerned about performance you can allow link = link.split("?")[0] to stand,

please disable your prefer-destructuring config inside your .eslintrc.json,

{   
  "rules": {
    "prefer-destructuring": ["error", {"object": false, "array": false}]   
  } 
}
Related