Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
ian Avatar asked Jul 22 '09 18:07

ian


2 Answers

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] + '');
}
like image 129
zombat Avatar answered Sep 29 '22 12:09

zombat


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

var number = 10;

You just need

number = 10;
like image 40
kemiller2002 Avatar answered Sep 29 '22 11:09

kemiller2002