-1

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?

1
  • 1
    Your variable 'soundtimer' is scoped to the test function. Commented May 26, 2022 at 18:05

2 Answers 2

1

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');

Sign up to request clarification or add additional context in comments.

1 Comment

its funny but this is how I have it on my actual code but it wont work regardless.
0

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');

2 Comments

this is good, however I have multiple variables ending with timer so I would have to add them all to the object?
Yes, you can absolutely do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.