SpaceToon
SpaceToon

Reputation: 69

Why do the values not change in an Array after processing in for.Each?

I have 4 different values (strings) in JavaScript. I need to make a check, if one of these values is not a number. If so, then replace the value with "---", if not, do nothing. So I put the values in an array and called the forEach-function to check. So I actually want my predefined variables (before putting them in an array) to change if they are not a number, but only the elements of the array change.

So I did some researches and I found the difference between call-by-reference and call-by-value. So I changed my variables to String-Objects, but it does not work. I know, hat calling the elements of my array would also work, but I want to understand why my actual variables does not change ?


    var first = new String("1");
    var second = new String("2");
    var third = new String("3");
    var fourth = new String("test");

    var testArr = [first, second, third, fourth];
    testArr.forEach(function (value, index) {
        if (isNaN(value)) {
            this[index] = "---";
        }
    }, testArr);

    console.log(fourth);
    //*here I expect "---" but it is "test"*
    //I know that testArr[3] is now "---", but why not the variable fourth as well?


Upvotes: 0

Views: 944

Answers (1)

Gena Moroz
Gena Moroz

Reputation: 954

Value stored in variables will never be changed, because in your case variable host value itself, not reference. If you want to apply this kind of magic, you should:

  1. Put initial values in array/object
  2. Use objects instead of typed variables e.g:

    var first = {value:'1'};
    var second = {value:'2'};
    var third = {value:'3'};
    var fourth = {value:'replaceme'};
    
    var testArr = [first, second, third, fourth];
    testArr.forEach(function (obj, index) {
        if (isNaN(obj.value)) {
            obj.value = "---";
        }
    });
    
    console.log(fourth);
    

Upvotes: 2

Related Questions