user9463040
user9463040

Reputation:

can we change the value of a variable stored within another variable in javascript

There is a variable let say var content which holds some HTML content and this HTML also contains a JavaScript variable let say ${id}. Now I want to update the value of ${id} variable. I have tried with the following code but it's not working.

var id = '';
var content = `<div class="row well margin_btm_ten">
    <div class="col-md-1">
        <b>ID is ${id}</b>  
    </div>`;
row_id = 2;
setTimeout(function(){
    console.log(content)
});

Upvotes: 0

Views: 179

Answers (3)

Cristian S.
Cristian S.

Reputation: 973

It's not possible since the reference to "content" is being created with the current value of the variable id. JavaScript variables are basically containers for storing data values. You would need to "rerun" the content variable, to get the new id. But I think you should rather use functions than overwriting variables.

const printName = (name => console.log(`Hello ${name}`));

let name = "Mark";

printName(name);

name = "Peter";

printName(name);

Upvotes: 0

connexo
connexo

Reputation: 56754

You can make id a function with custom setter for id property which will make content update every time you set a new id.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

function id() {
  var id;
  Object.defineProperty(this, 'id', {
    get() {
      return id;
    },
    set(value) {
      id = value;
      content = `<div class="row well margin_btm_ten">
          <div class="col-md-1">
              <b>ID is ${id}</b>  
          </div>`;
    },
    enumerable: true,
    configurable: true
  });
};

var obj = new id();

var content = `<div class="row well margin_btm_ten">
    <div class="col-md-1">
        <b>ID is ${obj.id}</b>  
    </div>`;

console.log(content) // id: undefined

app.innerHTML += content

obj.id = 2;

console.log(content) // id: 2

app.innerHTML += content

obj.id = 'Hello World!';

console.log(content) // id: 'Hello World'

app.innerHTML += content
<div id="app"></div>

Upvotes: 0

Levi Rocha
Levi Rocha

Reputation: 88

You can have content be a function that returns the html content, so that it will calculate it every time it's called. This way if the id variable changes, the value returned by content() will also change:

var id = 'one';
var content = () => `<div class="row well margin_btm_ten">
    <div class="col-md-1">
        <b>ID is ${id}</b>  
    </div>`;
console.log(content());
id = 'two';
console.log(content());

Upvotes: 2

Related Questions