Trying to construct a variable name from a string and another variable name with window[] but not working

Asked 1 month ago
Viewed 14 times

This is my code:

function test(tlm) { 
 var soundtimer = 'success';
 var type = tlm.replace('send','');
 var timer = window[type+'timer'];

 console.log(timer);
}

test('sendsound');

I should get success but I get undefined instead. Why is that?

asked 1 month ago

Correct Answer

Your 'soundtimer' variable is locally scoped to the test function. Moving it outside allows it to be globally declared on window:

var soundtimer = 'success';
function test(tlm) {
  var type = tlm.replace('send','');
  var timer = window[type+'timer'];

  console.log(timer);
}

test('sendsound');
answered 1 month ago

Other Answer

You can use an object within your function.

function test(tlm) { 
  var local = {
    soundtimer:'success'
  };
 var type = tlm.replace('send','');
 var timer = local[type+'timer'];

 console.log(timer);
}

test('sendsound');
answered 1 month ago