Invite-Only Early Access — Think Throo GitHub App is currently invite-only. Request access here.
2024February

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. Email: ramu.narasinga@gmail.com

Tired of AI-generated code that works but nobody understands?

I spent 3+ years studying OSS codebases and wrote 350+ articles on what makes them production-grade. I built an open source tool that reviews your PR against your existing codebase patterns.

Your codebase. Your patterns. Enforced.

Get started for free —thinkthroo.com