SUMguy
SUMguy

Reputation: 1673

Simple ternary operator throwing unexpected error message

I have a React app which contains links to subroutes, and I use the subdomain/path to populate the props on each detail page.

In other words, when a user navigates to a page I use pathname to populate things like the page title and contents. One of the pages/routes contains a name/title which is normally written in upper camel casing ("SoCal"), so I use following code which contains a ternary operator that determines if location = "socal" and if it does, I want the location variable to be set to "SoCal" so that when I use <h1>{location}</h1> to populate the page title, it will be displayed correctly.

The problem is that when I use the ternary operator it always sets the location to SoCal, even if the original value of location was Texas (for example). It seems like I'm doing something wrong, but can't see what it is.

var location = titleCase(window.location.pathname.replace("/", ""));

function detailPage() {
  const [filter] = useState(location.toLowerCase());
  location = "socal" ? location = "SoCal" : location;
  console.log(location)

Note that in the above example, I'm using = instead of === as you would expect because when I use === the code breaks and returns the error message:

"Expected an assignment or function call and instead saw an expression. (no-unused-expressions)"

Any ideas about what I'm doing wrong?

Upvotes: 1

Views: 934

Answers (2)

Dan Mullin
Dan Mullin

Reputation: 4435

The problem lies here:

location = "socal" ? location = "SoCal" : location;

The first part of a ternary statement is a condition check. You are checking whether the value of "socal" is true of false. You're also doing an assignment in the operator which isn't allowed.

Upvotes: 0

shinjw
shinjw

Reputation: 3421

The order of your ternary operator is incorrect. You will want to use the following syntax to leverage ternary operators in your code.

It should follow as such:

variable = (conditional statement) ? (value if true) : (value if false)

In your case.

location = location === "socal" ? "SoCal" : location 

Upvotes: 1

Related Questions