0

if condition inside first bracket causes error:

function fd(t) {
  let output = '';
  if (t >= 41) {
    let mns = 45
    (mns === 1) ? (output = "true") : (output = "false");
  }
  return output;
}

console.log(fd(65));

Error message: "ReferenceError: can't access lexical declaration `mns' before initialization"

if condition without first bracket works just fine:

function fd(t) {
  let output = '';
  if (t >= 41) {
    let mns = 45
    mns === 1 ? (output = "true") : (output = "false");
  }
  return output;
}

console.log(fd(65));

Can anyone please explain me this behavior?

noobie
  • 751
  • 4
  • 13
  • 33

2 Answers2

2

You are missing a semicolon after let mns = 45 to conclude the statement. Without the semicolon to conclude the statement, it would be like trying to pass (mns === 1) as an argument to the let statement. It would be like the two lines were combined into one: let mns = 45(mns === 1) ? (output = "true") : (output = "false");

The second function works because there is no bracket around msn === 1, so it won't try to pass it as an argument to the let statement.

As a general rule, always remember to add a semicolon after each JavaScript statement.

function fd(t) {
  let output = '';
  if (t >= 41) {
    let mns = 45;
    (mns === 1) ? (output = "true") : (output = "false");
  }
  return output;
}

console.log(fd(65));

As Xufox suggested in the comments, you could just move the ternary operator to the return statement to avoid ambiguity.

function fd(t) {
     let mns;
      if (t >= 41) {
        mns = 45;
      }
      return (mns === 1) ? ("true") : ("false");
}

console.log(fd(65));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

That happens because let declaration is not concluded yet. To end the declaration use ; or declare as var instead of let.

function fd(t) {
  let output = '';
  if (t >= 41) {
    let mns = 45;  // note the semicolan or declare it as var
    (mns === 1) ? (output = "true") : (output = "false");
  }
  return output;
}

console.log(fd(65));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
BlackBeard
  • 10,246
  • 7
  • 52
  • 62