Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable in a variable in JavaScript?

Tags:

javascript

I want to define a variable that contains a variable. In this example the variable that I want to pass is "filldata".

I have tried passing it using $filldata as well as +filldata+.

if (fill == true) {
     $filldata = "fill: true,";
} else {
     $filldata = "fill: false,";
};

if (amount == true) {
        var set1 = {
            label: "Earnings",
            id: "earnings",
            data: data1,
            points: {
                show: true,
            },
            bars: {
                show: false,
                barWidth: 12,
                aling: 'center'
            },
            lines: {
                show: true,
                $filldata
            },
            yaxis: 1
        };
    } else {
        var set1 = "";
    }
like image 252
Scott Paterson Avatar asked Nov 27 '25 17:11

Scott Paterson


1 Answers

Since you are just trying to create a boolean property named 'fill' with the value of some variable, also called fill (using fussy truthy/falsy values), then you can just skip creating the intermediate $filldata variable altogether and just create the property with the value evaluated inline. It's more succinct and more obvious.

Try:

if (amount == true) {
    var set1 = {
        label: "Earnings",
        id: "earnings",
        data: data1,
        points: {
            show: true,
        },
        bars: {
            show: false,
            barWidth: 12,
            aling: 'center'
        },
        lines: {
            show: true,
            fill: fill==true
        },
        yaxis: 1
    };
} else {
    var set1 = "";
}

EDIT:

Also, note that it is not good practice to declare the variable set1 inside the if block scope if you intend to use it elsewhere. A better alternative would be:

var set1 = (amount == true) ?
    {...your object as defined above...}
    : "";
like image 199
GPicazo Avatar answered Nov 30 '25 06:11

GPicazo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!