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

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;

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

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: "",
}

Type the below into the console:

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

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)

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 and you are not sure if you would use that anywhere later.

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

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github —  https://github.com/ramu-narasinga

My website —  https://ramunarasinga.com

My Youtube channel —  https://www.youtube.com/@ramu-narasinga

Learning platform —  https://thinkthroo.com

Codebase Architecture —  https://app.thinkthroo.com/architecture

Best practices —  https://app.thinkthroo.com/best-practices

Production-grade projects —  https://app.thinkthroo.com/production-grade-projects