Search code examples
javascriptvariablesglobal-variables

Using a global variable in JavaScript


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?


Solution

  • 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] + '');
    }