Javascript Calculator (overwriting issues) [CLOSED]

Javascript Calculator (overwriting issues) [CLOSED]


Hello again,

I’m encountering a second issue with the Js calculator project. :neutral_face:

What can I do not to overwrite the result of the expression by the sqrt method. I want the expression to be evaluated in the end by the result function…

function result() {
  const result = getElementById("result");
  let x = calcs.textContent;
  x = eval(x);
  result.textContent = x;
<div id="screenZone">
      <div id="calculations"></div>
      <div id="result"></div>
<input type="button" class="smallKey" value="&radic;" disabled onclick="addToScreenZone('√')">
function addToScreenZone(x) {
  let exp = calcs.textContent;
  calcs.textContent += x;
  let sqrtIndex = exp.indexOf('√'); 
  if(sqrtIndex != -1) {
    let num = parseInt(calcs.textContent.slice(sqrtIndex+1)); //not including the sqrt symbol to the string and then parsing it into an integer
    getElementById("result").textContent = Math.sqrt(num); //overwriting the div with the id result

Any help would be greatly appreciated.


I’m not entirely sure what you are asking here. If you don’t want to overwrite the field, just don’t overwrite it. Save it into an intermediary variable.

However I would like to warn you against use of eval. You might have heard the “eval is evil” saying. Unfortunately there is truth to that. There are a few corner cases where use of eval is acceptable, but I feel like its use here a) goes against the spirit of the exercise, and b) is violating major security rule. You are allowing arbitrary JavaScript from a text field to be executed. Please read up on acceptable use for eval.