Matthew Snell
Matthew Snell

Reputation: 957

Invalid left-hand side argument error when concatenating a string with variable in a function

I'm attempting to concatenate the value in a function with c and add 5 each time. However, I keep getting the error Uncaught ReferenceError: Invalid left-hand side in assignment. Does anyone know of a workaround? I am assuming I cannot use the + operator as a concatenate and then use it in the +=? I'm confused why this isn't working.

var c1 = 0;
var c2 = 0;

function(d) {
    d.number; //possible value of 1 or 2
    c + d.number += 5; //isn't this c1 += 5, or c2 += 5?
    "c" + d.number += 5; //also tried this - same error
    console.log(c1);
    console.log(c2);
;}

Upvotes: 1

Views: 748

Answers (1)

jakeehoffmann
jakeehoffmann

Reputation: 1419

In case what Pointy said in the comments is not clear, you can "construct" the variable name (as you are trying to do) when it's an object property using the [ ] operator.

Here is an example:

var cObj = {};
cObj.c1 = 0;
cObj.c2 = 0;

function(d) {
    cObj['c' + d.number] += 5;
    console.log(cObj.c1);
    console.log(cObj.c2);
;}

Upvotes: 2

Related Questions