You are on page 1of 83

JavaScript

Statements
Statements

• In JavaScript, statements are composed of - Values,


Operators, Expressions, Keywords, and Comments.
• The statements are executed, one by one, in the same
order as they are written.
• Each executable statement ends with a semicolon.
• Multiple statements, each separated with semicolon,
can be written on one line.
Conditional Statements
• Conditional statements are used to perform different
actions based on different conditions.

• Conditional statements in JavaScript are –


1. if statement
2. else statement
3. else if statement
4. switch statement
if Statement

• if statement is used to specify a block of code to be


executed, if a specified condition is true.

• Syntax –
if (condition)
{
// block of code
}
if Statement

var x = 10;
if (x == 10)
{
document.write(“x is equal to 10”);
}
else Statement

• else statement is used to specify a block of code to be


executed, if a specified condition is false.
• Syntax –
if (condition)
{ // block of code
} else
{ // block of code
}
else Statement
var x = 9;
if (x == 10)
{
document.write(“x is equal to 10”);
} else
{
document.write(“x is not equal to 10”);
}
else if Statement

• else if statement is used to specify a new condition


along with block of code to be executed.

• The block of code specified next to else if will be


executed if the first condition is false and the new
condition is true.
else if Statement
• Syntax –
if (condition1)
{ // block of code
} else if (condition 2)
{ // block of code
} else
{ // block of code
}
else if Statement
var x = 11;
if (x < 10)
{ document.write(“x is less than 10”); } else if (x == 10)
{ document.write(“x is equal to 10”);
} else
{ document.write(“x is greater than 10”);
}
switch Statement

• The switch statement is used to perform different


actions based on different conditions.

• It is used to specify many code blocks and to select


one of these code blocks to be executed.
switch Statement
Syntax –
switch (expression)
{ case a: //code
break;
case b: //code
break;
default: //code
}

}
switch Statement

• The switch expression is evaluated once and the value of the


expression is compared with the values of each case.

• If there is a match, the associated block of code is executed.

• If there is no match, the default code block is executed.


switch Statement
var a = 20;
switch (a)
{ case 10: document.write(“Number is 10”);
break;
case 20: document.write(“Number is 20”);
break;
default: document.write(“Neither 10 nor 20”);
}

}
Accepting User Input

• To accept input from the user, prompt() function is used.

• It displays prompt box that consists of textbox, Ok and Cancel


buttons.

• User can enter text in textbox and click on Ok button, which can
then be stored in a variable.
Accepting User Input

• E.g.,
var name = prompt(“What is your name?”);
// after this, user enters name
document.write(“Hello ” + name);
// message printed along with accepted name
Accepting User Input

• Input from prompt() function is of type string.

• In case, numeric value is required for calculation purpose,


datatype conversion is essential.

• To convert to integer, parseInt() function is used while to convert


to floating point number, parseFloat() function is used.
Accepting User Input

• E.g.,
var num = parseInt(prompt(“Enter a Number”));
// entered number is converted to integer
var ans = num * 2;
document.write(“Answer is ” + ans);
Loop Statements
• Loop statements are used to execute a block of code a number of times.
• Loop statements in JavaScript are –
1. while
2. do-while
3. for
4. for-in
5. for-of
While Loop
• The while loop statement loops through a block of code as long as a specified
condition is true.

• Syntax –
while (condition)
{
//code of block
}
While Loop
• Example –
var x = 1;
while (x < 10)
{ document.write(x);
x = x + 1;
}
It displays numbers from 1 to 9.
Do While Loop

• The do while loop statement is a special kind of while


loop statement, which executes the code block once
before checking for the condition, then it repeats the
loop as long as a specified condition is true.

• Syntax –
do { //code of block
} while (condition)
Do While Loop
• Example –
var x = 10;
do
{
document.write(x);
} while (x < 10)
It displays number 10
For Loop

• For loop statement creates a loop with 3 optional statements.

• Syntax -
for (expression1; expression2; expression3)
{
// block of code
}
For Loop

• Expression 1 is executed only once before the execution of the


code block.

• Expression 2 defines the condition for executing the code


block.

• Expression 3 is executed every time after the code block has


been executed.
For Loop

• Example –
for (var x = 1; x <= 5; x++)
{
document.write(x);
document.write(“<br>”);
}
It displays numbers from 1 to 5 on separate line.
For Loop

• There can be many initialization statements in expression


1, separated by comma.

• Similarly, there can be many increment and/or decrement


statements in expression 3, separated by comma.

• E.g., for (var x = 1, y = 10; x <= 5; x++, y--) {…}


Break Statement

• Break statement is used to jump out of a loop.

• It can be used to specify the only condition or


additional condition when the loop should stop
execution.

• It can be used with all types of loop statements.


Break Statement
• Example –
for (var x = 1; ; x++)
{
document.write(x);
if (x == 5)
{ break; }
}
It displays numbers from 1 to 5.
Break Statement
• Example –
for (var x = 1; x < 50; x++)
{
document.write(x);
if (x == 10)
{ break; }
}
It displays numbers from 1 to 10.
Continue Statement

• Continue statement is used to break one iteration of the


loop and continue with the next iteration in the loop.

• The loop continues the next iteration when the


specified condition is true.

• It can be used with all types of loop statements.


Continue Statement
• Example –
for (var x = 1; x <=10; x++)
{
if (x == 5)
{ continue; }
document.write(x);
}
It displays numbers from 1 to 10, except value 5.
For in Loop
• For in loop statement loops through the properties of an Object.

• It can also loop over the properties of an Array.

• Syntax –
for (key in object) { //code of block }
for (variable in array) { //code of block }
For of Loop
• For of loop statement loops through the values of an iterable object.

• It loops over iterable data structures such as Arrays, Strings etc.

• Syntax –
for (variable of iterable) { //code of block }
Functions

• Function is a block of code designed to perform a particular task.

• Function is executed when it is called (invoked).

• It is defined with the function keyword, followed by a name,


followed by parentheses.
Functions

• Function names can contain letters, digits, underscores, and dollar


signs.

• The parenthesis may include parameter names separated by commas.

• The code to be executed by the function is placed inside the curly


brackets {} after parentheses.
Functions

• Syntax –
function name(para1, para2,..)
{
//code
}
Function Invocation

• The code inside the function is executed when the function is


called or invoked.

• Function can be invoked –


1. Automatically (self invocation)
2. Through JavaScript code
3. When an event occurs, e.g., on button click
Function Invocation
function display()
{ document.write(“Good Morning”);
}
display(); //function invoked here
OR
<input type = “button”
onclick = display();
value = “Click to call Function”>
Function Return

• A return statement inside the function block, stops execution of


the function.

• A return statement can also be used to compute a return value.

• The return value is returned to the invoking statement or code,


i.e., the point from where function is called.
Function Return
function sum(a, b)
{
var c = a + b;
return c;
}
var ans = sum(10,15);
document.write(“Answer is : ” + ans);
Function Return

function sum(a, b)
{
return a + b;
}
var ans = sum(10,15);
document.write(“Answer is : ” + ans);
Variable Scope

• Variables declared within a function have local scope, i.e.,


variables become local to that function.

• Local variables can only be accessed from within the


function.

• Local variables are created when a function starts, and


deleted when the function is completed.
Variable Scope

• Variables declared outside a function have global


scope, i.e., variables become global variable.

• Global variables can be accessed from within the


function and also outside the function.
Arrays

• Array is a special kind of variable. It can hold more than one


value.

• Multiple values are separated with comma and embedded in


square bracket [].

• Syntax –
var array_name = [value1, value2, …];
Arrays
• Example –
var colours = [“yellow”, “blue”, “green”];
OR
var colours = [
“yellow”,
“red”,
“blue”
];
Arrays

• The keyword ‘new’ can be used to create an array and


assign values to it.

• E.g.,
var colours = new Array(“yellow”, “green”,
“blue”);
Arrays

• The keyword ‘new’ does not create expected array with


one element with numeric value.

• E.g.,
var num = [20]; //creates array with one element
var num = new Array(20);
//creates an array with 20 undefined elements
Recognizing an Array

• The ‘typeof’ operator when used with an array returns the


value as “object”, because an array is an object.

• Instead of ‘typeof’ operator, isArray() method of an array is


used.

• E.g., var colours = [“yellow”, “blue”, “green”];


document.write(Array.isArray(colours)); //prints true
Accessing Array Elements

• Array elements can be accessed by referring to the


index number.

• Array indexes start with 0, i.e., first element has index


[0], second element has index [1] and so on.

• E.g. var colours = [“yellow”, “blue”, “green”];


document.write(colours[0]); // will print ‘yellow’
Array Creation

• In another way, array can be created first and then, elements


are added to an array.
var colours = [ ];
colours[0] = “yellow”;
colours[1] = “red”;
colours[2] = “blue”;
Changing Array Element

• Value of an array element can be changed by


accessing that element and assigning the new value.

• E.g. In the array ‘colours’ as defined below –


var colours = [“yellow”, “blue”, “green”];
To change value “blue” to “red”, use below statement
-
colours[1] = “red”;
Accessing Full Array

• The full array can be accessed by referring to the name


of the array.

• E.g. To access and print the array ‘colours’ –


var colours = [“yellow”, “blue”, “green”];
document.write(colours);
Length Property

• The length property of an array returns the length of


an array, i.e., number of elements in an array.

• E.g.,
var colours = [“yellow”, “blue”, “green”];
var length = colours.length;
document.write(length); // will print 3
Accessing Last Element

• The last element of an array can be accessed by using


the length property of an array.

• Example –
var colours = [“yellow”, “blue”, “green”, “red”];
var colour = colours[colours.length – 1];
document.write(colour); // will print red
Looping Array Elements
• For loop can be used to loop through an array.

• Example –
var colours = [“yellow”, “blue”, “green”, “red”];
var len = colours.length;
for (var i=0; i < len; i++)
{ document.write(colours[i]);
}
Looping Array Elements

• To loop through an array, forEach() function can be


used.

• The forEach() function calls a function for each


element of an array.

• The forEach() function is not executed for empty


elements.
Looping Array Elements

• Example –
var colours = [“yellow”, “blue”, “green”, “red”];
colours.forEach(arrFunction);
function arrFunction(element)
{ document.write(element + “<br>”);
}
Array Methods

push() join()
pop() splice()
shift() slice()
unshift() sort()
concat() reverse()
toString()
Push()

• The push() method is used to add a new element or


elements to an array at the end.

• Example –
var colours = [“yellow”, “blue”];
colours.push(“green”);
document.write(colours);
// will display three elements
Push()
• The push() method returns the length of new array.

• Example –
var colours = [“yellow”, “blue”];
var length = colours.push(“green”);
document.write(length); // will display 3
document.write(colours);
// will display three elements
Pop()
• The pop() method is used to remove the last element from an
array.

• Example –
var colours = [“yellow”, “blue”, “green”];
document.write(colours); // display three elements
colours.pop();
document.write(colours); // display yellow, blue
Pop()

• The pop() method returns the value that was popped out,
i.e., removed from an array.

• Example –
var colours = [“yellow”, “blue”, “green”];
var colour = colours.pop();
document.write(colour); // display green
shift()
• The shift() method is used to remove the first element
from an array and shift other elements to lower index.

• Example –
var colours = [“yellow”, “blue”, “green”];
colours.shift();
document.write(colours); // display blue, green
shift()
• The shift() method is used to return the value that has
been removed, i.e., the first element from an array.

• Example –
var colours = [“yellow”, “blue”, “green”];
var colour = colours.shift();
document.write(colour); // display yellow
unshift()
• The unshift() method is used to add the new element or
elements to an array at the beginning and shift older elements.

• Example –
var colours = [“yellow”, “blue”, “green”];
colours.unshift(“red”);
document.write(colours);
// display red, yellow, blue, green
unshift()
• The unshift() method returns the length of new array.

• Example –
var colours = [“yellow”, “blue”];
var length = colours.unshift(“green”);
document.write(length); // will display 3
document.write(colours);
// will display three elements
concat()
• The concat() method is used to create a new array by merging
existing arrays.
• Example –
var col1 = [“yellow”, “blue”, “green”];
var col2 = [“orange”, “black”];
colours = col1.concat(col2);
document.write(colours);
// display yellow, blue, green, orange, black
concat()
• The concat() method can take any number of array arguments.
• Example – var col1 = [“yellow”, “blue”, “green”];
var col2 = [“orange”, “black”];
var col3 = [“white”, “brown”];
colours = col1.concat(col2, col3);
document.write(colours);
// display yellow, blue, green, orange, black, white, brown
toString()

• The toString() method is used to convert an array to a


string of array values.

• Example –
var colours = [“yellow”, “blue”, “green”];
document.write(colours.toString());
// display yellow, blue, green
join()
• The join() method is used to join all array elements into a
string. It is similar to toString() method, but in addition, we
can specify the separator.

• Example –
var colours = [“yellow”, “blue”, “green”];
document.write(colours.join(“*”));
// display yellow * blue * green
splice()
• The splice() method is used to add new element/s to an
array at specified position and return new array .

• Syntax –
array.splice(position, count, newElement1,…)
- position defines the position from where new
elements to be added
- count defines the number of elements to be removed
splice()
• Example –
var colours = [“yellow”, “blue”, “green”];
document.write(“Original array: ” + colours);
colours.splice(2, 0, “brown”, “red”);
document.write((“Modified array: ” + colours);
// Output is –
yellow, blue, brown, red, green
splice()
• The splice() method is also used to remove elements of an
array without leaving gap in the array.

• Example –
var colours = [“yellow”, “blue”, “green”, “red”];
colours.splice(1, 1);
document.write((“Modified array: ” + colours);
// Output is – Modified array: yellow, green, red
slice()
• The slice() method is used to slice out a piece of an array into a
new array. It does not remove any element from the source array.

• Syntax –
array.slice(start, end)
- start and end defines the position in the source array to create
new array, from where to start and where to end respectively
slice()
• Example – with only start value
var colours = [“yellow”, “blue”, “green”];
document.write((“Source array: ” + colours);
var newColour = colours.slice(1);
document.write((“New array: ” + newColour);
// Output is – New array: blue, green
slice()
• Example – with start and end value
var colours = [“yellow”, “blue”, “green”, “red”];
document.write((“Source array: ” + colours);
var newColour = colours.slice(1,3);
document.write((“New array: ” + newColour);
// Output is – New array: blue, green
sort()

• The sort() method is used to sort an array


alphabetically.

• Syntax –
array.sort()
sort()

• Example –
var colours = [“yellow”, “blue”, “green”, “red”];
document.write((“Source array: ” + colours);
colours.sort();
document.write((“Sorted array: ” + colours);
// Sorted array: blue, green, red, yellow
reverse()

• The reverse() method is used to reverse the elements in an


array.

• It can be used along with sort() method to sort an array in


descending order.

• Syntax –
array.reverse()
reverse()

• Example –
var colours = [“yellow”, “blue”, “green”, “red”];
document.write((“Source array: ” + colours);
colours.sort();
colours.reverse();
document.write((“Sorted reverse array: ” + colours);
// Sorted reverse array: yellow, red, green, blue
Multi-dimensional Array
• In multi-dimensional array, one array is an element of
another array.

• e.g., arr1 = [[1, 2, 3], [4, 5], 6, 7, 8];


Here, 1st and 2nd element of array ‘arr1’ are arrays
while remaining elements are numbers.

• To access elements of inner arrays, two dimensions are


required like arr1[0][0]
Multi-dimensional Array
• In other way, already defined array can be a part of
another array.

• e.g., arr1 = [1, 2, 3, 4]; arr2 = [arr1, “a”, “b”];

• Elements of arr1 can be accessed through arr2 using


two dimensions as -
document.write(arr2[0][1]); //prints 2

You might also like