0

I am a learner. When I try to assign value to a variable as follows it doesn't work. Want to know the reason.

this doesn't work:

const w =
  if (2 > 1) {
    return 1500;
  } else {
    return 2500;
  }

However this works:

const w = function() {
  if (2 > 1) {
    return 1500;
  } else {
    return 2500;
  }
}()

Is there a better approach?

1
  • First, you can't assign statements to any variable or constant in your case. Secondly, return keyword is used to return a value from a function not to assign a value to some other variable or constant. Commented Nov 19, 2019 at 5:45

2 Answers 2

2

In JavaScript we use if in statements (that's why it's called if statement). However, what you have after const w = is an expression. Because of that, your first snippet didn't work: you cannot use if where JavaScript expects an expression.

That being said, you should use the "analog" of if for expressions, which is the conditional operator.

In your case:

const w = 2 > 1 ? 1500 : 2500;
console.log(w)

Alternatively, if you (for whatever reason) want to keep the if statement:

let w;

if (2 > 1) {
  w = 1500
} else {
  w = 2500
};

console.log(w)

Sign up to request clarification or add additional context in comments.

Comments

-1

You cannot use a statement to assign into a variable. For the alternate solution use conditional/Ternary operator

Syntax

const var_name = condition ? true_value : false_value

Example

const w = 2 > 1 ? 1500 : 2500

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.