0% found this document useful (0 votes)
4 views

Copy of 4. JavaScript - VIT Intership

The document provides an introduction to procedural programming, detailing its principles, historical languages, and the distinction from other programming paradigms. It also covers HTML, CSS, and JavaScript, explaining their roles in web development, including examples of JavaScript usage, variables, data types, and operators. Additionally, it discusses JavaScript comments and the importance of understanding both primitive and non-primitive data types.

Uploaded by

Piyush Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Copy of 4. JavaScript - VIT Intership

The document provides an introduction to procedural programming, detailing its principles, historical languages, and the distinction from other programming paradigms. It also covers HTML, CSS, and JavaScript, explaining their roles in web development, including examples of JavaScript usage, variables, data types, and operators. Additionally, it discusses JavaScript comments and the importance of understanding both primitive and non-primitive data types.

Uploaded by

Piyush Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 173

Welcome

Introduction to Procedural Programming

Procedural programming is derived from imperative programming.


Its concept is based on procedure calls. Procedures are nothing but a series of computational
steps to be carried out.
In Procedural programming, the execution of the instructions takes place step by step.
When you use Procedural language, you give instructions directly to your computer and tell it
how to reach its goal through processes.
Procedural programming focuses on the process rather than data (Object-oriented
Programming) and function (Functional Programming).
The first major procedural programming languages around 1957-1964 were FORTRAN, ALGOL,
COBOL, PL/I and BASIC. The procedural Programming paradigm is one of the first paradigms to
emerge in the computational world.
Welcome
Types of Procedural Languages

FORTRAN(Formula Translation Language)


ALGOL(Algorithmic Language)
COBOL(Common Business Oriented Language)
BASIC(Beginner’s All Purpose Symbolic Instruction Code)
PASCAL
C
Welcome
HTML,CSS and Javascript

HTML:
HTML is at the core of every web page, regardless the complexity of a site or number of
technologies involved. It's an essential skill for any web professional.
It's the starting point for anyone learning how to create content for the web. And, luckily for us,
it's surprisingly easy to learn.
Once a tag has been opened, all of the content that follows is assumed to be part of that tag
until you "close" the tag.
When the paragraph ends, I'd put a closing paragraph tag: </p>. Notice that closing tags look
exactly the same as opening tags, except there is a forward slash after the left angle bracket.
Here's an example: <p>This is a paragraph.</p>
Using HTML, you can add headings, format paragraphs, control line breaks, make lists,
emphasize text, create special characters, insert images, create links, build tables, control some
styling, and much more.
Welcome
HTML,CSS and Javascript

CSS
CSS stands for Cascading Style Sheets.
This programming language dictates how the HTML elements of a website should actually
appear on the frontend of the page.
If HTML is the drywall, CSS is the paint.
Javascript
JavaScript is a more complicated language than HTML or CSS, and it wasn't released in beta
form until 1995. Nowadays, JavaScript is supported by all modern web browsers and is used on
almost every site on the web for more powerful and complex functionality.
In short, JavaScript is a programming language that lets web developers design interactive
sites. Most of the dynamic behavior you'll see on a web page is thanks to JavaScript, which
augments a browser's default controls and behaviors.
Welcome
Javascript in Body

<!DOCTYPE html>
<html>
<body>
<h2>Use Javascript in the Body</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick="document.getElementById('demo').innerHTML =
'Hello JavaScript!'">Click Me!</button>
</body>
</html>
Welcome
Javascript - External

<!DOCTYPE html>
<html>
<head>
<script src = “sample.js”>
</script>
</head>
<body>
<h2>Use Javascript in the Body</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick=”ethnus()”>Click Me!</button>
</body>
</html>

sample.js
function ethnus() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
Welcome
Javascript Versions

Till date, ES has published nine versions and the latest one (9th version) was published in the year
2018.

1. ES1 1997 6. ES2 1998


2. ES3 1999 7. ES4 Abandoned
3. ES5 2009 8. ES6 2015
4. ES7 2016 9. ES8 2017
5. ES9 2018

ECMA Script's first three versions- ES1, ES2, ES3 were yearly updates whereas, ES4 was never
released due to political disagreements. After a decade, ES5 was eventually released with several
additions
Welcome
Javascript Output Methods

JavaScript can "display" data in different ways:

Writing into an HTML element, using innerHTML.


Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Welcome
Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Welcome
Using document.write()

<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>
Welcome
Using window.alert()

<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
Welcome
Using console.log()

<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>
Welcome
Welcome
Javascript Variables

A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).

• Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.

• After first letter we can use digits (0 to 9), for example value1.

• JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables


var x = 10;
var _value="sonoo";
Incorrect JavaScript variables
var 123=30;
var *aa=320;
Welcome
Example

<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Welcome
Local Variable

A JavaScript local variable is declared inside block or function. It is accessible within the function
or block only. For example:

<script>
function abc(){
var x=10;//local variable
}
</script>
Welcome
Global Variable

A JavaScript global variable is accessible from any function.


A variable i.e. declared outside the function or declared with window object is known as global
variable.
Example:
<html>
<body>
<script>
var data=200;//global variable
function a()
{ document.writeln(data); }
function b()
{ document.writeln(data); }
a();//calling JavaScript function
b();
</script> </body> </html>
Welcome
Javascript Comments

The JavaScript comments are meaningful way to deliver message.


It is used to add information about the code, warnings or suggestions so that end user can
easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

Advantages of Javascript Comments


To make code easy to understand :It can be used to elaborate the code so that end user can
easily understand the code.
To avoid the unnecessary code :It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may be need to
disable the code. In such case, it is better to use comments.
Welcome
Types of Javascript Comments

There are two types of comments in JavaScript:


Single-line Comment
Multi-line Comment

Javascript Single-line Comment


It is represented by double forward slashes (//). It can be used before and after the statement.
Let’s see the example of single-line comment i.e. added before the statement.

<script>
// It is single line comment
document.write("hello javascript");
</script>
Welcome
Types of Javascript Comments

JavaScript Multi line Comment:

It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash.
For example: /* your code here */

Example:
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
Welcome
Javascript Datatypes

JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.

Primitive data type


Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the data
type. It can hold any type of values such as numbers, strings etc. For example:

var a=40;//holding number


var b="Rahul";//holding string
Welcome
Javascript Primitive Datatypes

There are five types of primitive data types in JavaScript. They are as follows:

Datatype Description
String Represents sequence of characters.Eg:”Hello”
Number Represents numeric value.Eg:100
Boolean Represents Boolean value either “true” or “false”
Undefined Represents undefined value
Null Represents null.
Welcome
Javascript Non-Primitive Datatypes

Datatype Description

Object Represents instance through which we can access members.


Array Represents group of similar values.
RegExp Represents a regular expression.
Welcome
Welcome
Arithmetic Operators

Following are the list of arithmetic operators:


• +(Addition):Used to add two operands.

• -(Subtraction):Used to subtract two operands

• *(Multiplication):Used to multiply two operands

• /(Division):Used to find the quotient

• %(Modulus):Used to find the remainder.

• ++(Increment):Used to perform increment operation

• --(Decrement):Used to perform decrement operation.


Welcome
Example

<html> document.write("a % b = ");


<body> result = a % b;
<script type = "text/javascript"> document.write(result);
<!-- var a = 33; document.write(linebreak);
var b = 10; a = ++a;
var c = "Test"; document.write("++a = ");
var linebreak = "<br />"; result = ++a;
document.write("a + b = "); document.write(result);
result = a + b; document.write(linebreak);
document.write(result); b = --b;
document.write(linebreak); document.write("--b = ");
document.write("a - b = "); result = --b;
result = a - b; document.write(result);
document.write(result); document.write(linebreak); //-->
document.write(linebreak); </script>
document.write("a / b = "); Set the variables to different
result = a / b; values and then try...
document.write(result); </body>
document.write(linebreak); </html>
Welcome
Comparison Operators

Following are the list of comparison/relational operators:


>(greater than)
<(less than)
==(equals)
>=(greater than or equals)
<=(less than or equals)
!=(not equals)
Welcome
Example

<html> document.write("(a != b) => ");


<body> result = (a != b);
<script type = "text/javascript"> document.write(result);
<!-- var a = 10; document.write(linebreak);
var b = 20; document.write("(a >= b) => ");
var linebreak = "<br />"; result = (a >= b);
document.write("(a == b) => "); document.write(result);
result = (a == b); document.write(linebreak);
document.write(result); document.write("(a <= b) => ");
document.write(linebreak); result = (a <= b);
document.write("(a < b) => "); document.write(result);
result = (a < b); document.write(linebreak); //-->
document.write(result); </script>
document.write(linebreak); Set the variables to different
document.write("(a > b) => "); values and different operators and then
result = (a > b); try...
document.write(result); </body>
document.write(linebreak); </html>
Welcome
Logical Operators

Javascript supports the following logical operators:-


&&(Logical AND):When both the operands are true ,it returns true
||(Logical OR):Even if one of the operands are true,it returns true
!(Logical NOT):True becomes false,false becomes true.
Welcome
Example

<html> document.write("!(a && b) => ");


<body> result = (!(a && b));
<script type = "text/javascript"> document.write(result);
<!-- document.write(linebreak);
var a = true; //-->
var b = false; </script>
var linebreak = "<br />";
<p>Set the variables to
document.write("(a && b) => "); different values and different
result = (a && b); operators and then try...</p>
document.write(result); </body>
document.write(linebreak); </html>
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
Welcome
Bitwise Operators

The following are the list of bitwise operators:


&(Bitwise AND)
|(Bitwise OR)
^(Bitwise XOR)
~(1’s complement)
>>(Shift right)
<<(Shift left)
Welcome
Example

<html> document.write(d);
<body> <script> document.write(linebreak);
<!-- var a = 10; // Bit presentation 10 document.write(b>>2);
var b = 0b1010; // binary number document.write(linebreak);
var c = 030;// Octal document.write(b<<2);
var d = 0xfff;// hexa document.write(linebreak);
var linebreak = "<br />"; document.write(~b);
document.write(a); document.write(linebreak);
document.write(linebreak); (Negation sign + 1 will be added)
document.write(b); //--> </script>
document.write(linebreak); <p>Set the variables to different
document.write(c); values and different operators and
document.write(linebreak); then try...</p> </body> </html>
Welcome
Assignment Operators

The different forms of assignment operators are:


+=(Addition assignment)
-=(Subtraction assignment)
*=(Multiplication assignment)
/=(Division assignment)
%=(Modulus assignment)
Welcome
Example

document.write("Value of a => (a = b) =>


<!DOCTYPE html> ");
<head><title></title></head> a = b;
<body> document.write(a);
<script> document.write(linebreak);
var a = 33;
var b = 10; document.write("Value of a=>(a += b) =>
var linebreak = "<br />"; ");
document.write("Value of a => (a += b) => ");a *= b;
a += b; document.write(a);
document.write(a); document.write(linebreak);
document.write(linebreak); </script>
document.write("Value of a => (a -= b) => ");</body>
a -= b; </html>
document.write(a);
document.write(linebreak);
Welcome
Conditional Operator

The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.

? : (Conditional ):If Condition is true? Then value X : Otherwise value Y


Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!-- var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak); //-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body> </html>
Welcome
Control Statements

Control Statements are those which can be used to control the sequence of execution of the
program.Different categories of control statements are:
Branching Statements:if
Looping Statements:for,while,do-while
Execution Termination Statements:break,continue
Welcome
If statement

The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.

Syntax:
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated.
If the resulting value is true, the given statement(s) are executed.
If the expression is false, then no statement would be not executed.
Most of the times, you will use comparison operators while making decisions.
Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!-- var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body> </html>
Welcome
If..Else statement

The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.

Syntax:
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated.
If the resulting value is true, the given statement(s) in the ‘if’ block, are executed.
If the expression is false, then the given statement(s) in the else block are executed.
Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Welcome
If..else…if statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.

Syntax:
The syntax of an if-else-if statement is as follows −

if (expression 1) { Statement(s) to be executed if expression 1 is true }


else if (expression 2) { Statement(s) to be executed if expression 2 is
true }
else if (expression 3) { Statement(s) to be executed if expression 3 is
true }
else { Statement(s) to be executed if no expression is true }
Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Welcome
Switch Statement

Syntax:
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case
against the value of the expression until a match is found. If nothing matches, a default condition
will be used.

switch (expression) {
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...

case condition n: statement(s)


break;

default: statement(s)
}
Welcome
Example

<body>
<script type = "text/javascript">
<!-- var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />"); break;

case 'B': document.write("Pretty good<br />"); break;

case 'C': document.write("Passed<br />"); break;

case 'D': document.write("Not so good<br />"); break;

default: document.write("Unknown grade<br />")


}
document.write("Exiting switch block"); //-->
</script> </body>
Welcome
Looping Statements

Process of repeatedly executing set of statements is called Looping.There are 3 kinds of looping
statements:
✔ for

✔ while

✔ for-in

for
Syntax:
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Welcome
While Loop

Syntax:

while (expression) {
Statement(s) to be executed if expression is true
}

The while loop executes set of statements as long as the condition is true.
Welcome
Example

<html>
<body>

<script type = "text/javascript">


<!--
var count = 0;
document.write("Starting Loop ");

while (count < 10) {


document.write("Current Count : " + count + "<br />");
count++;
}

document.write("Loop stopped!"); //-->


</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Welcome
For-In Loop

The for-in loop is used to loop through an object properties.

Syntax:
The syntax of ‘for..in’ loop is −

for (variablename in object) {


statement or block to execute
}

In each iteration, one property from object is assigned to variablename and this loop continues till
all the properties of the object are exhausted.
Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>
Welcome
Loop Control Statements

There may be a situation when you need to come out of a loop without reaching its bottom.
There may also be a situation when you want to skip a part of your code block and start the
next iteration of the loop.

To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.
Welcome
Break Statement

Used to terminate the execution.

Example:
<body>
<script type = "text/javascript">
<!-- var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20) {


if (x == 5) { break; } // breaks out of loop completely
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> "); //-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
Welcome
Continue Statement

The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block.
When a continue statement is encountered, the program flow moves to the loop check
expression immediately and if the condition remains true, then it starts the next iteration,
otherwise the control comes out of the loop.
Welcome
Example

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10) {


x = x + 1;
if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body></html>
Welcome
Welcome
Javascript Array

JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
ByWelcome
Array Literal

The syntax of creating array using array literal is given below:


var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).

Example:
<html>
<body>
<script>
//single dimension array (1 for loop for iteration)
var stu =[10,11,12,13,14,15]; //array literal
for (i=0; i<stu.length; i++){
document.write(stu[i] + "<br/>");
}
</script> </body> </html>
Welcome
Array Directly(By using new keyword)

The syntax of creating array directly is given below:


var arrayname=new Array();
Here, new keyword is used to create instance of array.

Example:
<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script> </body> </html>
Welcome
Array Constructor

Here, you need to create instance of array by passing arguments in constructor so that we don't
have to provide value explicitly.

Example:
<html>
<body>
<script>
//By using array constructor
var cus=new Array(2.3, 4.4,3.5,5.6);
for (k=0;k<cus.length;k++) {
document.write(cus[k] + "<br>");
}
</script>
</body>
</html>
Welcome
Array Methods

1) concat() method:
The JavaScript array concat() method combines two or more arrays and returns a new array.
This method doesn't make any change in the original array.

Syntax:
The concat() method is represented by the following syntax:

array.concat(arr1,arr2,....,arrn)
Welcome
Example

<html>
<body>

<script>
var arr1=[1,2,3,4,5];
var arr2=[10,11,12,13];
var result= arr1.concat(arr2);
document.writeln(result);
</script>

</body>
</html>
Welcome
Every() Method

The JavaScript array every() method checks whether all the given elements in an array are
satisfying the provided condition. It returns true when each given array element satisfying the
condition otherwise false.
Syntax:
The every() method is represented by the following syntax:
array.every(callback(currentvalue,index,arr),thisArg)
Parameter:
• callback - It represents the function that test the condition.

• currentvalue - The current element of array.

• index - It is optional. The index of current element.

• arr - It is optional. The array on which every() operated.

• thisArg - It is optional. The value to use as this while executing callback.


Welcome
Example

<html>
<body>

<script>
var marks=[50,40,45,37,20];

function check(value)
{
return value>30; //return false, as marks[4]=20
}

document.writeln(marks.every(check));
</script>

</body>
</html>
Welcome
Filter Method

The JavaScript array filter() method filter and extract the element of an array that satisfying the
provided condition. It doesn't change the original array.
Syntax:
The filter() method is represented by the following syntax:
array.filter(callback(currentvalue,index,arr),thisArg)
Parameter:
• callback - It represents the function that test the condition.

• currentvalue - The current element of array.

• index - It is optional. The index of current element.

• arr - It is optional. The array on which filter() operated.

• thisArg - It is optional. The value to use as this while executing callback.

Return:
• A new array containing the filtered elements.
Welcome
Example

<html>
<body>
<script>
var marks=[50,40,45,37,20];
function check(value)
{
return value>30;
}
document.writeln(marks.filter(check));
</script>
</body>
</html>
Welcome
Find()

The JavaScript array find() method returns the first element of the given array that satisfies the
provided function condition.
Syntax:
The find() method is represented by the following syntax:
array.find(callback(value,index,arr),thisArg)
Parameter
• callback - It represents the function that executes each element.

• value - The current element of an array.

• index - It is optional. The index of current element.

• arr - It is optional. The array on which find() operated.

• thisArg - It is optional. The value to use as this while executing callback.

Return
• The value of first element of the array that satisfies the function condition.
Welcome
Example

<html>
<body>
<script>
var arr=[5,22,19,25,34];
var result=arr.find(x=>x>20);
document.writeln(result)
</script>
</body>
</html>
Welcome
findIndex()

The JavaScript array findIndex() method returns the index of first element of the given array that
satisfies the provided function condition. It returns -1, if no element satisfies the condition.
Syntax:
The findIndex() method is represented by the following syntax:
array.findIndex(callback(value,index,arr),thisArg)
Parameters:
• callback - It represents the function that executes each element.

• value - The current element of an array.

• index - It is optional. The index of current element.

• arr - It is optional. The array on which findIndex() method operated.

• thisArg - It is optional. The value to use as this while executing callback.

Return:
• Index of the first element of the array
Welcome
Example

<html>
<body>

<script>
var arr=[5,22,19,25,34];
var result=arr.findIndex(x=>x>20);
document.writeln(result);
</script>

</body>
</html>
Welcome
forEach()

The JavaScript array forEach() method is used to invoke the specified function once for each array
element.
Syntax
The forEach() method is represented by the following syntax:
array.forEach(callback(currentvalue,index,arr),thisArg)
Parameter
• callback - It represents the function that test the condition.

• currentvalue - The current element of array.

• index - It is optional. The index of current element.

• arr - It is optional. The array on which forEach() operated.

• thisArg - It is optional. The value to use as this while executing callback.

Return: undefined
Welcome
Example

<html>
<body>

<script>
var arr = ['C', 'C++', 'Python'];

arr.forEach(function(fetch) {
document.writeln(fetch);
});
</script>

</body>
</html>
Welcome
indexOf() method

The JavaScript array indexOf() method is used to search the position of a particular element in a
given array. This method is case-sensitive.
The index position of first element in an array is always start with zero. If an element is not present
in an array, it returns -1.

Syntax:
The indexOf() method is represented by the following syntax:
array.indexOf(element,index)

Parameter:
• element - It represent the element to be searched.

• index - It represent the index position from where search starts. It is optional.
Welcome
Example

<!DOCTYPE html>
<html>
<body>

<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
document.writeln(result);
</script>

</body>
</html>
Welcome
lastIndexOf() method

The JavaScript array lastIndexOf() method is used to search the position of a particular element in
a given array. It behaves similar to indexOf() method with a difference that it start searching an
element from the last position of an array.

The lastIndexOf() method is case-sensitive. The index position of first character in a string is
always start with zero. If an element is not present in a string, it returns -1.

Syntax:
The lastIndexOf() method is represented by the following syntax:
array.lastIndexOf(element,index)

Parameter:
• element - It represent the element to be searched.
• index - It represent the index position from where search starts. It is optional.

Return:An index of a particular element.


Welcome
Example

<html>
<body>
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.lastIndexOf("C++");
document.writeln(result);
</script>
</body>
</html>
Welcome
map() method

The JavaScript array map() method calls the specified function for every array element and returns
the new array. This method doesn't change the original array.

Syntax:
The map() method is represented by the following syntax:
array.map(callback(currentvalue,index,arr),thisArg)

Parameter:
• callback - It represents the function that produces the new array.
• currentvalue - The current element of array.
• index - It is optional. The index of current element.
• arr - It is optional. The array on which map() method operated.
• thisArg - It is optional. The value to use as this while executing callback.

Return:
A new array whose each element generate from the result of a callback function.
Welcome
Example

<html>
<body>

<script>
var arr=[2.1,3.5,4.7];
var result=arr.map(Math.round);
document.writeln(result);
</script>

</body>
</html>
Welcome
pop() Method

The JavaScript array pop() method removes the last element from the given array and return that
element. This method changes the length of the original array.

Syntax:
The pop() method is represented by the following syntax:

array.pop()

Return:
The last element of given array.
Welcome
Example

<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
</script>
</body>
</html>
Welcome
Push()

The JavaScript array push() method adds one or more elements to the end of the given array. This
method changes the length of the original array.

Syntax:
The push() method is represented by the following syntax:
array.push(element1,element2....elementn)

Parameter:
element1,element2....elementn - The elements to be added.

Return:
The original array with added elements.
Welcome
Example

<html>
<body>
<script>
var arr=["AngularJS","Node.js"];
arr.push("JQuery");
document.writeln(arr);
</script>
</body>
</html>
Welcome
Some() Method

The some() methods perform testing and checks if atleast a single array element passes the test,
implemented by the provided function. If the test is passed, it returns true. Else, returns false.

Syntax:
array.some(callback_funct(element, index, array), thisArg);

Parameter:

• callback_funct: It is the function that tests each element present in the array. It undertakes the
following three arguments:
• element: It is the current element, being in process.
• index: Although it is optional, it is the index value of the current element in process.
• arr: It is the given array on which some() method performs the test.
• thisArg: It is an optional parameter, used as 'this' value while executing the callback function. If
we do not provide, 'undefined' will be used as 'this' value.

Return:
It returns a boolean value. If it founds an element returning true value to the callback function, it
returns true. Otherwise, false.
Welcome
Example

<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr=[12,81,23,34];
function test(arr)
{ return(arr>80); } // test() will return a true value.
var res=arr.some(test);
document.write("Its "+res);
</script>
</body>
</html>
Welcome
Shift()

The JavaScript array shift() method removes the first element of the given array and returns that
element. This method changes the length of the original array.

Syntax:
The shift() method is represented by the following syntax:

array. shift()

Return:
The first element of an array.
Welcome
Example

<html>
<body>

<script>
var arr=["AngularJS","Node.js","JQuery"];
var result=arr.shift();
document.writeln(result);
</script>
</body>
</html>
Welcome
Slice()

The JavaScript array slice() method extracts the part of the given array and returns it. This method
doesn't change the original array.

Syntax:
The slice() method is represented by the following syntax:
array.slice(start,end)

Parameter:
• start - It is optional. It represents the index from where the method starts to extract the

elements.
• end - It is optional. It represents the index at where the method stops extracting elements.

Return: A new array contains the extracted elements.


Welcome
Example

<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,2);
document.writeln(result);
</script>
</body>
</html>
Welcome
String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

By string literal
By string object (using new keyword)
ByWelcome
String literal

The string literal is created using double quotes. The syntax of creating string using string literal is
given below:
var stringname="string value";

Example:
<html>
<body>
<script>
var str="This is string literal";
document.write(str);
</script>
</body>
</html>
ByWelcome
string object

The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.

Example:
<html>
<body>
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>
Welcome
String Methods

1) JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

<script>
var str="javascript";
document.write(str.charAt(2));
</script>

2) JavaScript String concat(str) Method


The JavaScript String concat(str) method concatenates or joins two strings.

<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Welcome
String Methods

3) JavaScript String indexOf(str) Method


The JavaScript String indexOf(str) method returns the index position of the given string.

<script>
var s1="javascript from ethnus indexof";
var n=s1.indexOf("from");
document.write(n);
</script>

4) JavaScript String lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given string.

<script>
var s1="javascript from ethnus indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Welcome
String Methods

5) JavaScript String toLowerCase() Method


The JavaScript String toLowerCase() method returns the given string in lowercase letters.

<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>

6) JavaScript String toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase letters.

<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Welcome
String Methods

7) JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.

<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>

8) JavaScript String trim() Method


The JavaScript String trim() method removes leading and trailing whitespaces from the string.

<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Welcome
String Methods

9) JavaScript String split() Method:


<script>
var str="This is Ethnus website";
document.write(str.split(" ")); //splits the given string.
</script>
Welcome
Javascript Functions

JavaScript functions are used to perform operations. We can call JavaScript function many times
to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
• Code reusability: We can call a function several times so it save coding.

• Less coding: It makes our program compact. We don’t need to write many lines of code each

time to perform a common task.


Syntax:
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
Welcome
Example

<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Welcome
Function Arguments

<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
Welcome
Function with Return Value

<html>
<body>
<script>
function getInfo(){
return "hello ethnus! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
Welcome
Javascript Objects

A javaScript object is an entity having state and behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.
Welcome
Creating objects in Javascript

There are 3 ways to create objects in Javascript:


By object literal
By creating instance of Object directly (using new keyword)
By using an object constructor (using new keyword)
By object literal:
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Welcome
Example Object Literal

<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Welcome
Creating an Instance of Object

The syntax of creating object directly is given below:


var objectname=new Object();
Here, new keyword is used to create object.

Example:
<script>
var emp=new Object();
emp.id=101;
emp.name=“Vijay Adhiraj";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
ByWelcome
Using an Object Constructor

The this keyword refers to the current object.


The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Welcome
Javascript Date Object

The JavaScript date object can be used to get year, month and day. You can display a timer on
the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and
set day, month, year, hour, minute and seconds.

Constructor
You can use 4 variant of Date constructor to create date object.
Date()
Date(milliseconds)
Date(dateString)
Date(year, month, day, hours, minutes, seconds, milliseconds)
Welcome
Javascript Date Methods

1) getDate() method

The JavaScript date getDate() method returns the day for the specified date on the basis of local
time.

Syntax
The getDate() method is represented by the following syntax:

dateObj.getDate()
Return
An integer value between 1 and 31 that represents the day of the specified date.
Welcome
Example

<html>
<body>

<script>
var date=new Date();
document.writeln("Today's day: "+date.getDate());
</script>

</body>
</html>
Welcome
getDay() method

The JavaScript date getDay() method returns the value of day of the week for the specified date on
the basis of local time. The value of the day starts with 0 that represents Sunday.

Syntax
The getDay() method is represented by the following syntax:

dateObj.getDay()
Return
An integer value between 0 and 6 that represents the days of the week for the specified date.
Welcome
Example

<html>
<body>

<script>
var day=new Date();
document.writeln(day.getDay());
</script>

</body>
</html>
Welcome
getHours() method

The JavaScript date getHours() method returns the hour for the specified date on the basis of
local time.

Syntax:
The getHours() method is represented by the following syntax:

dateObj.getHours()
Return
An integer value between 0 and 23 that represents the hour.
Welcome
Example

<!DOCTYPE html>
<html>
<body>

<script>
var hour=new Date();
document.writeln(hour.getHours());
</script>

</body>
</html>
Welcome
getMilliSeconds()

The JavaScript date getMilliseconds() method returns the value of milliseconds in specified date
on the basis of local time.

Syntax
The getMilliseconds() method is represented by the following syntax:

dateObj.getMilliseconds()

Return
An integer value between 0 and 999 that represents milliseconds in specified date.
Welcome
Example

<html>
<body>

<script>
var milli =new Date();
document.writeln(milli.getMilliseconds());
</script>

</body>
</html>
Welcome
getMinutes()

The JavaScript date getMinutes() method returns the minutes in the specified date on the basis of
local time.

Syntax
The getMinutes() method is represented by the following syntax:

dateObj.getMinutes()
Return
An integer value between 0 and 59 that represents the minute.
Welcome
Example

<html>
<body>

<script>
var min=new Date();
document.writeln(min.getMinutes());
</script>

</body>
</html>
Welcome
getMonth()

The JavaScript date getMonth() method returns the integer value that represents month in the
specified date on the basis of local time. The value returned by getMonth() method starts with 0
that represents January.

Syntax
The getMonth() method is represented by the following syntax:

dateObj.getMonth()
Return
An integer value between 0 and 11 that represents the month in the specified date.
Welcome
Example

<html>
<body>

<script>
var date=new Date();
document.writeln(date.getMonth()+1);
</script>

</body>
</html>
Welcome
getSeconds()

The JavaScript date getSeconds() method returns the seconds in the specified date on the basis
of local time.

Syntax
The getSeconds() method is represented by the following syntax:

dateObj.getSeconds()
Return
An integer value between 0 and 59 that represents the second.
Welcome
Example

<html>
<body>

<script>
var sec=new Date();
document.writeln(sec.getSeconds());
</script>

</body>
</html>
Welcome
Welcome
History Object

The JavaScript history object represents an array of URLs visited by the user. By using this object,
you can load previous, forward or any particular page.

The history object is the window property, so it can be accessed by: window.history or,history.

Property of Javascript History Object


• length:Returns the length of the history URL’s.

Methods of Javascript History Object


• forward() :loads the next page.
• back() :loads the previous page.
• go() :loads the given page number.
Welcome
back() method

<html>
<body>

<h1>The Window History Object</h1>


<h2>The history.back() Method</h2>

<button onclick="history.back()">Go Back</button>

<p>Clicking "Go Back" will not result in any action, because there is no
previous page in the history list.</p>

</body>
</html>
Welcome
forward() method

<html>
<body>

<h1>The Window History Object</h1>


<h2>The history.forward Method</h2>

<button onclick="history.forward()">Go Forward</button>

<p>Clicking "Go Forward" will not result in any action, because there is no
next page in the history list.</p>

</body>
</html>
Welcome
Document object

The document object represents the whole html document.


When html document is loaded in the browser, it becomes a document object.
It is the root element that represents the html document.
It has properties and methods.
By the help of document object, we can add dynamic content to our web page.
It is the object of window so it is represented as window.document
Welcome
Methods of Document Object

The important methods are:

Method Description

write(“String”) Writes the given string on the document.

writeln(“String”) Writes the given string on the document with new line
character at the end
getElementbyId() Returns the element having the given ID value.

getElementsbyName() Returns all the elements having the given name value.

getElementsbyClassName() Returns all the elements having the given class name.

getElementsbyTagName() Returns all the elements having the given tag name.
Welcome
Accesing field value

<html>
<body>
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
</body>
</html>
Welcome
document.getElementById()

<html>
<body>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</body>
</html>
Welcome
document.getElementByName()

<html>
<body>
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>
</body>
</html>
Welcome
document.getElementByTagName()

<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Welcome
document.getElementByClassName()

<html>
<head> <h5>DOM Methods </h5> </head>
<body>
<div class="Class">
This is a simple class implementation
</div>
<script type="text/javascript">
var x=document.getElementsByClassName('Class');
document.write("On calling x, it will return an arrsy-like object: <br>"+x);
</script>
</body>
</html>
Welcome
innerHTML property

<script type="text/javascript" >


function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
Welcome
innerText property

<script type="text/javascript" >


function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}

</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
Welcome
Navigator Object

The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:window.navigator


Or,navigator .

Properties:
Property Description
1.appName Returns the name
2.appVersion Returns the version
3.appCodeName Returns the code name
4.cookieEnabled Returns true if cookie is enabled otherwise returns false.
5.userAgent Returns the user agent.
6.language Returns the language.
Welcome
Navigator Object

Property Description
7.userLanguage Returns the user language.
8.plugins Returns the plugins.
9.systemLanguage Returns the system language.
10.mimeTypes[] Returns the array of mime types
11.platform Returns the platform.
12.online Returns true if browser is online otherwise false.
Welcome
Example

<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>
Welcome
Screen Object

The JavaScript screen object holds information of browser screen. It can be used to display
screen width, height, colorDepth, pixelDepth etc.
The navigator object is the window property, so it can be accessed by:window.screen .

Properties:
• width:returns the width of the screen

• height:returns the height of the screen

• availWidth:returns the available width

• availHeight:returns the available height

• colorDepth:returns the color depth

• pixelDepth:returns the pixel depth.


Welcome
Example

<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>
Welcome
Location Object

The location object contains information about the current URL.

The location object is a property of the window object.

The location object is accessed with:

window.location or just location


Welcome
Example

<html>
<body>
<h1>The Window Location Object</h1>
<h2>The origin Property</h2>
<p id="demo"></p>
<script>
let origin = window.location.origin;
document.getElementById("demo").innerHTML = origin;
</script>
</body>
</html>
Welcome
Location Object Methods

The following are the methods:

• assign() :Loads a new document

• reload() :Reloads the current document

• replace() :Replaces the current document with a new one


Welcome
assign()

<html>
<body>
<h1>The Window Location Object</h1>
<h2>The assign Property</h2>
<button onclick="myFunction()">Load new document</button>
<script>
function myFunction() {
location.assign("https://www.ethnus.com");
}
</script>
</body>
</html>
Welcome
reload()

<html>
<body>

<h1>The Window Location Object</h1>


<h2>The reload Property</h2>

<script>
location.reload();
</script>

</body>
</html>
Welcome
replace()

<html>
<body>
<h1>The Window Location Object</h1>
<h2>The replace Property</h2>
<button onclick="myFunction()">Replace document</button>
<script>
function myFunction() {
location.replace("https://www.ethnus.com")
}
</script>
</body>
</html>
Welcome
Welcome
Rest parameter

The rest parameter is introduced in ECMAScript 2015 or ES6, which improves the ability to
handle parameters. The rest parameter allows us to represent an indefinite number of
arguments as an array. By using the rest parameter, a function can be called with any number of
arguments.

Before ES6, the arguments object of the function was used. The arguments object is not an
instance of the Array type. Therefore, we can't use the filter() method directly.

The rest parameter is prefixed with three dots (...). Although the syntax of the rest parameter is
similar to the spread operator, it is entirely opposite from the spread operator. The rest
parameter has to be the last argument because it is used to collect all of the remaining
elements into an array.
Welcome
Rest parameter syntax

function fun(a, b, ...theArgs) {


// statements
}

Sample Code:

function show(...args) {
let sum = 0;
for (let i of args) {
sum += i;
}
console.log("Sum = "+sum);
}

show(10, 20, 30);


Welcome
Example

<html>
<body>
<h2>JavaScript Function Rest Parameter</h2>
<p>The rest parameter (...) allows a function to treat an indefinite number of
arguments as an array:</p>

<p id="demo"></p>
<script>
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Welcome
Spread Operator

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or
object into another array or object.

Example:
<html>
<body>

<script>
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

document.write(numbersCombined);
</script> </body> </html>
Welcome
Global object

The global object provides variables and functions that are available anywhere.

By default, those that are built into the language or the environment.

Recently, global This was added to the language, as a standardized name for a global object,
that should be supported across all environments.

All properties of the global object can be accessed directly:

alert("Hello");// is the same as window.alert("Hello");


Welcome
setTimeOut()

The window.setTimeout() method can be written without the window prefix.

The first parameter is a function to be executed.

The second parameter indicates the number of milliseconds before execution.

Syntax : window.setTimeout(function, milliseconds);


Welcome
Example

<html>
<body>

<h2>JavaScript Timing</h2>

<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>

<button onclick="setTimeout(myFunction, 3000);">Try it</button>

<script>
function myFunction() {
alert('Hello');
}
</script>

</body>
</html>
Welcome
setInterval()

The setInterval() method repeats a given function at every given time-interval.


Syntax:window.setInterval(function, milliseconds);

The window.setInterval() method can be written without the window prefix.

The first parameter is the function to be executed.

The second parameter indicates the length of the time-interval between each execution.

This example executes a function called "myTimer" once every second (like a digital watch).
Welcome
Example

<html>
<body>

<h2>JavaScript Timing</h2>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<script>
setInterval(myTimer, 1000);

function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
Welcome
Welcome
Promises in ES6

A Promise represents something that is eventually fulfilled.


A Promise can either be rejected or resolved based on the operation outcome.Promise is the
easiest way to work with asynchronous programming in JavaScript.
Asynchronous programming includes the running of processes individually from the main thread
and notifies the main thread when it gets complete.
Prior to the Promises, Callbacks were used to perform asynchronous programming.
Callback:
A Callback is a way to handle the function execution after the completion of the execution of
another function.
A Callback would be helpful in working with events. In Callback, a function can be passed as a
parameter to another function.
Welcome
Why Promise required?

A Callback is a great way when dealing with basic cases like minimal asynchronous operations.
But when you are developing a web application that has a lot of code, then working with
Callback will be messy. This excessive Callback nesting is often referred to as Callback hell.
To deal with such cases, we have to use Promises instead of Callbacks.
Welcome
How does Promise work?

The Promise represents the completion of an asynchronous operation. It returns a single value
based on the operation being rejected or resolved. There are mainly three stages of the Promise,
which are shown below:
Welcome
How does Promise work?

Pending - It is the initial state of each Promise. It represents that the result has not been
computed yet.

Fulfilled - It means that the operation has completed.

Rejected - It represents a failure that occurs during computation.

Once a Promise is fulfilled or rejected, it will be immutable. The Promise() constructor takes two
arguments that are rejected function and a resolve function. Based on the asynchronous
operation, it returns either the first argument or second argument.
Welcome
Creating a Promise

In JavaScript, we can create a Promise by using the Promise() constructor.

Syntax:
const promise = new Promise((resolve,reject) => {....});

Example:
let promise = new Promise((resolve, reject)=>{
let a = 3;
if(a==3) { resolve('Success'); }
else { reject('Failed'); }
})
promise.then((message)=>{
console.log("It is then block. The message is: ?+ message)
}).catch((message)=>{
console.log("It is Catch block. The message is: ?+ message)
})
Welcome
Promise Methods

The Promise methods are used to handle the rejection or resolution of the Promise object. Let's
understand the brief description of Promise methods.
.then():
This method invokes when a Promise is either fulfilled or rejected.
This method can be chained for handling the rejection or fulfillment of the Promise.
It takes two functional arguments for resolved and rejected.
The first one gets invoked when the Promise is fulfilled, and the second one (which is optional)
gets invoked when the Promise is rejected.
Let's understand with the following example how to handle the Promise rejection and resolution
by using .then() method.
Welcome
Promise Methods

let success = (a) => {


console.log(a + " it worked!")
}

let error = (a) => {


console.log(a + " it failed!")
}

const Promise = num => {


return new Promise((resolve,reject) => {
if((num%2)==0){
resolve("Success!")
}
reject("Failure!")
})
}

Promise(100).then(success, error)
Promise(21).then(success,error)
Welcome
Promise Methods

.catch():It is a great way to handle failures and rejections. It takes only one functional argument for
handling the errors.

Example:
const Promise = num => {
return new Promise((resolve,reject) => {
if(num > 0){
resolve("Success!")
}
reject("Failure!")
})
}

Promise(20).then(res => {
throw new Error();
console.log(res + " success!")
}).catch(error => {
console.log(error + " oh no, it failed!")
})
Welcome
Promise Methods

.resolve():It returns a new Promise object, which is resolved with the given value. If the value has a
.then() method, then the returned Promise will follow that .then() method adopts its eventual state;
otherwise, the returned Promise will be fulfilled with value.

Example:
Promise.resolve('Success').then(function(val) {
console.log(val);
}, function(val) {
});
Welcome
Promise Methods

.reject():It returns a rejected Promise object with the given value.

Example

function resolved(result) {
console.log('Resolved');
}
function rejected(result) {
console.error(result);
}

Promise.reject(new Error('fail')).then(resolved, rejected);


Welcome
Classes

Object Orientation is a software development paradigm that follows real-world modelling. Object
Orientation, considers a program as a collection of objects that communicates with each other via
mechanism called methods. ES6 supports these object-oriented components too.
Object-Oriented Programming Concepts
Object − An object is a real-time representation of any entity. According to Grady Brooch, every
object is said to have 3 features
• State − Described by the attributes of an object.

• Behavior − Describes how the object will act.

• Identity − A unique value that distinguishes an object from a set of similar such objects.

Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for
the object.
Method − Methods facilitate communication between objects.
Welcome
Declaring a Class

class Class_name {

A class definition can include the following −

• Constructors − Responsible for allocating memory for the objects of the class.
• Functions − Functions represent actions an object can take. They are also at times referred to as
methods.
• These components put together are termed as the data members of the class.
• Note − A class body can only contain methods, but not data properties.

Example: Declaring a class


class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
Welcome
Class Expression

var var_name = new Class_name {


}
Example: Class Expression

var Polygon = class {


constructor(height, width) {
this.height = height;
this.width = width;
}
}
The above code snippet represents an unnamed class expression. A named class expression can
be written as.

var Polygon = class Polygon {


constructor(height, width) {
this.height = height;
this.width = width;
}
}
Welcome
Creating Objects

To create an instance of the class, use the new keyword followed by the class name. Following is
the syntax for the same.

var object_name= new class_name([ arguments ])

Where, the new keyword is responsible for instantiation.


The right hand side of the expression invokes the constructor. The constructor should be passed
values if it is parameterized.

Example: Instantiating a class


var obj = new Polygon(10,12)
Welcome
Accessing Functions

A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation
(called as the period) to access the data members of a class.

//accessing a function
obj.function_name()
Example:
'use strict'
class Polygon {
constructor(height, width) {
this.h = height;
this.w = width;
}
test() {
console.log("The height of the polygon: ", this.h)
console.log("The width of the polygon: ",this. w)
}
}
var polyObj = new Polygon(10,20); //creating an instance
polyObj.test();
Welcome
/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

THANK YOU
https://learn.codemithra.com

Leave your Feedback


https://ethnus.link/vitinternshipfeedbac

[email protected] +91 7815 095 095 +91 9019 921 340

You might also like