multiple conditions in an if statement in javascript

Viewed 1129

I know there has been a question like this, but mine is a little different, and it already works, but I don't know how to simplify it.

if (location.pathname === `/` || location.pathname ===`/kurikulum/` || location.pathname === `/pengembangan-diri/` || location.pathname === `/statistik/` || location.pathname === `/teknologi/` || location.pathname === `/ekonomi/` || location.pathname === `/desain/` || location.pathname === `/corona/`)

as you can see it is not beautiful, I wonder can we make it without repeating location.pathname?

this is on gatsby, but it is a javascript question

5 Answers

Use includes(), it will return true or false if the value is in the array.

const pathnames = [
  '/',
  '/kurikulum/',
  '/pengembangan-diri/',
  '/statistik/',
  '/teknologi/',
  '/ekonomi/',
  '/desain/',
  '/corona/'
]

if (pathnames.includes(location.pathname)) {
  // do something
}

you can put all of your paths into a path array then run an indexOf() function to see if something fits

const paths = ['/', '/path', '/path1']
const thePath = '/',

if (paths.indexOf(thepath) >= 0) {
  console.log('the path exists')
} else {
console.log('the path doesnt exist')
}

Another way is that you can use array.filter or array.some.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const searchFunc = (searchItem) => words.filter(word => word === searchItem).length > 0;
if(searchFunc('limit')){
  console.log("Item is found");
}

// expected output: "Item is found"

You can simplify by define an JavaScript array of objects like below:

{
  path: '/some-path-to-compare`,
}

Then instead of compare by lot of lines, use loop then compare with the path field.

Related