-3

var firstDefrost = "4.0";

function zero(zeroArray) {
  if (zeroArray[1] == undefined) {
    zeroArray[1] = 0;
    zeroArray[2] = "";
    console.log("zero array 1 called")
  } else if (zeroArray[1] == ".") {
    zeroArray[1] = 0;
    zeroArray[2] = "";
    /*I want it to return 40 not 4.0 which is what is happening */
    console.log("zero array 2 called" + zeroArray)
  }

  return zeroArray;

}

firstDefrost = zero(firstDefrost);

In the second else if block of code I want the value to be returned of 40 but instead it returns 4.0 which I don't want.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ben reaby
  • 19
  • 4
  • 2
    You argument is called `zeroArray`, but you actually pass a string, and in JavaScript strings are immutable -- you can't modify it, instead you need to create new one. In your particular case contents of the second `else` block could look like this: `zeroArray = zeroArray[0] + "0";` or `zeroArray = zeroArray[0] + zeroArray[2];`. It might look like you're modifying `zeroArray` string, but actually you modify contents of variable `zeroArray` -- by assigning newly constructed string value. – alx Nov 13 '21 at 01:35
  • 1
    Why not just `console.log("40")`? Why do you feel a need to modify the original? – Spectric Nov 13 '21 at 01:35
  • The question title should describe your problem well enough so that readers get the gist of what it's about. See: [How do I write a good title?](https://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title) – John Kugelman Nov 13 '21 at 02:00

2 Answers2

1

From the cases in the OP, it looks like the objective is to take a number represented by a string param, and return a string representing that number times 10.

function zero(string) {
  return `${+string*10}`
}

console.log(zero("4.0"))
console.log(zero("3"))
danh
  • 62,181
  • 10
  • 95
  • 136
0

This happens because when you use zeroArray[1] you can get the character in that position of the string but you cannot assign a new value like that, you need an array to do this operation. Let me edit your code with some little changes:

var firstDefrost = "4.0"; 

    function zero ( zeroArray ){
        zeroArray = zeroArray.split("");
        if(zeroArray[1] == undefined){
            zeroArray[1] = "0";
            zeroArray[2] = "";
            console.log("zero array 1 called")
            }
        else if(zeroArray[1] == "."){
            zeroArray[1] = "0";
            zeroArray[2] = "";
            /*I want it to return 40 not 4.0 which is what is happening */
            console.log("zero array 2 called" + zeroArray)
            }
        
        return zeroArray.join("");
        
    }
    
firstDefrost = zero(firstDefrost);
Rob-dev
  • 61
  • 4