Harrison Reeves
Harrison Reeves

Reputation: 101

How can I add content to an existing JavaScript variable?

So I want to add content like a string or another variable to a variable that already exists. I know this isn't right, but this is what I have.

var variable = "Variable";

function dispVar1() {
    let p = document.createElement("p");

    p.innerHTML = variable;
}

function dispVar2() {
    let p = document.createElement("p");
    let alteredVar = variable + " that has been altered";
    /* Also, could I do "" + variable to make string go before the variable? */

    p.innerHTML = alteredVar;
}
<input type="button" value="Original" onclick="dispVar1();">
<input type="button" value="Altered" onclick="dispVar2();">

Upvotes: 0

Views: 63

Answers (2)

Tom O.
Tom O.

Reputation: 5941

You can simply use the + assignment operator to concatenate strings. You can see in the example I am creating a variable newValue that concats your original variable plus some additional text:

var variable = "Variable";
var targetEl = document.querySelector('#target');

function dispVar1() {
  target.innerHTML = '';
  let p = document.createElement("p");

  p.innerHTML = variable;
  target.appendChild(p);
}

function dispVar2() {
  target.innerHTML = '';
  let p = document.createElement("p");

  const newValue = variable + ' (here\'s some added text)';
  p.innerHTML = newValue;
  target.appendChild(p);
}
<input type="button" value="Original" onclick="dispVar1();">
<input type="button" value="Altered" onclick="dispVar2();">
<div id="target"></div>

Alternatively, you can take advantage of String.prototype.concat to achieve the same thing - but MDN doesn't recommend it:

It is strongly recommended that the assignment operators (+, +=) are used instead of the concat() method.

According to this performance test, the assignment operators are several times faster.

Upvotes: 1

Will
Will

Reputation: 7017

Your initial code works:

let alteredVar = variable + " that has been altered";

An alternative using template literals with placeholders is more fashionable than concatenation because it removes the necessity of escaping certain characters, is more flexible, and arguably more readable:

let alteredVar = `${variable} that has been altered`;

Upvotes: 0

Related Questions