user15253655
user15253655

Reputation:

Reactjs - SyntaxError: Octal literals are not allowed in strict mode

I have the following code for my app component in reactjs:

function App() {
  var [expression, setExpression] = useState("");
  var [result, setResult] = useState("");

  return (
    <div className="App">

    <div id="equals">
{result}
    </div>
<div id="display">
{expression}

</div>
<button id='zero' onClick={() => setExpression(expression + "0")}>0 </button>
<button id='one' onClick={() => setExpression(expression + "1")}>1 </button>
<button id='two' onClick={() => setExpression(expression + "2")}>2 </button>
<button id='three' onClick={() => setExpression(expression + "3")}>3 </button>
<button id='four' onClick={() => setExpression(expression + "4")}>4 </button>
<button id='five' onClick={() => setExpression(expression + "5")}>5 </button>
<button id='six' onClick={() => setExpression(expression + "6")}>6 </button>
<button id='seven' onClick={() => setExpression(expression + "7")}>7 </button>
<button id='eight' onClick={() => setExpression(expression + "8")}>8 </button>
<button id='nine' onClick={() => setExpression(expression + "9")}>9 </button>
<button id="add" onClick={() => setExpression(expression + "+")}>+</button>
<button id="subtract" onClick={() => setExpression(expression + "-")}>-</button>
<button id="multiply" onClick={() => setExpression(expression + "*")}>*</button>
<button id="divide" onClick={() => setExpression(expression + "/")}>/</button>
  <button id="equals" onClick={() => setResult(eval(expression))}>=</button>
    </div>

  );
}

But when I open the browser I get the error:

SyntaxError: Octal literals are not allowed in strict mode.

I don't know how to fix it though. Thanks in advance.

Upvotes: 0

Views: 2391

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

This is a bit subtle. The issue is that you're concatenating strings. At some point, it would appear you've clicked the 0 button followed by any of the other digit buttons. That means you end up with expression being "01" or similar. That's a legacy octal literal, which (as you've discovered) are disallowed in strict mode.

You'll need to update your code that adds to the expression so that when it's about to add the digit 1 through 9, it looks to see if there's a 0 (and only a 0) after the last operator and, if so, removes that 0 before adding the digit.

For instance, if expression is "1+0", clicking 2 should remove that "0" before adding the "2" so that it ends up being "1+2", not "1+02".

Upvotes: 1

Related Questions