Sam Houston
Sam Houston

Reputation: 3651

Callback issues in javascript

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

Upvotes: 1

Views: 55

Answers (2)

chris97ong
chris97ong

Reputation: 7060

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

Upvotes: 2

Tim
Tim

Reputation: 21

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

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

Upvotes: 2

Related Questions