JavaScript ppt
JavaScript ppt
Example
What is JavaScript?
• JavaScript can run on both web browsers and servers. A popular JavaScript
server-side environment is Node.js Unlike client-side JavaScript, server-
side JavaScript executes on the server that allows you to access databases,
file systems, etc.
3 Places to put JavaScript code
Using var
Using let
Using const
Using nothing
When to Use JavaScript var?
var sum=10+20;
Addition +,
Subtraction -, ++ Increment
Multiplication *, -- Decrement
Division /,
Remainder %,
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
JavaScript Logical Operators
The following operators are known as JavaScript logical operators.
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an
instance of an object type
Javascript Data Types
If Statement
If else statement
if else if statement
JavaScript If statement
SYNTAX:
if (condition)
{ // statements to execute }
JavaScript If...else Statement
• It evaluates the content whether condition is true of false. The
syntax of JavaScript if-else statement is given below.
• Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else
statement
JavaScript If...else if statement
Syntax:
if (condition1)
{ // ... }
else if (condition2)
{ // ... }
else if (condition3) { //... }
else { //... }
Flowchart of JavaScript If...elseif
statement
Switch statement in JavaScript
• Use this, if we want to execute bunch of codes for different condition. The
switch statement is similar to if…else statement.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
statement;
}
Flowchart of JavaScript Switch
What is loop in Example?
• The JavaScript for loop iterates the elements for the fixed
number of times. It should be used if number of iteration is
known.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}
Flowchart of JavaScript for loop
2) JavaScript while loop
The do while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it
will repeat the loop as long as the condition is true.
Syntax:
do {
// code block to be executed
}
while (condition);
JavaScript Break and Continue
Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
JavaScript Functions
Function with Return Value:
We can call function that returns a value and use it in our program.
When JavaScript reaches a return statement, the function will stop
executing.
Syntax:
return expression;
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.
1) By object literal
2) By creating instance of Object directly (using new keyword)
3) By using an object constructor (using new keyword)
JavaScript Objects
1. By object literal
Syntax:
Objectname ={property1:value1,property2:value2..... propertyN:valueN }
Example:
<script>
const person={
firstName:"Mohana", lastName:"Priya", age:23,
phone:9876543210,address:"chennai"
};
</script>
2) By creating instance of Object
Syntax:
let objectname =new Object();
Example:
<script>
const employee=new Object();
employee.id=1001;
employee.name="Ashok";
employee.salary=16000;
</script>
3) By using an Object constructor
Syntax:
objectName.methodName();
Example:
<script>
const person={
firstName:"Dinesh",
lastName:"Kumar",
id:1005,
fullName:function(){
return this.firstName+" "+this.lastName;
}
};
</script>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements .
Example:
const color=["Green","Red","Blue","Yellow"];
2) JavaScript Array directly (new keyword)
Syntax:
let arrayname=new Array();
Example:
const student_name=new Array();
3)By using an Array constructor (using new keyword)
Example:
<script>
const fruits=new Array("apple","Mango","pineapple");
document.getElementById("demo").innerHTML=fruits[1];
</script>
JavaScript Array Methods
Popping and Pushing
JavaScript Array pop()
• The pop() method removes the last element from an array
The concat() method creates a new array by merging (concatenating) existing arrays
Sorting an Array
• The sort() method sorts an array alphabetically
Reversing an Array
• The reverse() method reverses the elements in an array.
JavaScript String
1) By string literal
• The string literal is created using double quotes.
Syntax:
let stringname="string value";
2)By string object (using new keyword)
Example:
<script>
let x="javascript";
let y=new String("Javascript");
document.getElementById("demo").innerHTML=typeofx+"<br>"+typeof y;
</script>
Escape Character
Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
JavaScript String Methods
Method/Prop Description
charAt() Returns the character at a specified index (position)
charCodeAt() Returns the Unicode of the character at a specified index
concat() Returns two or more joined strings
constructor Returns the string's constructor function
endsWith() Returns if a string ends with a specified value
fromCharCode() Returns Unicode values as characters
Method Description
isFinite() Checks whether a value is a finite number
isInteger() Checks whether a value is an integer
isNaN() Checks whether a value is Number.NaN
isSafeInteger() Checks whether a value is a safe integer
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
Property Description
constructor Returns the function that created JavaScript's Number
prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object
JavaScript Random
Math.random()
The JavaScript math random() method returns the random number
between 0 (inclusive) and 1 (exclusive).
Syntax:
Math.random()
Return
The random number between 0 (inclusive) and 1 (exclusive).
JavaScript Math Methods
Methods Description
The JavaScript math random() method returns the random number between 0 (inclusive) and 1
(exclusive).
Syntax
Math.random() Return
The random number between 0 (inclusive) and 1 (exclusive).
JavaScript Events
Note: The onKeyDown event is triggered when the user presses a key. The
onKeyUp event is triggered when the user releases a key. The onKeyPress event
is triggered when the user presses & releases a key ( onKeyDown followed by
onKeyUp ).
Form events
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by
specifying window or directly.
For example:
window.alert("hello javatpoint");
is same as:
alert("hello javatpoint");
Window Object
• The window object represents a window in browser. An object of window is
created automatically by the browser.
• Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Methods of window object
Method Description
• The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.
JavaScript Navigator Object
Strange enough, "Netscape" is the application name for both IE11, Chrome,
Firefox, and Safari.
"Mozilla" is the application code name for both Chrome, Firefox, IE, Safari,
and Opera.
Warning !!!
The information from the navigator object can often be misleading, and
should not be used to detect browser versions because:
Different browsers can use the same name
The navigator data can be changed by the browser owner
Some browsers misidentify themselves to bypass site tests
Browsers cannot report new operating systems, released later than the
browser
JavaScript Window Location
The window.location object can be used to get the current page address (URL) and to redirect the
browser to a new page.
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http: or https:)
Window Object
What is the DOM?
When a web page is loaded, the browser creates a Document Object Model
of the page.
Document- is means it can be any file [e.g.: HTML ,XML .. etc]
Object -means (Tags Element) Eg: <h1> <img> .. etc
Model- Layout Structure (eg:HTML Structure)
The HTML DOM model is constructed as a tree of Objects
With the object model, JavaScript gets all the power
it needs to create dynamic HTML
The HTML DOM is a standard object model and programming interface for HTML. It defines:
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML
element).
A method is an action you can do (like add or deleting an HTML element).
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.
The innerHTML Property
innerText innerHTML
Retrieves and sets the content Retrieves and sets the content
in plain text. in HTML format.
We can not insert We can insert the HTML tags.
the HTML tags.
It ignores the spaces. It considers the spaces.
It returns text without It returns a tag with
an inner element an inner element
tag. tag.
Finding HTML Elements
Method Description
Property Description
element.innerHTML = new Change the inner HTML of
html content an element
element.attribute = new value Change the attribute value of an
HTML element
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
Syntax
for (variable_name in object_name) //Here in is the keyword
{
// statement or block to execute
}
Example:
const fruits = ["apple", "orange", "cherry"];
const mobile={name:"Oppo",model:"A37",color:"Gold"};
JavaScript Iterables
for…of loop
Unlike the object literals, this loop is used to iterate the iterables (arrays,
string, etc.).
Syntax
for(variable_name of object_name) // Here of is a keyword
{
//statement or block to execute
}
In every iteration, one property from the iterables gets assigned to the
variable_name, and the loop continues till the end of the iteration.
. Arrow Functions
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.
JavaScript Classes
JavaScript Class Syntax
Use the keyword class to create a class.
Always add a method named constructor()
Syntax
class ClassName {
constructor() { ... }
}
• A JavaScript class is not an object.
• It is a template for JavaScript objects.
JavaScript HTML DOM EventListener
Syntax:
element.addEventListener(event, function, useCapture);
Example
element.addEventListener("click", function(){ alert("Hello World!"); });
JavaScript HTML DOM EventListener
Property Description