1

I was playing around with callbacks and ran into this problem, unsure how related it is to callbacks, but I cant explain the result, any help would be greatly appreciated.

Why is the result: 'hi samsamsamsamsamsamsamsamsamsamsamsam',

I would expect: 'hi sam'


function addSam(cb){
    var name = '';
    setTimeout(function(){
        name += 'sam';
        cb();
    }, 1000);
}

function speak(){
    console.log('hi ' + name);
}

When I call addSam(speak), The console returns:

'hi samsamsamsamsamsamsamsamsamsamsamsam'

Why does name += 'sam' happen multiple times?

How should I change the code so this only happens once and I can output simply:

hi sam

3
  • Your code will print only "hi". I am damn sure Commented Mar 12, 2016 at 9:54
  • This is not possible, at least with code you posted. I pretty sure you have something else you are not posing here. Or you are missing var name = ''; in your real code. Commented Mar 12, 2016 at 9:54
  • Sorry, I should have been clear, I run: addSam(speak) at the end of this, this prints out 'hi samsamsamsamsamsamsamsamsamsamsamsam' in the console Commented Mar 12, 2016 at 10:02

2 Answers 2

2

This is because the variable name was defined inside addSam function, so it will only be accessible within that function and not globally.

If you want the function to output hi sam when it is called addSam(speak), define name variable outside of the function so that it can be accessed globally. Like this:

var name = '';
function addSam(cb){
    setTimeout(function(){
        name += 'sam';
        cb();
    }, 1000);
}

function speak(){
    console.log('hi ' + name);
}

addSam(speak); // outputs 'hi sam' after a second
Sign up to request clarification or add additional context in comments.

Comments

2
function addSam(cb){
    var name = '';
    setTimeout(function(){
        name += 'sam';
        cb(name);
    }, 1000);
}

function speak(name){
    console.log('hi ' + name);
}

Comments

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.