views:

764

answers:

4

How do I do this?

My code is something like this:

var number = null;

function playSong(artist,title,song,id)
{
    alert('old number was: '+[number]+'');


    var number = '10';

    alert(''+[number]+'');
}

The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?

+5  A: 

Remove the var in front of number in your function. You are creating a local variable by

var number = 10;

what you need is just

number = 10;
Kevin
+7  A: 

By using var when setting number = '10', you are declaring number as a local variable each time. Try this:

var number = null;

function playSong(artist,title,song,id)
{
    alert('old number was: '+[number]+'');


    number = '10';

    alert(''+[number]+'');
}
zombat
+2  A: 

The problem is that you're declaring a new variable named number inside of the function. This new variable hides the global number variable, so the line number = 10 assigns only to this new local variable.

You need to remove the var keyword from var number = 10.

SLaks
+1  A: 

Like in C, you need to define your variable outside of the function/method to make it global.

var number = 0;

function playSong(artist,title,song,id)
{
    alert('old number was: '+[number]+'');
    number = '10';
    alert(''+[number]+'');
}
Babak Naffas
It's reassuring to see the same answer posted within the same minute.
Babak Naffas
Actually, any definition without 'var' will be a global variable, regardless of where it's defined. Javascript can be scary.
Brian Ramsay
You learn something new every day.
Babak Naffas