Doug Null
Doug Null

Reputation: 8327

A javascript variable defined outside a function is 'undefined' within the function

Why is MM_SYSTEM_RESTART_SECONDS undefined in the following snippet?

If var MM_SYSTEM_RESTART_SECONDS = 40; is put inside the function, then MM_SYSTEM_RESTART_SECONDS is 40, but if outside the function, then MM_SYSTEM_RESTART_SECONDS is always undefined.

var MM_SYSTEM_RESTART_SECONDS = 40;


function wait_until_MM_restarts()
{
    restart_timeout_start_seconds = get_cookie( "restart_timeout_start_seconds" )
    elapsed_restart_seconds =  elapsed_seconds( restart_timeout_start_seconds )
    append_debug_message( elapsed_restart_seconds + "/" +   MM_SYSTEM_RESTART_SECONDS )
    if( elapsed_restart_seconds > MM_SYSTEM_RESTART_SECONDS )

Upvotes: 0

Views: 982

Answers (1)

user1952338
user1952338

Reputation: 131

This just bit me. If you call the function before/above the variable declaration the variable might be undefined.

For example

f("before");

var value = 99;
function f(msg)
{    
  alert("msg=" + msg + " value=" + value);
}

f("after");

results in:

msg=before value=undefined
msg=after value=99

http://jsfiddle.net/qUhQV/4/

Upvotes: 2

Related Questions