Sunday, 24 July 2016

JavaScript Functions with Timer

Timer
timer allows us to execute javascript functions after a specified period or at specific time and can also synchronize multiple events in a particular time span.

Various methods that allows us to use timer

  • setTimeout() - executes code at specified interval. Syntax : setTimeout(function,delaytime) function defines the method that the timer calls and the delaytime specifies the number of milliseconds to wait before calling the method.
  • clearTimeout() - deactivates the timer that is set using the setTimeout() method. Syntax : clearTimeout(timer)
  • setInterval() - executes function after a specified time interval. Syntax : setInterval(function, intervalTime). function parameter specifies the method to be called and intervalTime parameters specifies the time interval between the function calls.
  • clearInterval() - deactivates the timer that is set using the setInterval() method. Syntax : clearInterval(timer)
Example 1
<!DOCTYPE html>
<html>
<head>
    <title>javaScript setTimeout() method</title>
</head>
<body>
    <h1>JavaScript setTimeout() method</h1>
    <script>
        function func_setTimeout() {
            var time = setTimeout("alert('2 seconds')", 2000);
        }
    </script>
    <form>
        <input type="button" value="setTimeout() alert" onclick="func_setTimeout()" />
    </form>
</body>
</html>

Example 2: function will be called again and again in case of setInterval() method
<!DOCTYPE html>
<html>
<head>
    <title>javaScript setInterval() method</title>
</head>
<body>
    <h1>JavaScript setInterval() method</h1>
    <script>
        function func_setTimeout() {
            var time = setInterval("alert('2 seconds')", 2000);
        }
    </script>
    <form>
        <input type="button" value="setInterval() alert" onclick="func_setTimeout()" />
    </form>
</body>
</html>


JavaScript Function Scope and Closures

Scope
scope refers to an area within which a function and its variables are accessible.
Functions can have two scope

  • Global - specifies that a function can be accessed from anywhere in the program.
  • Local - specifies that a function can be accessed within the parent function.
Closure
A closure is a variable that is created inside a function and continues to exist after the function has finished executing.

Example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript function scope</title>
</head>
<body>
    <h1>JavaScript function scope</h1>
    <script>
        function func_global()
        {
            var name = "closure";
            func_local();
            function func_local(name)
            {
                document.write("I am in Local Scope  <br />");
            }
            document.write("I am in Global Scope & name is " + name);
        }
        func_global();
    </script>
</body>
</html>



JavaScript Functions

function
function is a collection of statements that is executed when it is called at some point in the program.
function enhances the code readability and usability by using it number of times in a program, without need of writing the repeated code.

function are divided into two categories

  • function without parameters
  • function with parameters
Built-in global function
  • alert() - It is used to display alert message such as some error or message. It contains an OK button, which user has to click to continue with the execution of the code.
  • confirm() - It is used to display message as well as return true or false value. The confirm box displays a dialog box with two button OK and Cancel. Javascript will be executed on the basis of the choice user takes.
  • prompt() - It is used to take input from the user. It contains a text box and OK and Cancel buttons. If the user clicks OK button, the input value is returned. Otherwise, the box returns null.
  • eval() - evaluates and executes a string and return null.
  • isFinite() - returns a boolean value, true or false, indicating whether the argument passed to it is finite or infinite.
  • isNaN() - determines whether or not a value is an illegal number. NaN standa for not a number.
  • parseInt() - extracts a number from the beginning of a string. this function parses the string and returns the first integer value found in the string.
  • parseFloat() -  extracts a number from the beginning of a string. this function parses the string and returns the first floating point value found in the string.
  • Number() - converts a value of an object into a number. if the object contains boolean value,then it returns 1 for true and 0 for false.
  • escape() - encode the string so that it can be transmitted across any network to any computer that supports ASCII characters. This function encodes special character except *,@,-,_,+ and /.
  • unescape() - decodes a string that is encoded by the escape() function.
Defining function
function function_name (parameter1, parameter2,...parameter n)
{
//block of statements
}

Invoking function
function_name(parameter1 value, parameter2 value ... parameter n value);

Return Statement
A return statement specifies the value that is returned from a function.
Syntax
return value;

Example 1

<!DOCTYPE html>
<html>
<head>
    <title>javaScript function</title>
</head>
<body>
    <h1>JavaScript function</h1>
    <script>
        var number1=89;
        var number2=78;
        var number3=67;
        function func_Addition(number1, number2, number3)  //function definition
        {
            var sum = number1 + number2 + number3;
            document.write("Sum :" + sum);
        }

        func_Addition(number1, number2, number3); //function invocation
    </script>
</body>
</html>

Example 2
<!DOCTYPE html>
<html>
<head>
    <title>javaScript function</title>
</head>
<body>
    <h1>JavaScript function</h1>
    <script>
        var number1=89;
        var number2=78;
        var number3=67;
        function func_Addition(number1, number2, number3) // function definition
        {
            var sum = number1 + number2 + number3;
            return sum;   // return value
        }

        var result = func_Addition(number1, number2, number3); //function invocation
        document.write("sum :" + result);
    </script>
</body>
</html>

JavaScript Popup Boxes

Popup Boxes
It allows us to display message in a window and can also be used to prompt user to enter some input.

There are three type of popup boxes

  • alert box
  • confirm box
  • prompt box
alert box
It is used to display alert message such as some error or message. It contains an OK button, which user has to click to continue with the execution of the code.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript alert box</title>
</head>
<body>
    <h1>JavaScript alert box</h1>
    <script>
        alert("This is alert box");
    </script>
</body>
</html>


confirm box
It is used to display message as well as return true or false value. The confirm box displays a dialog box with two button OK and Cancel. Javascript will be executed on the basis of the choice user takes.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript confirm box</title>
</head>
<body>
    <h1>JavaScript confirm box</h1>
    <script>
        var result = confirm("Please choose the option");
        if (result) {
            document.write("ok button clicked");
        }
        else {
            document.write("cancel button clicked");
        }
    </script>
</body>
</html>
When OK Clicked

When Cancel Clicked


prompt box
It is used to take input from the user. It contains a text box and OK and Cancel buttons. If the user clicks OK button, the input value is returned. Otherwise, the box returns null.
Example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript prompt box</title>
</head>
<body>
    <h1>JavaScript prompt box</h1>
    <h1>Enter your age</h1>
    <script>
        var age = prompt("Please enter your age");
        if (age == null || age == "")
        {
            document.write("Please enter valid age");
        }
        else
        {
            document.write("your age is :" + age);
        }
    </script>
</body>
</html>

If nothing is entered

If data is entered


JavaScript break, continue Statement

Jump Statement
It allows us to skip certain statement or jump out of statement.

There are two type of jump statement

  • break statement
  • continue statement
break statement
break statement allows us to break or exit out of loop. It causes loop to immediately exited. If the loops has statements after the break statement, those statement are not executed.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript break statement</title>
</head>
<body>
    <h1>JavaScript break statement</h1>
    <script>
        var number1 = 4;
        while (number1 > 0)
        {
            document.write("count : " + number1 + "<br/>");
            number1--;
            break;
            document.write("statement will not get executed");
        }
    </script>
</body>
</html>


continue statement
continue statement is also used to stop the execution of a loop. However, the continue statement does not exit the loop; it executes the condition for the next iteration of the loop.If the loops has statements after the continue statement, those statement are not executed.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript continue statement</title>
</head>
<body>
    <h1>JavaScript continue statement</h1>
    <script>
        var number1 = 4;
        while (number1 > 0)
        {
            document.write("count : " + number1 + "<br/>");
            number1--;
            continue;
            document.write("statement will not get executed");
        }
    </script>
</body>
</html>

JavaScript Loops(while, do...while, for loop)

Loops
Loops allows us to execute a particular group of statement repeatedly.
The number of times the statements executes depends on the particular condition. Until the condition is true statement will execute.

There are three types of loops

  • while loop
  • do...while loop
  • for loop
while Loop
In while loop condition is checked first, if the condition is true the statements will executes until the condition is not false.
If condition is false in the first iteration the statement will never execute.
Syntax
while(condition)
{
statement 1
}
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript while loop</title>
</head>
<body>
    <h1>JavaScript while loop</h1>
    <script>
        var number1 = 4;
        var number2 = 8;
        while (number1 > 0)
        {
            document.write("count : " + number1 + "<br/>");
            number1--;
        }
    </script>
</body>
</html>


do...while loop
In the do...while condition is checked at the last, which means that the statement will execute at least one time.
Syntax
do
{
statement 1
}
while(condition);
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript do...while loop</title>
</head>
<body>
    <h1>JavaScript do...while loop</h1>
    <script>
        var number1 = 4;
        var number2 = 8;
        do {
            document.write("count : " + number1 + "<br/>");
            number1--;
        } while (number1 > 0)
    </script>
</body>
</html>



for loop
It allows us to execute statements predefined number of times. Number of iteration in for loop is known before hand.
Syntax
for(initialization_statement; condition; updation_statement)
{
statement 1
}
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript for loop</title>
</head>
<body>
    <h1>JavaScript for loop</h1>
    <script>
        var number1;
        for (number1 = 0; number1 < 6; number1++)
        {
            document.write("count :" + number1 + "<br/>");
        }
    </script>
</body>
</html>


JavaScript Operator Precedence

Operator Precedence
Operators are used to perform various task, such as calculation, making decision etc.
The combination  of operators and operands form expressions. Expressions are evaluated in the order of high to low precedence.
Below table showing operators in the decreasing order of precedence from top to bottom and left to right.
Operator Type
Individual Operator
member
., []
New
new
function call
()
Increment
++
Decrement
--
Logical-not
!
Bitwise not
~
Unary +
+
Unary negation
-
typeof
typeof
void
void
Delete
delete
Multiplication
*
Division
/
Modulus
%
Addition
+
Subtraction
-
Bitwise shift
<<, >>, >>>
Relational
<, <=, >, >=
In
in
instanceof
instanceof
Equality
==, !=, ===, !==
Bitwise-and
&
Bitwise-xor
^
Bitwise-or
|
Logical-and
&&
Logical-or
||
Conditional
?:
Assignment
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=
Comma
,




example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript Operator Precedence</title>
</head>
<body>
    <h1>JavaScript Operator Precedence</h1>
    <script>
        document.write("2 * 3 / 6 + 4 - 4 : Result : " + (2 * 3 / 6 + 4 - 4) + "<br />");
        document.write("(2 * (3 / 6 + 4) - 4) : Result : " + (2 * (3 / 6 + 4) - 4) + "<br />");
        document.write("((2 * 3 / 6 + 4) - 4) : Result : " + ((2 * 3 / 6 + 4) - 4) + "<br />");
    </script>
</body>
</html>



JavaScript Logical and Conditional Operators

Logical Operators

  • && : returns true only if both the operands are true, otherwise returns false.
  • || : returns true only if either of the operand is true, otherwise returns false.
  • ! : negates the operand, returns true if the operand is false and return false if the operand is true.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Logical Operators</title>
</head>
<body>
    <h1>JavaScript Logical Operators</h1>
    <script>
        var number1 = true;
        var number2 = false;
        var number3 = true;
        document.write("number1 && number3 :" + (number1 && number3) + "<br />");
        document.write("number1 && number2 :" + (number1 && number2) + "<br />");
        document.write("number1 || number3 :" + (number1 || number2) + "<br />");
        document.write("number1 || number3 :" + (number1 || number3) + "<br />");
        document.write("!(number1 && number3) :" + !(number1 && number3) + "<br />");
        document.write("!(number1 && number2) :" + !(number1 && number2) + "<br />");
        document.write("!(number1 || number3) :" + !(number1 || number2) + "<br />");
        document.write("!(number1 || number3) :" + !(number1 || number3) + "<br />");

    </script>
</body>
</html>


Conditional Operators
  • ?: - returns the second operand if the first operand is true. However, if the first operand is false, it returns the third operand.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Conditional Operators</title>
</head>
<body>
    <h1>JavaScript Conditional Operators</h1>
    <script>
        var number1 = true;
        var number2 = false;
        var number3 = true;
        document.write("number1 && number3 ? number1 : number3 : Result - " + (number1 && number3 ? number1 : number3) + "<br />");
        document.write("number1 && number2 ? number1 : number2 : Result - " + (number1 && number2 ? number1 : number2) + "<br />");
    </script>
</body>
</html>


JavaScript Comparison Operators

Comparison Operators
Used to compare the values of operators and returns true or false.

Different Comparison Operators

  • == : returns true if both the operands are equal; otherwise, it returns false.
  • != : returns true if both the operands are not equal; otherwise,it returns false.
  • > : returns true it the left hand side operand is greater than right hand side operand. otherwise, returns false.
  • >= : returns true it the left hand side operand is greater than or equal to right hand side operand. otherwise, returns false.
  • < : returns true it the left hand side operand is less than right hand side operand. otherwise, returns false.
  • <= : returns true it the left hand side operand is less than or equal to right hand side operand. otherwise, returns false.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Comparison Operators</title>
</head>
<body>
    <h1>JavaScript Comparison Operators</h1>
    <script>
        var number1 = 2567;
        var number2 = 50;
        number3 = 89;
        document.write("2567 == 2567 :" + (number1 == number1) + "<br />");
        document.write("2567 == 50 :" + (number1 == number2) + "<br />");
        document.write("2567 != 2567 :" + (number1 != number1) + "<br />");
        document.write("2567 != 50 :" + (number1 != number2) + "<br />");
        document.write("2567 > 50 :" + (number1 > number2) + "<br />");
        document.write("2567 < 89 :" + (number1 < number3) + "<br />");
        document.write("2567 >= 89 :" + (number1 >= number3) + "<br />");
        document.write("2567 <= 89 :" + (number1 <= number3) + "<br />");

    </script>
</body>
</html>


JavaScript Assignment Operators

Assignment Operators
This are used to assign values to a variable or methods.

Different Assignment Operators

  • = : assigns value to the left hand side variable.
  • += : adds the right hand side operand to the left hand side operand and assigns the result to the left hand side operand.
  • -= : subtracts the right hand side operand from the left hand side operand and assigns the result to the left hand side operand.
  • *= : multiplies the right hand side operand with the left hand side operand and assigns the result to the left hand side operand.
  • /= : divides the left hand side operand with the right hand side operand and assigns the quotient to the left hand side operand.
  • %= : divides the left hand side operand with the right hand side operand and assigns the remainder to the left hand side operand.
Example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript Assignment Operators</title>
</head>
<body>
    <h1>JavaScript Assignment Operators</h1>
    <script>
        var number1 = 2567;
        var number2 = 50;
        var number3;
        number3 = number1;
        document.write("Number 1 :" + number1 + "<br />");
        document.write("Number 2 :" + number2 + "<br />");
        document.write("Number 3 :" + number3 + "<br />");
        number2 += number1;//2617
        document.write("Adding Number 1 & Number 2 :" + number2 + "<br />");
        number2 -= number1;//50
        document.write("Subtracting Number 2 from Number 1 :" + number2 + "<br />");
        number1 +=number3;//5134
        document.write("Adding Number 1 & Number 3 :" + number1 + "<br />");
        number1 -= number3;//2567
        document.write("Subtracting Number 1 from Number 3 :" + number1 + "<br />");
        number1 /= number3;//1
        document.write("Dividing Number 1 from Number 3 for Quotient:" + number1 + "<br />");
        number1 %= number3;//1
        document.write("Dividing Number 1 from Number 3 for Remainder:" + number1 + "<br />");
        number1 *= number2;//50
        document.write("Dividing Number 1 with Number 2:" + number1 + "<br />");
    </script>
</body>
</html>


JavaScript Arithmetic Operators

Operators
An operator is a symbol or a word that is reserved for some specific task or action.

Different JavaScript Operators

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Conditional Operator
Arithmetic Operators
This are used to perform some mathematical operations. Such as addition, subtraction, multiplication etc.
Different Arithmetic Operators 
  • + : adds two numbers or joins two strings. this operator also represents a positive number when it is prefixed to a number.
  • - : subtracts two numbers or represents a negative number.
  • * : multiplies two numbers.
  • / : divides two numbers and returns the quotient,
  • % : divides two numbers and returns the remainder.
  • ++ : increment the value of the number by 1. it can be prefixed or suffixed to a number. when prefixed, the value is incremented in the current statement, and when suffixed, the value is incremented after the current statement.
  • -- : decrements the value of the number by 1. it can be prefixed or suffixed to a number. when prefixed, the value is decremented in the current statement, and when suffixed, the value is decremented after the current statement.
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Arithmetic Operators</title>
</head>
<body>
    <h1>JavaScript Arithmetic Operators</h1>
    <script>
        var number1 = 2567;
        var number2 = 50;

        document.write(number1 + number2 + "<br />");
        document.write("Indian" + " Ocean" + "<br />");
        document.write(number1 - number2 + "<br />");
        document.write(number1 / number2 + "<br />");
        document.write(number1 % number2 + "<br />");
        document.write(number1++  + "<br />");
        document.write(++number1  + "<br />");
        document.write(number2-- + "<br />");
        document.write(--number2 + "<br />");
    </script>
</body>
</html>


JavaScript Variables

Variables
 variables are used to store data temporarily. variable consist of a name, value and memory address.
name is used to identify variable uniquely, value refers to the data stored in the variable, and memory address refers to the memory location of the variable.

declaring a variable
var variablename; //Single variable declared
var variablename1, variablename2, variablename3 // multiple variable declared.

declaring and defining a varible
var variablename=1234;
or
var variablename;
variablename=1234;

JavaScript allows us to store multiple types of values in a variable. Same variable can be used to store both string and a number at a different times in a script. This is why javaScript is considered poorly typed.
variable stores most recent value assigned to it.

example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript Variable</title>
</head>
<body>
    <h1>JavaScript Variable</h1>
    <script>
        var numberLiteral = 23;
        var _floatingpointLiteral = 45.908;
        var $_booleanLiteral = true;
   
        document.write(numberLiteral + "<br />");
        document.write(_floatingpointLiteral + "<br />");
        document.write($_booleanLiteral + "<br />");

        function funcNumber(i) {
            document.write(i + "<br />");
        }
        funcNumber(numberLiteral);
        numberLiteral = "Reusing Number literal";
        funcNumber(numberLiteral);
        numberLiteral = 8.9087;
        funcNumber(numberLiteral);
    </script>
</body>
</html>

JavaScript Reserved Words

Reserved Words
Reserved words are those words whose meanings are already defined to the JavaScript interpreter.
So, this words cannot be used as identifier for variables and methods.

List of Reserved Words

  • abstract
  • boolean
  • break
  • byte
  • case
  • catch
  • char
  • class
  • const
  • continue
  • default
  • delete
  • do
  • double
  • else
  • extends
  • false
  • final
  • finally
  • float
  • for
  • function
  • goto
  • if
  • implements
  • import
  • in
  • instanceof
  • int
  • interface
  • native
  • new
  • null
  • package
  • private
  • protected
  • public
  • return
  • short
  • static
  • super
  • switch
  • synchronized
  • this
  • throw
  • throws
  • transient
  • true
  • try
  • typeof
  • use
  • var
  • void
  • volatile
  • while
  • with
example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Reserver Words</title>
</head>
<body>
    <h1>JavaScript Reserved Words</h1>
    <script>
        var numberLiteral = 23;
        var _floatingpointLiteral = 45.908;
        var $_booleanLiteral = true;
        
        document.write(numberLiteral + "<br />");
        document.write(_floatingpointLiteral + "<br />");
        document.write($_booleanLiteral + "<br />");

        function funcNumber(i) {
            document.write(i + "<br />");
        }
        funcNumber(numberLiteral);
    </script>
</body>
</html>


JavaScript Identifiers

Identifiers
It is the names given to all the components, like variables, methods.
ECMAScript has defined some rules for identifiers.

  • Identifier must start with a letter, dollar sign ($), or underscore (_).
  • Identifier cannot start with a number.
  • Identifier can contain any combination of letters, a dollar sign, underscore and numbers after the first character.
  • Identifier can be of any length.
  • Identifier are case-sensitive, for example number and Number are different identifier.
  • Identifier cannot contain reserved world or keywords.
example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Identifier</title>
</head>
<body>
    <h1>JavaScript Identifier</h1>
    <script>
        var numberLiteral = 23;
        var _floatingpointLiteral = 45.908;
        var $_booleanLiteral = true;
        var $string_Literal = "This is a String";
        var _arrayLiteral = ["array literal 1", "array literal 2", "array literal 3"];
       
        document.write(numberLiteral + "<br />");
        document.write(_floatingpointLiteral + "<br />");
        document.write($_booleanLiteral + "<br />");
        document.write($string_Literal + "<br />");
        document.write(_arrayLiteral[0] + "<br />");
        document.write(_arrayLiteral[1] + "<br />");
        document.write(_arrayLiteral[2] + "<br />");
    </script>
</body>
</html>


JavaScript Literals

Literals
A literal is a data value that represents a fixed value in a program.

Types of Literals 

  • Numeric Literal
  • Floating-point Literal
  • Boolean Literal
  • String Literal
  • Array Literal
  • Regular Expression Literal
  • Object Literal
Numeric Literal
A numeric literal can be defined in the decimal, hexadecimal, octal.
Decimal include digits from 0-9 without a leading zero.
Hexadecimal include digits 0-9 and A-F or a-f, a leading 0x indicates hexadecimal.
Octal numeric include digits from 0-7, a leading 0 indicates octal.

example
77, 90 //decimal base 10
023, 054 //octal base 8
0x3452, 0x7788 //hexadecimal base 16

Floating-point Literal
It can have the following parts
  • A decimal integer that can be positive or negative
  • A decimal point (.)
  • A fraction (another decimal number)
  • An exponent (optional)
example
2.9089, -3.4567

Boolean Literal
It can be either true or false.

String Literal
It can be either zero or more characters enclosed in double (") or  single (') quotation mark.

example
"xycn"
'123456667'
Special Characters that can be used in the String literals

  • \t - represents a tab.
  • \f - represents a form feed, which is also referred as form feed.
  • \b - represents a backspace.
  • \n - represents a new line.
  • \r - represents a carriage return character, which is used to start a new line of text.
  • \" - represents a double quote.
  • \' - represents a single quote.
  • \\ - represents a back space.
  • \v - represents a vertical tab.
  • \uXXXX - represents a unicode character specified by a four digit hexadecimal number.
Array Literal
It is a list of zero or more expressions representing array elements that are enclosed in a square brackets ([]).

example
var numbers = ["123","234","456"]

Regular Expression Literal
Also known as RegExp, is a pattern used to match a character or string in some text.

example
var newregexp=/abc/;
or var newregexp= new RegExp("abc");

Object Literal
It is a collection of name-value pair enclosed in curly braces ({}).

example
var sports = {cricket: 11, football: 14, chess: 5};

Example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript Literal</title>
</head>
<body>
    <h1>JavaScript Literal</h1>
    <script>
        var numberLiteral = 23;
        var floatingpointLiteral = 45.908;
        var booleanLiteral = true;
        var stringLiteral = "This is a String";
        var arrayLiteral = ["array literal 1", "array literal 2", "array literal 3"];
       
        document.write(numberLiteral + "<br />");
        document.write(floatingpointLiteral + "<br />");
        document.write(booleanLiteral + "<br />");
        document.write(stringLiteral + "<br />");
        document.write(arrayLiteral[0] + "<br />");
        document.write(arrayLiteral[1] + "<br />");
        document.write(arrayLiteral[2] + "<br />");
    </script>
</body>
</html>


JavaScript Comments, Semicolon, White space and Line breaks

Comments
Commented code is ignored at the time of program execution. It is used to provide additional information such as description of the function, purpose of the code and many others.
We can comment either a single line or multiple line.

  • Single Line Comment - Starts with //
  • Multi Line Comment - Starts with /* and ends with */
example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Comment</title>
</head>
<body>
    <h1>JavaScript Comment</h1>
    <script>
        var number = 23;
       // var Number = 45; Single line Comment
        var NumBer = 67;
        document.write(number);
        /* Multilie Comment
        document.write(Number);
        document.write(NumBer); */ 
    </script>
</body>
</html>



Semicolon
In JavaScript, statements are generally followed by semicolon, which indicates the termination of the statement. However, it is not necessary to use the semicolon at the end of the statement.
example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Optional Semicolon</title>
</head>
<body>
    <h1>JavaScript Optional Semicolon</h1>
    <script>
        var number = 23;
        var Number = 45
        var NumBer = 67;
        document.write(number + "<br />");
        document.write(Number + "<br />")
        document.write(NumBer + "<br />")
    </script>
</body>
</html>


White Spaces and Line Breaks
The Javascript interpreter ignores tabs, spaces and new lines that appear in the program, except string and regular expression.

example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Line Breaks and White Space</title>
</head>
<body>
    <h1>JavaScript Line Breaks and White Space</h1>
    <script>
        var number = 23; var Number = 45; var NumBer = 67;
        document.write(number + "<br />");document.write(Number + "<br />");document.write(NumBer + "<br />");
    </script>
</body>
</html>


JavaScript Character Set and Case Sensitivity

Character Set
It is the set of characters reserved to write JavaScript program.In ASCII (American Standard Code of Information Interchange) character set, there were only 128 different characters.
Out of these 128 characters, 96 characters are available for use and the remaining 32 characters are reserved as controlled characters.

Special Characters

  • \t - represents a tab.
  • \f - represents a form feed, which is also referred as form feed.
  • \b - represents a backspace.
  • \n - represents a new line.
  • \r - represents a carriage return character, which is used to start a new line of text.
  • \" - represents a double quote.
  • \' - represents a single quote.
  • \\ - represents a back space.
example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Character Set</title>
</head>
<body>
    <h1>JavaScript Character Set</h1>
    <script>
        var number = 23;
        var Number = 45;
        var NumBer = 67;
        document.write("\t" + number + "<br />" );
        document.write("\\" + Number + "<br />");
        document.write("\'" + NumBer + "\'" );
    </script>
</body>
</html>



Case Sensitivity
JavaScript is a case-sensitive language, which means that the keywords, variable names, function names and every thing else should be typed with a consistent casing of letters.

<!DOCTYPE html>
<html>
<head>
    <title>javaScript Case Sensitivity</title>
</head>
<body>
    <h1>JavaScript Case Sensitivity</h1>
    <script>
        var number = 23;
        var Number = 45;
        var NumBer = 67;
        document.write(number + "<br />" );
        document.write(Number + "<br />");
        document.write(NumBer);
    </script>
</body>
</html>



Using JavaScript in HTML Document

We can insert JavaScript  code in html document using script element. The script element either contains scripting statement or reference to a external script file.

Attributes of the Script Element

  • async - specifies whether the script should be executed asynchronously or not.
  • type - specifies multipurpose internet mail extensions type of script.
  • charset - specifies the character encoding used in the script.
  • defer - specified whether the browser will continue parsing or not.
  • src - specifies the uniform resource locator of the file that contains the script.
Script element can be used in the web page in the following ways
  • In the Head element
  • In the Body element
  • In the external script file
JavaScript in the Head Element
We can place script inside the head element. Script present in the head element runs, when some action is performed such as click of the submit button.
Example

<!DOCTYPE html>
<html>
<head>
    <title>Script Inside Head element</title>
    <h1>Script Inside Head element</h1>
    <script >
        document.write("Welcome to the JavaScript");
    </script>
</head>
</html>



JavaScript in the Body Element
We can place script inside the body element. Script present in body element runs, when page starts loading in a web browser.
Example

<!DOCTYPE html>
<html>
<head>
    <title>Script Inside Body element</title>
</head>
<body>
    <h1>Script Inside Body element</h1>
    <script>
        document.write("Welcome to the JavaScript");
    </script>
</body>
</html>


JavaScript in the External file
We can place javaScript code in the external file if code is very lengthy, It affects the readability of the the html document. We can also reuse the javascript in several pages by including the external file.
Javascript file are saved with the extension .js.
Example
Create External.js file and put this code
document.write("Script In External File");

In HTML file
<!DOCTYPE html>
<html>
<head>
    <title>Script in External File</title>
    <script src="Externaljs.js"></script>
</head>
<body>
    <h1>Script Inside External File</h1>
</body>
</html>


HTML Output Element

Output Element
It is used to display the result of the calculation, which can be written using the JavaScript. There are three attributes form, name and for. The form attribute is used to specify the name of the form in which the output is displayed. The name attribute is used to specify the name of the current element and the for attribute is used to specify the name of the control in which the result is displayed.

Attributes of the output element

  • for- associates the output with a specific control. the value of this attribute must match the id attribute of its associated control.
  • form- refers to the id of a form.
  • name- specifies the name of the output element.
example 1

<!Doctype Html>
<html>
<head>
<title>output element</title>
<script type="text/javascript">
function subtract()
{
document.forms["form"]["resultsubtract"].value=123-23;
}
</script>
</head>
<body onload="subtract()">
<h1>Output element</h1>
<form name="form">
Subtracting the two numbers :
<output name="resultsubtract">
</output>
</form>
</body>
</html>

example 2

<!Doctype Html>
<html>
<head>
<title>output element</title>
<script type="text/javascript">
function subtract()
{
num1=parseInt(prompt("enter first number",0));
num2=parseInt(prompt("enter second number",0));
document.forms["form"]["resultsubtract"].value=num1-num2;
}
</script>
</head>
<body onload="subtract()">
<h1>Output element</h1>
<form name="form">
Subtracting the two numbers :
<output name="resultsubtract">
</output>
</form>
</body>
</html>