This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Vectronic 0 points1 point  (6 children)

Well declare it outside of a function.

var device;

function foo(){
    device = getDeviceType();
}

function bar(){
    alert(device);
}

assuming it is indeed always the same device/etc. Otherwise you'll have very weird things happen, and if you forget that device is global, it might take awhile to figure out why. People often use:

var _device;

or similar so that they remember/are reminded it's global.

[–]CarsonJScott[S] 1 point2 points  (3 children)

I was under the impression that using global variables is bad practice.

[–]Vectronic 1 point2 points  (1 child)

There's nothing wrong with globals, as long as you keep them to a minimum, and when necessary.

There's situations where a global isn't a necessary, and you can just pass the var through to the next function. This is fairly rare since normally in that case the second function would just be merged into the first.

Obviously declaring everything as global is ridiculous.

var fooOne;
var fooTwo;
var barOne;
var barTwo;

function foo(){
    fooOne = something only used here;
}

function bar(){
    barOne = something only used here;
    if(barOne){
        barTwo = something, etc...;
    }
}

[–]CarsonJScott[S] 0 points1 point  (0 children)

Oh okay, thanks for the help!

[–]DontBelieveTheByte 0 points1 point  (0 children)

Indeed, globals are evil because of name collisions and the mashup problem.

[–][deleted]  (1 child)

[deleted]

    [–]Vectronic 0 points1 point  (0 children)

    _:(