Sunday, December 1, 2013

Javascript exercise: variable can be accessed before declared

This exercise show that we can access variable before declaration without error, what it return is undefined. But cannot access variable without declaration, it will stop the javascript.

variable can be accessed before declared
variable can be accessed before declared

Example code:
<!DOCTYPE HTML>
<html>
    <head>
        <title>Mobile-Web-App</title>

<script>
var testjavascript = (function (){
 console.log("Test Start");
 console.log("use var before declaration: " + my_var);
 
 var my_var;
 console.log("use var after declaration: " + my_var);
 
 local_var = "Hello World";
 console.log("use var after value assigned: " + my_var);
 
 console.log("Un-declared var: " + another_var);
 
 console.log("Test End");
});
 
console.log("testjavascript() run after document loaded.");
window.onload = testjavascript();
</script>
    </head>
    <body>
        <h1>Mobile-Web-App</h1>
        <h2>http://mobile-web-app.blogspot.com/</h2>
    </body>
</html>


No comments:

Post a Comment