Tutorial:JavaScript

From Metrixstream
(Difference between revisions)
Jump to: navigation, search
(Code)
(Example)
Line 40: Line 40:
 
  B: 11
 
  B: 11
 
  C: 11
 
  C: 11
 +
 +
== Example ==
 +
 +
=== Code ===
 +
 +
<script>
 +
 +
var value = 10;
 +
 +
function test() {
 +
  value = 11;
 +
 +
  log("test: " + value);
 +
}
 +
 +
log("A: " + value);
 +
 +
test();
 +
 +
log("B: " + value);
 +
 +
</script>

Revision as of 13:32, 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

Example

Code

<script>

var value = 10;

function test() {
  value = 11;

  log("test: " + value);
}

log("A: " + value);

test();

log("B: " + value);

</script>
Personal tools