DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on • Edited on

How to de-structure an array returned by url.pathname.split(‘/’)

There is a nice trick to skip the empty string returned by the url.pathname.split(‘/’). “url” is a variable with the following, for example:

const url = new URL("https://medium.com/p/bfd60bf42c62/edit");
url;
Enter fullscreen mode Exit fullscreen mode

Copy and paste the above code snippet into this browser console.

Looking to practice and elevate your frontend skills? checkout https://tthroo.com for SaaS project based tutorials.

You will find that it logs the below object:

{
  hash: "",
  host: "medium.com",
  hostname: "medium.com",
  href: "https://medium.com/p/bfd60bf42c62/edit",
  origin: "https://medium.com",
  password: "",
  pathname: "/p/bfd60bf42c62/edit",
  port: "",
  protocol: "https:",
  search: "",
  searchParams: URLSearchParams {size: 0},
  username: "",
}
Enter fullscreen mode Exit fullscreen mode

Type the below into the console:

url.pathname.split("/");
const [var1, var2, var3] = url.pathname.split("/");
console.log(var1, var2, var3);
Enter fullscreen mode Exit fullscreen mode

You will see that it is inevitable to get the first element as an empty string in the returned/logged array in the browser.

What is the clean way to skip the empty string when you de-structure it?

Just skip the defining the first item as shown below and you don’t have to worry about first empty string element.

const [, var2, var3] = url.pathname.split("/");
console.log(var2, var3)
Enter fullscreen mode Exit fullscreen mode

I picked this from Line 26: in create-next-app codebase

Conclusion:

Well, you could still declare a variable when you de-structure it but this affects code readability since you now have a variable that contains empty string and you are not sure if you would use that anywhere later.

Looking to practice and elevate your frontend skills? checkout https://tthroo.com for SaaS project based tutorials.

Get free courses inspired by the best practices used in open source.

About me:

Website: https://ramunarasinga.com/

Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: ramu.narasinga@gmail.com

Learn the best practices used in open source.

Top comments (0)