dimanche 29 avril 2018

Getting the result of an if else statement out of scope in Javascript

In this code I currently have the value of the addToOutput variable trapped inside an if else statement in a way that I am unable to get that value of the variable outside to the statement. I wish to get this value out so that when the user enters a number (for example 930) the function will output 900+30+0. To compile the results I have the variable "output" but if its unable to get the value from addToOutput I will not be able to get the desired result how can I make it so the value of addToOutput will be in scope?

function expandedForm(num) {

  let stringOfNumber = num.toString();
    let numberArray = Array.from(stringOfNumber);
    let zero = "0";
    let output;
    let addToOutput;
    for (let i=0; i<numberArray.length; i){
       let firstNumber = numberArray.shift();
       let arraySize = numberArray.length;

       ifElse(arraySize, firstNumber,zero)

       output = output + addToOutput;
    }
}

function ifElse (arraySize, firstNumber, zero, addToOutput){
    if(arraySize > 0){
      let numberOfZeros = zero.repeat(arraySize);
      addToOutput=firstNumber+ numberOfZeros + " + ";

      return(addToOutput);
    }
    else{
      addToOutput = firstNumber;
      return(addToOutput);
    }
 }
expandedForm(930);

Aucun commentaire:

Enregistrer un commentaire