Tutorial:JavaScript

From Metrixstream
(Difference between revisions)
Jump to: navigation, search
Line 10: Line 10:
 
   
 
   
 
  </script>
 
  </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

Revision as of 13:31, 6 June 2012

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
Personal tools