1. Computing

JavaScript By Example

10. Blocks

By

Being able to put just one statement in the true and false paths of an if statement is not going to be all that useful. We need to be able to include more statements than that. JavaScript provides a means to include multiple statements anywhere that a single statement is allowed. All we need to do this is to combine the statements together into a block. A block of statements can be substituted anywhere that a single statement is allowed.

We create a block of statements in JavaScript by wrapping those statements inside of {}. You can even nest blocks one inside another.

In order to more easily see where a particular block starts and ends it is recommended that all of the code within the block be indented by the same amount (usually two or three characters is enough but you should be consistent with indenting). Indenting each block will make it easier to see where you have nested blocks and which } is intended to close which block. You need to note though that JavaScript pays no notice of the indentation and if you leave out a } or add an extra one then the blocks may not be closed in the spots you intend.

Another way in which JavaScript differs from some other languages with regard to blocks is that in JavaScript a block does not define a scope (if you don't know what that means we'll get to it in example 16).

Note that to test this example try adding a ? followed by your name to the end of the address of the page - example10.html?Stephen - the script will add the number of characters in the name you enter to the end of the message it displays.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 10</title>
</head>
<body>
<p id="ex">JavaScript is not available.</p>
<script type="text/javascript" src="example10.js"></script>
</body>
</html>

JavaScript


var name, count; name = window.location.search.substring(1);
if ('' === name) {
  count = 0;
  document.getElementById('ex').innerHTML = 'Who are you? - ' + count;
  }
else {
  count = name.length();
  document.getElementById('ex').innerHTML = 'hello ' + name + ' - ' + count;
  }

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. JavaScript By Example - Blocks

©2014 About.com. All rights reserved.