Front End Development Libraries Projects - Build a JavaScript Calculator

Tell us what’s happening:

All tests are passing except #13. Please help l am stuck for over a week.

Your code so far

var displayText=document.getElementById(`display`);//Getting the display element
displayText.textContent=`0`;//Setting the display area's text to 0

const clearDisplayDiv=()=>{//Function to clear the display div
   displayText.textContent=``;//Clearing the display div
   displayText.textContent=`0`; //Setting the initial value to 0
  }
var is_operator=false;

const getNumbers=(event)=>{//function for inputting digits
   if (displayText.textContent===`0`) {//checking if the display div is empty
      displayText.textContent=event.textContent;//assigning the clicked key's text content
    } else if (is_operator) {
      is_operator = false;
      displayText.textContent = event.textContent;
		} else if (displayText.textContent.includes(".")) {//To handle decimal inputs
      displayText.textContent = displayText.textContent + "" + event.textContent.replace(".", "");//Avoiding 2 consequitive dots
    } else {
      displayText.textContent = displayText.textContent + "" + event.textContent;
    }  
}

const getOperators=(event)=>{// function to input operators
  let lastElement = expression[expression.length - 1];
          if (["/", "*", "+", "-"].includes(lastElement) && is_operator) {//checking if the last element in the array is an operator
          expression.push(event.textContent);//adding the operator clicked to the end of the array
         } else {
          expression.push(displayText.textContent);
          expression.push(event.textContent);
        }
        is_operator = true;
 }

var expression=[];//declaring and initialising the array to hold the aquation to be calculated

const calculateResult=()=>{// function to calculate the result 
 
  try{//Try block to perform the calculation/evaluation
   
        expression.push(displayText.textContent);
    
    
        displayText.textContent = eval(expression.join(""));//evaluating/calculating the expression 
        expression = [];//setting the expression to empty in preparationg for the next calculation
       
  }
  
  catch(event){//Catch bock to catch and display error message
      
    displayText.textContent="ERR TRY AGAIN";//Error message to be outputted
    
  }
  
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0

Challenge Information:

Front End Development Libraries Projects - Build a JavaScript Calculator

Welcome to the forum @clydechitumba7

For this project you should use a frontend framework.

If you are using the freeCodeCamp editor, click the Ask for Help button located on the challenge (it looks like a question mark). This button only appears if you have tried to submit an answer at least three times.

The Ask for Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

The forum needs to inspect all of your code for debugging.

Happy coding

Please provide the HTML as well.

You are more likely to get help if you provide a live demo on something like Codepen, Stackblitz, Codesandbox, etc.


User Story #13: If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (- ) sign). For example, if 5 + * 7 = is entered, the result should be 35 (i.e. 5 * 7 ); if 5 * - 5 = is entered, the result should be -25 (i.e. 5 * (-5) ).

Maybe I’m reading your code wrong, but are you not always adding the operator to the expression array? And if so, are you not seeing an error?

const array = ["5", "+", "*", "7"];
eval(array.join(""));
Uncaught SyntaxError: Unexpected token '*'

When l do 5+7 the output is 35 i am not getting the error message - Uncaught SyntaxError: Unexpected token ''. The html is like below

<h1>MY JAVASCRIPT CALCULATOR</h1>
<div class="container">
<div class="display" id="display"></div>
<div class="calculator">
   <button id="add"  onclick="getOperators(this)">+</button>
  <button id="subtract"  onclick="getOperators(this)">-</button>
  <button id="multiply"  onclick="getOperators(this)">*</button>
  <button id="divide"  onclick="getOperators(this)">/</button>
   
  <button id="one"  value="1" onclick="getNumbers(this)">1</button>
  <button id="two"   onclick="getNumbers(this)">2</button>
  <button id="three"  onclick="getNumbers(this)">3</button>
  <button id="four"  onclick="getNumbers(this)">4</button>
  <button id="five"  onclick="getNumbers(this)">5</button>
  <button id="six"  onclick="getNumbers(this)">6</button>
  <button id="seven"  onclick="getNumbers(this)">7</button>
  <button id="eight"  onclick="getNumbers(this)">8</button>
  <button id="nine" onclick="getNumbers(this)">9</button>
  <button id="zero"  onclick="getNumbers(this)">0</button>
  <button id="decimal"  class="" onclick="getNumbers(this)">.</button>
  <button id="clear"  onclick="clearDisplayDiv()">A/C</button>
  
 </div> 
  <button id="equals"  class="equals" onclick="calculateResult()">=</button>
</div>

The sequence “5 * - + 5” = should produce an output of “10” : expected ‘-25’ to equal ‘10’

['5', '*', '-', '+', '5'].join("") // '5*-+5'
eval('5*-+5'); // -25

I used a frontend framework(React) but am still failling to pass test #13

my code for the React is like so


class MyJavaScriptCalculator extends React.Component {
  
  constructor(props){
  
    super(props)
    this.clearDisplayDiv = this.clearDisplayDiv.bind(this);
    this.getNumbers = this.getNumbers.bind(this);
    this.getOperators = this.getOperators.bind(this);
    this.calculateResult = this.calculateResult.bind(this);
    this.dot = this.dot.bind(this);
    
     this.state={
      display:"0",
      current:"",
      expression:"",
      evaluat:false,
      
    }
    
 }
  
  dot(e){
   let lasti =this.state.expression.slice(-1);
   let lastCharTestReg= /[*-+/\/]/;
   
    if(!lastCharTestReg.test(lasti) && !this.state.current.includes(".") && this.state.evaluat==false){
      this.setState({
        expression:this.state.expression + ".",
        current:this.state.current + ".",
        display:this.state.display + "."
      })
    }
  }
    
  getOperators = (e) => {   
   let last =this.state.expression.[this.state.expression.length-1];
   let lastCharTestReg= /[+\-*\/]/;
    
    if(!lastCharTestReg.test(last)){
      this.setState({
        current:"",
        expression:this.state.expression + e.target.textContent
    })
    }else{
      if(last !=="-" && e.target.textContent=="-"){
        this.setState({
          expression:this.state.expression + e.target.textContent
        })
    }else if(e.target.textContent!=="-" && last=="-"){
      this.setState({
      current:"",
      expresion: this.state.expression.slice(0,-2) + e.target.textContent 
        })
    }else{
      this.setState({
        expression:this.state.expression.slice(0,-1) + e.target.textContent
      })
    }
  }
  }
  
  calculateResult(e){
    
  if (this.state.expression !== "") {    
  let answer=math.evaluate(this.state.expression);
      
    this.setState({
      display:answer,
      expression:answer,
      evaluat:true
    }) 
  }
  }  
  
 getNumbers = (e) => {
   
  if(this .state.current[0]==="0" && e.target.textContent==="0"){
     this.setState({
      current : this.state.current
    })
  } else{
    if(this.state.evaluat && typeof this.state.expression=="number"){
      this.setState({
        expression:e.target.textContent,
        current:e.target.textContent,
        evaluat:false,
        display:e.target.textContent
      })
    } else if(this.state.evaluat && typeof this.state.expression=="string"){
      this.setState({
        expression:this.state.expression + e.target.textContent,
        current:e.target.textContent,
        evaluat:false,
        display:e.target.textContent
      })
    } else {
      this.setState({
        expression:this.state.expression + e.target.textContent,
        current:this.state.current + e.target.textContent,
        evaluat:false,
        display:this.state.current + e.target.textContent
      })
    } 
  }
}
  
  clearDisplayDiv(){
    this.setState({ 
      current: "",
      expression: "",
      currentOperator: "",
      evaluat: "", 
      display: "0" 
    })
  }
    render() {
    return (
       <div class="container">
        
<div class="display" id="display">
  {this.state.display }
</div>
<div class="calculator">
  <button id="add"  onClick={this.getOperators} >+</button>
  <button id="subtract"  onClick={this.getOperators}>-</button>
  <button id="multiply"  onClick={this.getOperators}>*</button>
  <button id="divide"  onClick={this.getOperators}>/</button>
   
  <button id="one"   onClick={this.getNumbers} >1</button>
  <button id="two"   onClick={this.getNumbers}>2</button>
  <button id="three"  onClick={this.getNumbers}>3</button>
  <button id="four"  onClick={this.getNumbers}>4</button>
  <button id="five"  onClick={this.getNumbers}>5</button>
  <button id="six"  onClick={this.getNumbers}>6</button>
  <button id="seven"  onClick={this.getNumbers}>7</button>
  <button id="eight"  onClick={this.getNumbers}>8</button>
  <button id="nine" onClick={this.getNumbers}>9</button>
  <button id="zero"  onClick={this.getNumbers}>0</button>
  <button id="decimal"  onClick={this.dot}>.</button>
  <button id="clear"  onClick={this.clearDisplayDiv}>A/C</button>
  </div> 
  <button id="equals"  class="equals" onClick={this.calculateResult} value="=">=</button>
</div>      
        
      )
  }
}

ReactDOM.render(< MyJavaScriptCalculator />, document.getElementById("calculatorChallengeNode"));

the html is like so

<h1>MY JAVASCRIPT CALCULATOR</h1>
<div id="calculatorChallengeNode"></div>