shane18 Posted February 14, 2010 Share Posted February 14, 2010 Is there really any difference between: var Age = 18; or Age = 18; Whats the point of adding the var part? any real reason at all? Quote Link to comment Share on other sites More sharing options...
yozyk Posted February 14, 2010 Share Posted February 14, 2010 Try this code var scope = "global"; function checkscope() { var scope = "local"; document.write(scope); } checkscope(); and this scope = "global"; function checkscope() { scope = "local"; document.write(scope); myscope = "local"; document.write(myscope); } checkscope(); document.write(scope); document.write(myscope); http://www.mredkj.com/tutorials/reference_js_intro_ex.html Quote Link to comment Share on other sites More sharing options...
Omirion Posted February 14, 2010 Share Posted February 14, 2010 Simply put when you declare a var within a function like so Var foo = 1 Function myfunc(){ var foo = 0 alert(foo); } myfunc(); Alert(foo); You are making a local var, meaning foo is only accessible throughout the execution of your function an only to it. The result of calling myfunc() will be an alert msg with 0 The result of the alert msg outside the func will be 1. If you declare your var like so var foo = 1; Function myfunc(){ foo = 0; alert(foo); } myfunc(); alert(foo); The result of myfunc() will be and alert with 0. The result of calling alert(foo) outside the function will be 0. This is because when creating a var like so foo = 0 The function take the global var. An when done like so Var foo = 1 The function makes a foo var in local scope. Google "variable scope in javascript" Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.