Javascript Statement








Javascript statements are terminated by a semicolon.

Or you can omit the semicolon and let the parser determine where the end of a statement is.

Including semicolons helps prevent errors.

The first line of code has no semicolon. It leaves the parser to decide.

var sum = a + b        //valid even without a semicolon - not recommended
var diff = a - b;      //valid - preferred

The following code has two statements and each outputs a string to the web page.

<!DOCTYPE HTML>
<html>
<body>
  <script type="text/javascript">
    document.writeln("This is a statement");
    document.writeln("This is also a statement");
  </script>
</body>
</html>

Click to view the demo

The code above generates the following result.





Block

Multiple statements can be combined into a code block by using C-style syntax, beginning with { and ending with }:

if (test){
   test = false;
   console.log(test);
}

The best practice is to use code blocks with control statements, even if there's only one statement.

if (test)
   alert(test);     //valid, but error-prone and should be avoided

if (test){           //preferred
   console.log(test);
}





Comments

Javascript uses C-style comments for both single-line and block comments.

A single-line comment begins with two forward-slash characters, such as this:

//This is a single line comment.

A block comment begins with /* and ends with */, as in this example:

/*
 * This is a multi-line
 * Comment
 */

The following code uses comments to Javascript code.

<!DOCTYPE HTML>
<html>
<body>
  <script type="text/javascript">
      //this is a comment
    document.writeln("This is a statement");
    document.writeln("This is also a statement");
    /* more comments<!--from   w  w  w.  j  a  va2 s  . c  om-->
       more comments
       more comments
       more comments
    */
  </script>
</body>
</html>

Click to view the demo

Strict Mode

Strict mode is a different parsing and execution model for JavaScript.

unsafe activities, erratic behavior are addressed and errors are thrown.

To enable strict mode for an entire script, include the following at the top:

"use strict";

This pragma that tells JavaScript engines to change into strict mode.

You may specify a function in strict mode by including the pragma at the top of the function body:

function doSomething(){
   "use strict";
   //function body
}

When you are running in strict mode, you cannot define variables named eval or arguments. Doing so results in a syntax error. Both eval and arguments are reserved words.