Question

I basically want to get individual r,g,b value of a color and store it in an object so that I can access individual values. The split function splits the rgb value of variable colorVar and want to call the varHolder in other function which I have provided it below. But when I want to display the value in console.log, it flags up with undefined error.

I tried making the lineObj global variable but it didnt work.

function comparision(){
    split(colorL,lineObj);
    console.log('---------get-------');
//This log doesn't work
    console.log(lineObj.r);
}

function split(colorVar,varHolder){
    colorRgb = colorVar.slice(colorVar.indexOf('(') + 1, colorVar.indexOf(')'));
    var colorArr = colorRgb.split(','),
    i = colorArr.length;

    while (i--)
    {
    colorArr[i] = parseInt(colorArr[i], 10);
    }

    varHolder = {
    r: colorArr[0],
    g: colorArr[1],
    b: colorArr[2],
    a: colorArr[3]
    }
//The below log works.
    console.log('-----------Split-------')
    console.log(varHolder.r);
}
Was it helpful?

Solution

Your changed values in split() are not propagating back to your calling function comaprison() because the parameter varHolder is pass by value, not pass by reference. This means that any changes to the variable within the function are local to that function only. To get around this, you have to return the new variable to the outer function.

    varHolder = {
    r: colorArr[0],
    g: colorArr[1],
    b: colorArr[2],
    a: colorArr[3]
    }
    //The below log works.
    console.log('-----------Split-------')
    console.log(varHolder.r);

    return varHolder;
}

function comparision(){
    lineObj = split(colorL,lineObj);
    console.log('---------get-------');
    //This log doesn't work
    console.log(lineObj.r);
}

If this is your entire code, this can be simplified further by removing the varHolder parameter from the function entirely since the function never uses it, except for assigning it to a new variable. For example:

lineObj = split(lineObj);

function split(colorVar){
...
}

See Also: Is JavaScript a pass-by-reference or pass-by-value language?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top