Copy of 4. JavaScript - VIT Intership
Copy of 4. JavaScript - VIT Intership
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.
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
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Welcome
Using document.write()
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Welcome
Using window.alert()
<html>
<body>
<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).
• 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.
<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
<script>
// It is single line comment
document.write("hello javascript");
</script>
Welcome
Types of Javascript Comments
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.
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:
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
<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 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.
<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;
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 −
<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;
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;
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 />");
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>
Syntax:
The syntax of ‘for..in’ loop is −
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
Example:
<body>
<script type = "text/javascript">
<!-- var x = 1;
document.write("Entering the loop<br /> ");
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 /> ");
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
ByWelcome
Array Literal
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)
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.
<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.
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.
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.
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.
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.
<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.
<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,2);
document.writeln(result);
</script>
</body>
</html>
Welcome
String
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
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Welcome
String Methods
<script>
var s1="javascript from ethnus indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
<script>
var s1="javascript from ethnus indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Welcome
String Methods
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Welcome
String Methods
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Welcome
String Methods
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
<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 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
<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
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
<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.
<html>
<body>
<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>
<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
Method Description
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">
<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>
<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.
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
<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
<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
<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>
<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
Sample Code:
function show(...args) {
let sum = 0;
for (let i of args) {
sum += i;
}
console.log("Sum = "+sum);
}
<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.
<html>
<body>
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>
Welcome
setInterval()
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 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 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.
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
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
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
Example
function resolved(result) {
console.log('Resolved');
}
function rejected(result) {
console.error(result);
}
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.
• 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 {
• 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.
To create an instance of the class, use the new keyword followed by the class name. Following is
the syntax for the same.
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