Tutorial:JavaScript
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
Anonymous Functions
Anonymous functions are useful because you can limit their execution to a variable... which means you can hide their execution due to scope! A good example of this is the Google Analytics javascript code. Google just wants their code to execute. They don't want anything changed.
Example: Static Function
Notice how once test() is declared, it can always be called.
Code
<script>
function test() { log("test"); } test(); if (true) { test(); } function anotherTest() { test(); } anotherTest(); </script>
Output
test test test
Example: Anonymous Function
In this example the function only exists within the actual execution of placeholder().
Code
<script> function placeholder() { var testFunc = function() { log("test"); }; testFunc(); } placeholder(); testFunc(); </script>
Output
test - Uncaught ReferenceError: testFunc is not defined
Example: Anonymous Function within Anonymous Function
The above example was interesting, but seemed a little heavy because we still had to create an actual static function first. This example shows how to create an anonymous function which declares even more stuff inside it and immediately executes so nothing can get intercepted.
Code
<script> (function() { var testFunc = function() { log("test"); }; testFunc(); })(); testFunc(); </script>
Output
test - Uncaught ReferenceError: testFunc is not defined