Search This Blog

Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Flow Control and Looping Statements in java, javsscript, c#

 Flow control statements determine the next statement to execute. In this sense, the statements if-else, if, switch, while, for are flow control statements.
Conditional Statements:
    Conditional statements control whether a part of a script is executed depending the result of a particular expression (i.e. whether an expression returns a boolean true or false value). The two types of conditional structures are if and if ... else. In this section we will take a closer look at both of these conditional structures and provide some examples of their use.
Syntax:
if (condition)
{
   ...
} else if (condition1)
{
   ...
} else
{
   ...
}

Example: ( in javascript )
if (customerName == "Fred")
{
      document.write ("Hello Fred!");
} 
else if (customerName == "John")
{
      document.write ("Hello John!");
} 
else
{
      document.write ("You're not Fred! Where's Fred?");
}

Looping Statements:
1. for loops
Syntax:
for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
      statements to be executed
}

The initializer typically initializes a counter variable. Traditionally the variable i is used for this purpose. For example:
i = 0

This sets the counter to be the value i and sets it to zero.

The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times. For example, if we want to loop 100 times:

i < 100

Finally the loop expression specifies the action to perform on the counter variable. For example to increment by 1:

i++

Bringing this all together we can create a for loop to perform the task outlined in the earlier example:

var j = 10;

for (i=0; i<10; i++)
{
      j += j;
}

2. while loops: The for loop described above works well when you know how many times a particular task needs to be repeated. Clearly there will often be instances where something needs to be repeated until a certain condition is met, with no way of knowing how many repetitions are going to be needed to meet those criteria. To address this need JavaScript provides the while loop. In essence the while loop repeats a set of tasks until a specified condition is met.
Syntax:
while (''condition'')
{
      ''Statements''
}

    In that above syntax outline, condition is an expression that will return either true or false and JavaScript Statements represents the JavaScript to be executed while the expression is true. For example:

while ( i < 10 )
{
      i = i + j;
}

    In the above example, the while expression will evaluate whether i is less than 10. If it is already greater than 10 then the code in the braces is skipped and the loop exits without performing any tasks. If it is not greater than 10 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of i. This process repeats until i is greater than 10, at which point the loop exits

switch Statements: when a need arises to evaluate a large number of conditions. An easier way to handle such situations is to use the switch statement.
Syntax:
switch (''value'')
{
     case "''match1''" :
     ''statements''
     break;

     case "''match2''" :
     ''statements''
     break;

     case "''match3''" :
     ''statements''
     break;

     case "''match4''" :
     ''statements''
     break;

     case "''match5''" :
     ''statements''
     break;

     default :
     ''statements''
     break;
}
    There can be any number of case statements - basically as many as you need to fully compare the value in the switch statement against the possible options (represented by match1 through to match5 in the above example) specified by the case statements. When a match is found the statements corresponding to the matching case are executed. Note the break; statement. Without the break all the cases after the matching case will also be executed.

    The default statement specifies the action that should be taken if no match is found. The following provides an example of the switch statement in action:

Example: (in javascript)
var carModel = "Focus";

switch (carModel)
{
     case "Durango" :
     document.write ("Manufactured by Dodge");
     break;

     case "Camry" :
     document.write ("Manufactured by Toyota");
     break;

     case "Focus" :
     document.write ("Manufactured by Ford");
     break;

     case "320i" :
     document.write ("Manufactured by BMW");
     break;

     case "Civic" :
     document.write ("Manufactured by Honda");
     break;

     default  :
     document.write ("Unknown Car Model");
     break;
}

Breaking a Loop: Occasionally it is necessary to exit from a loop before it has met whatever completion criteria were specified. To achieve this, the break statement must be used. The following example contains a loop that uses the break statement to exit from the loop when i = 100, even though the loop is designed to iterate 1000 times:

for (i = 0; i < 1000; i++)
{
        if (i == 10) 
        {
             break;
        }
}

Skipping Statements in Current Loop Iteration: The break statement, when encountered in a loop breaks skips all remaining statements in the loop body and breaks the loop. The continue statement also skips all remaining statements in the loop for the current iteration, but returns to the top of the loop and allows it to continue running.
Share:

Declaring constants in javascript

 Declare constants in javascript:
Syntax
  const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
  nameN: The constant's name, which can be any legal identifier.
  valueN: The constant's value; this can be any legal expression, including a function expression.
Description
    This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).

    The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

   All the considerations about the "temporal dead zone" apply to both let and const.

   A constant cannot share its name with a function or a variable in the same scope.

Examples: The following example demonstrates how constants behave. Try this in your browser console.

// NOTE: Constants can be declared with uppercase or lowercase, but a common
// convention is to use all-uppercase letters.

// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

// MY_FAV is 7
console.log('my favorite number is: ' + MY_FAV);

// trying to redeclare a constant throws an error -  Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
const MY_FAV = 20;

// the name MY_FAV is reserved for constant above, so this will fail too
var MY_FAV = 20;

// this throws an error too
let MY_FAV = 20;

// it's important to note the nature of block scoping
if (MY_FAV === 7) {
    // this is fine and creates a block scoped MY_FAV variable
    // (works equally well with let to declare a block scoped non const variable)
    let MY_FAV = 20;

    // MY_FAV is now 20
    console.log('my favorite number is ' + MY_FAV);

    // this gets hoisted into the global context and throws an error
    var MY_FAV = 20;
}

// MY_FAV is still 7
console.log('my favorite number is ' + MY_FAV);

// throws an error - Uncaught SyntaxError: Missing initializer in const declaration
const FOO;

// const also works on objects
const MY_OBJECT = {'key': 'value'};

// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};

// However, object keys are not protected,
// so the following statement is executed without problem
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable

// The same applies to arrays
const MY_ARRAY = [];
// It's possible to push items into the array
MY_ARRAY.push('A'); // ["A"]
// However, assigning a new array to the variable throws an error - Uncaught TypeError: Assignment to constant variable.
MY_ARRAY = ['B'];

Share:

Basic outline for learning a programming language:

 Basic outline for learning a programming language:
  - Requires about keywords when name variables, function
  - Operators
    + Mathematical operators: +, -, *, /, ++, --, \, %
    + Relational operators: ==, !=, >, <, >=, <=
    + Logical operators: &&, ||
    + Bitwise Operators: &, |
  - Data types; char, string, number ( byte, integer, long, float, double)
  - Declare and assign constant, variable, function, class
  - Control commands: if, for, while, switch, continue, break
Share:
Powered by Blogger.

Recent Posts

Pages