Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple conditions in an if statement in javascript

Tags:

javascript

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

like image 275
Zulzidan.com Avatar asked Sep 14 '26 04:09

Zulzidan.com


1 Answers

You can use Array.includes to check if the current pathname exists in a given array.

let pathArr = ['/', '/kurikulum/', '/pengembangan-diri/', '/statistik/', '/teknologi/', '/ekonomi/', '/desain/', '/corona/'];
let testPath = '/desain/';

if (pathArr.includes(testPath)) {
   document.write('path found!');
};

Learn more about Array.includes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

like image 143
rishabh0211 Avatar answered Sep 16 '26 19:09

rishabh0211