Tutorial:JavaScript
From Metrixstream
Revision as of 13:34, 6 June 2012 by MetrixAdmin (Talk | contribs)
Contents |
Logging
Logging is your friend. It isn't always supported, so you need to write your own wrapper around it. All logging will go to the console window which is located in the developer tools for most popular web browsers.
<script> function log(str) { if (window["console"] && window["console"]["log"]) window["console"]["log"](str); } </script>
Scope
Scope is important because variables go in and out of existence depending on where they are referenced from. This gets extremely important to understand when using variables of the same name.
Example
Code
<script> var value = 10; log("A: " + value); if (true) { var value = 11; log("B: " + value); } log("C: " + value); </script>
Output
A: 10 B: 11 C: 11
Example
Code
<script> var value = 10; function test() { value = 11; log("test: " + value); } log("A: " + value); test(); log("B: " + value); </script>
Output
A: 10 test: 11 B: 11
Example
Code
<script> var value = 10; function test() { var value = 11; log("test: " + value); } log("A: " + value); test(); log("B: " + value); </script>
Output
A: 10 test: 11 B: 10