0

I have function that loops and inside that function I call another function (which should change "newArray[x]" value, but it doesn't do anything).

function UTF8() {
        newArray = ["0011", "0001"]
        newArray.forEach(x => {
            binaryToHexadecimal(newArray[x]);
            console.log(newArray[x])
        });
        console.log(newArray[0])
}

function binaryToHexadecimal(string) {
    if (string === "0000") {
        return string = "0";
    }
    else if (string ==="0001") {
        return string = "1";
    }
    else if (string ==="0010") {
        return string = "2";
    }
    else if (string ==="0011") {
        return string = "3";
    }
    else if (string ==="0100") {
        return string = "4";
    }

}
UTF8();
4
  • arguments are called by value. Assigning a new value to the parameter never changes the variable or property that you pass as argument. Commented Oct 26, 2020 at 18:40
  • 2
    1. newArray[x] is undefined because x will be either 0011 or 0001 and both newArray["0011"] and newArray["0001"] don't exist. 2. that's not how you replace a value from an array Commented Oct 26, 2020 at 18:40
  • 2
    1) you're using forEach, so x isn't the index, it's the array element itself 2) you would have to use newArray[x] = binaryToHexadecimal(newArray[x]); 3) this is precisely what .map() is for Commented Oct 26, 2020 at 18:40
  • 2
    ["0011", "0001"].map(b => parseInt(b, 2).toString(16).toUpperCase()); Commented Oct 26, 2020 at 18:41

2 Answers 2

2

The function is setting a local variable, it has no control over whatever variable was used to pass that value.

Just return the value you want from the function. For example:

return "0";

Then when calling the function, use that value to set your array element as needed:

newArray[x] = binaryToHexadecimal(newArray[x]);
Sign up to request clarification or add additional context in comments.

Comments

2

Use map instead of forEach.

And here return string = "0"; you can directly return the value.

function UTF8() {
        newArray = ["0011", "0001"]
        return newArray.map(x => {
            return binaryToHexadecimal(x);
        });
}

function binaryToHexadecimal(string) {
    if (string === "0000") {
        return "0";
    }
    else if (string ==="0001") {
        return "1";
    }
    else if (string ==="0010") {
        return "2";
    }
    else if (string === "0011") {
        return "3";
    }
    else if (string ==="0100") {
        return string = "4";
    }

}
const result = UTF8();
  console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.