React {?} in function

function Greeting() {
const username = “Sebastian”;

return <span>{username ? "Hello " + username : “not logged in”}</span>;
}

ReactDOM.render(<Greeting />, document.querySelector("#root"));

If i understand correct the ? is a shorthand for a if condition but i don’t really understand how it works the line about username ? “Hello”
}

If username is not falcy, that is to say, username !== "", then it is understood that the user is effectively logged in.

Hi,

The above ternary operator works as follows:
If the username is true, then it will return "Hello" + username , else it will return "not logged in" as output. Here the output will be "Hello Sebastian" because the username is true.

Ok so {?} is for if true and {:} is for else.

Hi,
In terms of if else condition, the above code is:

if(username) {
   return "Hello" + username;
} else {
   return "not logged in";
}

Yes. Look this:

The second certification of FCC explains this operator also.

1 Like