0

I am trying to understand the concept of writing expression in JSX but unable to understand that how is not javascript in curly braces an expression?

const Welcome()=>{
  const isLoggedIn = true;
  return(
    <div>
      {
        if(isLoggedIn){
          <p>Welcome!</p>
        }else{
          <p>Please Login</p>
        }
      }
    </div>  
  );
}

Please guide me either when we assign a value isLoggedIn is true then validation happens, if value is true then it prints Welcome otherwise please log in.

Please tell me how is this a statement and not an expression.

3
  • 1
    if statements in JavaScript are statements, not expressions (unlike, say Kotlin). Use a ternary operator or && || instead. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 14, 2021 at 5:31
  • @Ziwon Please explain how can we say that is a statement not an expression.In the block if(isLoggedIn) tell us either is it a statement or expression? Commented Dec 14, 2021 at 5:41
  • Expression returns a value. Statements don't return a value. For example you can do let a = 1 + 2 because 1 + 2 is an expression. However you cannot do let a = if (1) {2} because if (1) {2} is not an expression. Commented Dec 14, 2021 at 6:21

2 Answers 2

2

If you want to use if then you have to use ternary operator because if in java scripts are statements, not expressions.

const Welcome = () => {
  const isLoggedIn = true;
  return (<div>{isLoggedIn ? <p>Welcome!</p> : <p>Please Login</p>}</div>);
}
Sign up to request clarification or add additional context in comments.

Comments

1

if statements in JavaScript are, by definition, statements, and not expressions.

An expression can be considered as code that you can assign to a variable:

const myVar = 2 + 2;
const otherVar = someFuncCall();

Here, 2 + 2 and someFuncCall() are expressions because they can be assigned to a variable.

An if statement can't be assigned to a variable:

const invalidCode = if (someCondition) { "ABC"; } // This code won't run

You can use a ternary operator instead, which can be used to create expressions just like any other operators (e.g. + operator):

const Welcome = () => {
  const isLoggedIn = true;
  return(
    <div>
      {isLoggedIn ? (<p>Welcome!</p>) : (<p>Please Login</p>)}
    </div>  
  );
}

This code works, because it's possible to assign this result to a variable:

const myJsx = isLoggedIn ? (<p>Welcome!</p>) : (<p>Please Login</p>)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.