Statements

JavaScript works on sets of statements. These statements have an appropriate syntax where the syntax depends on what the statements contain. A statement can have multiple lines in it. Basically, a statement is a set of instructions given to a computer browser to execute JavaScript code. A statement can return a value that is terminated with a semicolon. A statement can be a call for a certain action, for example:

Document.Write("hello world");

The preceding statement calls the in-built Write() function and prints the message hello world on the screen.

We can write multiple statements in one line separated by a semicolon; for example:

var a=20; var b=2;var c=a*b; document.write(c);

A statement can also be terminated with a line break, for example:

var a=20;
Document.Write(a);

Each statement in JavaScript runs one by one in order of the given instructions in the JavaScript program.

Expression statements

In JavaScript, there is a difference between a statement and an expression. Whenever a value is expected in your script or code, an expression produces that value using a statement.

An expression is made of literals, variables, operators, and methods. The data type of the returned value depends on the variable used in the expression. We can create a compound expression from a smaller expression's group depending on their data type.

x = Math.PI;
  cx = Math.cos(x);
  alert("cos(" + x + ") = " + cx);

Statements are basically actions performed in scripts, for example, loops and if-else are statements in JavaScript. Wherever JavaScript expects a statement and you can also write an expression, is called an expression statement. It fulfills purpose of both statement and expression. But this can not be reversed. We can not write a statement where JavaScript is expecting an expression. For instance, if statement can not be used as an argument to a function.

To prevent this from happening JavaScript doesn't allow us to use function expressions and object literals as statements, that is, expression statement should not start with:

  • Curly brace
  • Keyword function

Compound empty statements

A compound statement is a set of statements written in curly brackets and all these statements are separated by a semicolon. It combines multiple statements in a program into a single statement. A compound statement is also known as a block statement.

This type of statement is usually used with conditional statements such as if, else, for, while loop, and so on. Consider the following example:

if(x<10) //  if x is less than 10 then x is incremented {
  x++;
}

An empty statement is the opposite of a compound statement. There is no statement in an empty statement but just a semicolon. This semicolon means that no statement will be executed. Usually, empty statements are used when you need to put comments in your code. Consider the following example:

for(i=0; i<10; i++)
{} /*  Empty  */

Declaration statements

This statement is use to declare a variable or a function in JavaScript.

function

In JavaScript, the function keyword is used to declare a function in a program.

Here is a simple example where the myFunction function is declared:

function myFunction() {
  //block of code
}

var

In JavaScript, to declare a variable, we use the var keyword. We need to declare a variable before using it.

Consider the following example:

var a =5;
var b = 23.5;
var c = "Good morning";

Here is an example of both var and function:

var a=2;
var b=3;
function Addition(x,y) {
  return x+y;
}
var c= Addition(a,b)
Document.Write("The value of c is " + c)

The output of the preceding code will be as follows:

The value of c is 5

Conditional statements

In JavaScript, when we want to perform different actions for different statements, we use a conditional statement. These are a set of commands to perform different actions on different conditions. In JavaScript, there are three types of conditional statements, which are as follows:

  • if
  • else
  • switch

Basically, these statements show the flow of your code. Conditional statements control the flow of your program, that is, which action will be perform on which condition.

Consider an example where you have an e-commerce website and you want to display an offer label on a product when there is special offer on it. In such a scenario, you can place the appropriate code inside conditional statements.

If statements

In programming languages, the if statement is a control statement. An if statement has two important parts:

  • A condition
  • A code to perform the action

In JavaScript and other languages, the if statement makes decisions based on the variable and type of data. For example, if you write a script asking to be notified on your birthday, then when the time arrives, the message "It's your birthday today" will be displayed.

The if statement is only executed when the condition is true. If the expression is false, then it will not execute.

Syntax

Here is the syntax for an if statement in JavaScript:

if(condition) {
  // block of code
}

Example

For example, in JavaScript, we can write an if statement code as follows:

var cAge=25;
If (cAge>18) {
  document.write ("You must have CNIC");
}// if age is above 18 it displays that you must have a CNIC  

Else if statements

In JavaScript, there may be some situations when we require to make a decision based on different possibilities. The else if statement will only be executed when the previous statement is false and its condition is true. There are two major points of the else if statement, they are as follows:

  • There should be an if statement before any else if statement
  • You may use as many else if statements as desired, but at the end, you must have an else statement.

Syntax

Here is the syntax for a simple if statement in JavaScript:

if(condition 1) {
  // block of code
}
else if(condition 2) {
  //block of code
}
else {
  //  block of code
}

In the preceding syntax, two conditions can be checked for their validity.

Here is the syntax for a slightly more complex else if statement in JavaScript:

if(condition 1) {
  // block of code
}
else if(condition 2) {
  // block of code
}
else if(condition 3) {
  // block of code
}
else {
  // block of code
}

In the preceding syntax, three conditions can be checked for their validity.

Example

For example, if you have a web page and you want to check who is accessing that web page. You will put two custom messages in your script inside the Else if statement. You will write these as follows:

var person="Manager";
If(person=="Admin") {
  Document.Write("I am visiting it");
}
Else if(person=="Manager") {
  Document.Write("I am accessing it");
}
Else {
  document.write("hello kitty");
}

The Else if statement is one of the most advanced forms of statements in JavaScript. It makes a decision after checking all the if conditions. It is just a type of complex statement where every if is a part of an else statement. All conditions must be true within the parenthesis following the else if keyword. If any of the conditions are false, then the else part will be executed.

Switch statement

In programming languages, the switch statement execution depends only on the value of the expression. There are lists of cases against which checks are done. The checks are done sequentially; JavaScript interpreter checks the first case and its condition to check whether it is true or not. Similarly, checks are done for all case statements to check whether their conditions are true and to find a break statement. When the interpreter encounters the break statement, it exits the switch loop. The break statement is meant to ensure that the switch statement returns control to the calling function once one case is executed, interpreter does not forward the control to the next applicable case.

Syntax

Here is the syntax for a simple switch statement in JavaScript:

switch(condition/expression)
  case expression 1:
    //block of code
  break;
  case expression 2:
    //block of code
  break;

  case expression 3:
    //block of code
  break;

  default:
    //block of code
  break;

Example

Following is an example of a valid switch statement:

Switch (personName)
  case "Jack":
    alert("my name is Jack");
  Break;
  case "Ahmed":
    alert("my name is Ahmed");
  break;
  default:
    alert("my name is Talha");
  break;

If the preceding code does not find a matching case then it executes the default statement. Basically a switch statement is an expression which evaluates different statements in order to execute some code based on some conditions.

Loops

In programming languages, loops are used to execute a block of code a number of times, depending on a condition. For example, if you have a statement and you want to execute it over and over, you just put it in a loop. Loops are basically used for repetitive tasks.

Another specific example of a loop is that if you want to traverse an array to find a specific number, you have to iterate through array elements. Each iteration will get the next array index.

There are four types of loops in JavaScript, they are as follows:

  • for
  • while
  • do-WHILE
  • for-in

For repetitive tasks we put a set of instructions in a loop. To control the number of times a loop executes, we use control variables in a loop for incrementing or decrementing value of an iterator or counter variable, which will repeat the block of code. You can also use the break and continuous statements in a loop.

For loop

The for loops are used to loop through or execute a block of code, until a condition returns a false result. In a for loop, we mention how many times the script should perform. For example, you might want to execute your script 12 times.

Syntax

A for loop in JavaScript is the same as in other languages, such as C, C++, and Python. The for loop syntax has three important parts:

  • Initialization: This is where loop initializes the counter variable. This is the first statement when a loop starts its execution.
  • Condition: This is an expression to be evaluated before every loop iteration. If the condition is satisfied and is true, we enter the loop; otherwise, if the condition is not satisfied and the condition returns false, then we exit the for loop.
  • Increment/Decrement: This is used for iteration and for increasing or decreasing the counter variable value. This is an update statement where increment or decrement is executed.
    for (initialization; condition; increment / decrement) {
      //code block
    }

Example

Consider the following example of a basic counter code in JavaScript:

var i; // declares the variable i
for(i=1; i < 5 ; i++) {
  Document.Write("basic counter:"+i);
  Document.Write("<br/>");
}

The output will be as follows:

Basic counter:1
Basic counter:2
Basic counter:3
Basic counter:4

While loop

This is also a commonly used loop in JavaScript. The while loop executes a block of statements repeatedly as long as its condition is true. The loop exits when the condition becomes false.

Syntax

Here is the syntax for a while loop in JavaScript:

while (condition expression) {
  // code block
}

There are two parts of a while loop:

  • The condition statement
  • The while loop code written in curly brackets

The while loop conditions have to be met in order for the loop to work. If the condition breaks, then the loop breaks.

Example

Here is an example of the while loop, which will print numbers from 1 to 4:

var count= 0;
While(count<5) {
  Document.Write("count");
  Document.Write("<br/>");
  count++;
}

The output will be as follows:

1
2
3
4

Do while loop

The do while loop is also known as a post-test loop because it first executes the statement and then checks the condition. If the condition is true, then it will enter the loop, and if the condition is false, it will break out from the loop.

Syntax

Here is the syntax for the do while loop in JavaScript:

Do {
  //statement
}
While(condition);

There are two important parts of the do while loop:

  • A statement
  • A condition

The do while loop is similar to the while loop, but it checks the condition at the end of the loop. The do while loop executes the specified statement at least once before checking the condition.

Example

Here is an example of the do while loop that prints the values 1 to 5:

var i=1;
Do {
  document.write("The value of i is " + i + "</br>");
  i++;
}
While(i<6);

The output will be as follows:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5

Tip

The do while loop can be used where we need to execute the loop at least once, irrespective of whether or not the condition is met.

For in loop

There is another type on loop used in JavaScript that is known as the for in loop. This loop is used for object properties in JavaScript. In this loop, one property of the object is assigned to a variable name.

Syntax

Here is a syntax for the for in loop in JavaScript:

For (property in object) {
  //code block
}

Example

Here is an example of the for in loop:

var I;
For (I is navigator) {
  Document.Write(i);
}
Document.Write("The loop ends here");

Jumps and labeled statements

In JavaScript, the jump statements are used to force the flow of execution to jump to another condition in the script. Basically, it is used to terminate iterative statements. There are two types of jump statements in JavaScript:

  • Break
  • Continue

These statements are used when you immediately leave a loop or when you want to jump to another condition due to a condition in a code.

Break statement

In JavaScript, a break statement is used with a switch statement. It is used to exit a loop or a condition earlier than planned. Break statements are also used in the for loop and the while loop.

Syntax

Here is the syntax for the break statement in JavaScript:

Any loop(condition) {
  //block of code that will be executed
  break;
  //block of code that won't get executed
}

Example

Consider the following simple example:

var i=1;
While(i<10) {
  if(i==3) {
    Document.Write("Breaking from if loop");
    Break;
  }
  Document.Write("The value of i is " + i);
  i+=2;
}

The output will be as follows:

The value of i is 1
Breaking from if loop
The value of i is 3

Continue statement

The keyword continue will skip the current iteration.

Syntax

Here is the syntax for the continue statement in JavaScript:

Any loop(condition) {
  //block of code that will be executed
  Any loop (condition) {
    //block of code that will be executed
    continue;
    block of code that wont be executed
  }
  //block of code  that will be executed
}

Example

Consider the following simple example:

var i=1;
While(i<5) {
  if(i==3) //skip the iteration {
    Document.Write("Continue statement encountered");
    continue;
  }
  Document.Write("The value of i is " + i);
  i=i+2;
}

The output will be as follows:

The value of i is 1
Continue statement encountered

Return statement

In JavaScript, a return statement is used to return a value from a function. After returning the value, it stops the function execution. Every function and statement returns a value. If no return statement is provided, undefined value is returned instead.

Syntax

Here is the syntax for the return statement in JavaScript:

function myfunc(x, y) {
  //some block of code
  return x;
}
Document.Write("The result is " + myfunc(2, 3));

Example

Consider the following simple example showing the working of a return statement:

Function multiply(a,b) {
  return a*B;
}
var mul=multiply(2,3);
Document.Write("The result is "+ mul);

The output will be as follows:

The result is 6

Throw statement

A throw statement is used to create a user-defined error condition for the try and catch block. These errors are also called exceptions. We can create our own exceptions in a code script.

Syntax

Here is the syntax for the throw statement in JavaScript:

try {
  //block of code
  throw "error";
  //block of code
}
catch(error) {
  //block of code
}

Example

Let's take a look at the following code snippet:

Try {
  document.write( "hello world);//the code will throw an error due to the missing "
}
Catch(error) {
  Error.messageTxt;
}

Try catch finally statement

In a try statement we write the code that needs error testing when it is being executed. In a catch block, you write code to handle errors occurring in the try block. When you write code inside the try block, you must write a catch block to handle any error that might occur in the the try block. The finally statement executes when the try and catch statements are executed successfully.

Syntax

The syntax for a try, catch, and finally block is as shown in the following code snippet:

Try {//generate exception}
Catch {//error handling code}
Finally {//block of code which runs after try and catch}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.204