-2
categoryId = categoryId === '' && location.pathname.match(regExp) ?location.pathname.match(regExp)[1] : categoryId

I know this is a ternary operator but what does categoryId === '' && location.pathname.match(regExp) do here? particularly no clue on '' && location.pathname.match(regExp) is it a boolean?

  • 2
    Does this answer your question? [Assignment with double ampersand "&&"](https://stackoverflow.com/questions/12878612/assignment-with-double-ampersand) – jonrsharpe Jul 27 '20 at 10:47
  • Then you should have a look at the documentation of [`String.prototype.match()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) and [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) – Andreas Jul 27 '20 at 10:48
  • Explicit grouping parentheses and more conventional spacing may help: `categoryId = ((categoryId === '') && (location.pathname.match(regExp))) ? location.pathname.match(regExp)[1] : categoryId` – jonrsharpe Jul 27 '20 at 10:48

1 Answers1

2

So I will take you through the piece of code you have provided as detailed as my free time now can permit me and from the top of my head.

categoryId is a variable that is accepting the result of what is on the right. thus the = sign.

categoryId === '' This part here is simply making a comparison between the results in categoryId to an empty string '' which will return a boolean. So its saying "is the result in categoryId an empty string? true or false.

&& this is saying that we are going to check under condition so check the above one and another...

location.pathname.match(regExp) this is the 2nd check... checking if a url path matches a certain regex definition/condition in regExp (you have not provided that so I can't say much there)

Now note that due to the use of &&, both conditions must return true before the true statement is run else it will be false.

? this is saying; if true, run the next condition/statement

location.pathname.match(regExp)[1] this is the condition/statement it will run if result is true.

: this means if it is false, run the next condition/statement

categoryId this is the condition to run when the result is false.

This type of conditional statement is called a "Conditional/Ternary Operator" find a bit more details here: https://www.w3schools.com/js/js_comparisons.asp

I hope this helps. If its not clear let me know so I clarify. Best way to learn!

mw509
  • 1,957
  • 1
  • 19
  • 25
  • _"So I will take you through the piece of code you have provided as detailed as my free time now can permit me and from the top of my head."_ - How is this relevant for the answer? – Andreas Jul 27 '20 at 11:18
  • Just to let him know am running through the whole code. If you think it is irrelevant, please feel free to edit. Team work makes the dream work! – mw509 Jul 27 '20 at 11:19