WD Unit 3
WD Unit 3
WD Unit 3
It does not provide security for data. It provides more security for data.
HTML, CSS and javascript are used. PHP, Python, Java, Ruby are used.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.
Example
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.
JavaScript allows you to work with three primitive data types −
• Numbers, eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as
named containers. You can place data into these containers and then refer to the data simply by
naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with
the var keyword as follows.
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money;
var name,age;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the
time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
double in super
3.4 Operators
Syntax:
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
The following example demonstrates how arithmetic operators perform different tasks on operands.
x + y; //returns 15
y - x; //returns 5
x * y; //returns 50
y / x; //returns 2
x % 2; //returns 1
x++; //returns 6
x--; //returns 4
+ operator performs concatenation operation when one of the operands is of string type.
The following example shows how + operator performs operation on operands of different data types.
Example: + operator
a + b; // "5Hello "
b + c; // "Hello World!"
Comparison Operators
JavaScript language includes operators that compare two operands and return Boolean value true or false.
Operators Description
> Checks whether left side value is greater than right side value. If yes then returns true otherwise
false.
< Checks whether left operand is less than right operand. If yes then returns true otherwise false.
>= Checks whether left operand is greater than or equal to right operand. If yes then returns true
otherwise false.
<= Checks whether left operand is less than or equal to right operand. If yes then returns true
otherwise false.
The following example demonstrates how comparison operators perform different tasks.
a == c; // returns true
a == x; // returns true
a != b; // returns true
Logical Operators
Logical operators are used to combine two or more conditions. JavaScript includes following logical
operators.
Operator Description
&& && is known as AND operator. It checks whether two operands are non-zero (0, false, undefined,
null or "" are considered as zero), if yes then returns 1 otherwise 0.
|| || is known as OR operator. It checks whether any one of the two operands is non-zero (0, false,
undefined, null or "" is considered as zero).
! ! is known as NOT operator. It reverses the boolean result of the operand (or condition)
var a = 5, b = 10;
Assignment Operators
JavaScript includes assignment operators to assign values to variables with less key strokes.
Assignment
operators Description
+= Sums up left and right operand values and assign the result to the left operand.
-= Subtract right operand value from left operand value and assign the result to the left
operand.
*= Multiply left and right operand values and assign the result to the left operand.
/= Divide left operand value by right operand value and assign the result to the left
operand.
%= Get the modulus of left operand divide by right operand and assign resulted modulus to
the left operand.
x = y; //x would be 10
x += 1; //x would be 6
x -= 1; //x would be 4
x *= 5; //x would be 25
x %= 2; //x would be 1
Ternary Operator
JavaScript includes special operator called ternary operator :? that assigns a value to a variable based on
some condition. This is like short form of if-else condition.
Syntax:
Ternary operator starts with conditional expression followed by ? operator. Second part ( after ? and before :
operator) will be executed if condition turns out to be true. If condition becomes false then third part (after :)
will be executed.
var a = 10, b = 5;
Points to Remember
1. JavaScript includes operators that perform some operation on single or multiple operands (data value) and
produce a result.
2. JavaScript includes various categories of operators: Arithmetic operators, Comparison operators, Logical
operators, Assignment operators, Conditional operators.
3. Ternary operator ?: is a conditional operator.
JavaScript has number of statements that control flow of the program. There are:
▪ conditionals (if-else, switch) that perform different actions depending on the value of an expression,
▪ loops (while, do-while, for, for-in, for-of), that execute other statements repetitively,
▪ jumps (break, continue, labeled statement) that cause a jump to another part of the program.
onditionals are control structures that perform different actions depending on the value of an
expression.
if-else
The if statement allows to make decision and to execute statement conditionally. If the condition
evaluates to true, statement is executed, otherwise it is not.
if (condition)
statement;
To conditionally execute more than one statement you should use curly braces like below:
if (condition) {
statement2;
It is considered good practice to always enclose code within braces even if only one statement is
to execute.Using an else clause allows to execute another statement if the condition is false:
if (condition) {
statement1;
} else {
statement2;
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
An example:
category = "middle";
Else
category = "heavy";
switch
The switch statement is similar to the if-else statement. If all of the branches depend on the
value of the same expression, the switch control structure can be used instead of the if-else.
switch (expression) {
case value1:
statement1;
[break;]
case value2:
statement2;
[break;]
default:
statement3;}
When the switch statement is executed, the program attempts to match the value of expression
to a case valel. If the value of expression is equal to a case value, the program executes the
associated statements. If matching is not found, the program looks for the optional default
clause. If it is found, associated statements are executed, if not the program skips all statements
within the switch statement.
An example:
switch (option) {
case 1:
type = "small";
break;
case 2:
type = "medium";
break;
case 3:
type = "large";
break;
default:
type = "other";
Loops in JavaScript
Iterative Method
Iterative method to do this is to write the document.write() statement 10 times.
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
document.write("Hello World\n");
< /script>
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown
below:
var I;
document.write("Hello World!\n");
< /script>
Many things may seem confusing to you in the above program at this point of time but do not worry
you will be able to understand everything about loops in JavaScript by the end of this tutorial. You can
observe that in the above program using loops we have used the document.write statement only once
but still, the output of the program will be same as that of the iterative program where we have used the
document.write statement 10 times.
• While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason
it is also called Entry control loop
• Once the condition is evaluated to true, the statements in the loop body are executed. Normally
the statements contain an update value for the variable being processed for the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life cycle.
var x = 1;
while (x <= 4)
// next iteration
x++;}
< /script>
Output:
Value of x:1
Value of x:2
Value of x:3
Value of x:4
2. for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Syntax:
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean
value. It is also an Entry Control Loop as the condition is checked prior to the execution of the
loop statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
Executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination:When the condition becomes false, the loop terminates marking the end of its
life cycle.
var x;
< /script>
Output:
Value of x:2
Value of x:3
Value of x:4
for…in loop
JavaScript also includes another version of for loop also known as the for..in Loops. The for..in
loop provides a simpler way to iterate through the properties of an object. This will be more clear
after leaning objects in JavaScript. But this loop is seen to be very useful while working with
objects.
Syntax:
for (variableName in Object)
{
statement(s)
}
In each iteration, one of the properties of Object is assigned to the variable
named variableName and this loop continues until all of the properties of the Object are processed.
Lets take an example to demonstrate how for..in loop can be used to simplify the work.
// creating an Object
fifth : "JavaScript" };
}< /script>
Output:
C
Java
Python
PHP
JavaScript
do while: do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
do while loop starts with the execution of the statement(s). There is no checking of any condition for
the first time.
After the execution of the statements, and update of the variable value, the condition is checked for true
or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.
var x = 21;
do
x++;
< /script>
Output:
Value of x: 21
Infinite loop
One of the most common mistakes while implementing any sort of looping is that that it may not ever
exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.
Examples:
for (var i = 5; i != 0; i -= 2)
document.write(i);
var x = 5;
// is not provided.
while (x == 5)
< /script>
e.g
<script>
var i;
if (i === 6)
break;
Document.write("Hello" + i + "<br>");
Output:
Hello1
Hello2
Hello3
Hello4
Hello5
Continue statement: The continue statement “jumps over” one iteration in the loop. It
breaks iteration in the loop and continues executing the next iteration in the loop.
<script>
var i;
if (i === 6)
continue;
Document.write("Hello" + i + "<br>");
</script>
Output:
Hello1
Hello3
Hello4
Hello5
Hello7
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given below:
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
The syntax of creating string object using new keyword is given below:
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Output:
Methods Description
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching a character
from the last position.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well
negative index.
split() It splits a string into substring array, then returns that newly created array.
trim() It trims the white space from the left and right side of the string.
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is
performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution.
This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
change onchange When the user modifies or changes the value of a form
element