SlideShare a Scribd company logo
JavaScript
BY
DR. S. PRADEEP KUMAR KENNY
Outline
• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of
web pages
Intro
• JavaScript is an object-based scripting
language that is lightweight and cross-
platform programming language.
• JavaScript is not compiled but translated. The
JavaScript Translator (embedded in browser) is
responsible to translate the JavaScript code.
• JavaScript is also used in environments that
aren't web-based, such as PDF documents,
site-specific browsers, and desktop widgets.
Intro
• It is used to create interactive websites. It is
mainly used for:
– Client-side validation
– Dynamic drop-down menus
– Displaying data and time
– Displaying popup windows and dialog boxes (like
alert dialog box, confirm dialog box and prompt
dialog box)
– Displaying clocks etc.
Internal JavaScript
• <script>
.
.
.
</script>
• Any number of scripts can be given.
• Scripts can be placed in the <body>, or in the
<head> section of an HTML page, or in both.
External JavaScript
• <html>
<body>
<script type="text/javascript"
src="script/sample.js"></script>
</body>
</html>
• Placing JavaScripts in external files has some
advantages: It separates HTML and code.
• It makes HTML and JavaScript easier to read and
maintain
Cached JavaScript files can speed up page loads.
JavaScript Display Possibilities
• Writing into an alert box, using
window.alert().
• Writing into the HTML output using
document.write().
• Writing into an HTML element, using
innerHTML.
• Writing into the browser console, using
console.log().
• window.alert(5 + 6);
• document.write(5 + 6);
• <button onclick="document.write(5 + 6)">Try
it</button>
• <p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
5 + 6;
</script>
• console.log(5 + 6);
Syntax and General Rules
• JavaScript is a programming language.
• JavaScript statements are separated by
semicolon.
• JavaScript statements are composed of:
– Values, Operators, Expressions, Keywords, and
Comments.
• JavaScript Values comprise of
– Fixed values are called literals. Variable values are
called variables.
JavaScript Literals
• JavaScript Literals rules
– Numbers are written with or without decimals
– Strings are text, written within double or single
quotes
– Expressions can also represent fixed values
JavaScript Variables
• var x = 5;
var y = 6;
var z = x + y;
• var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
One Statement, Many Variables
• var person = "John Doe", carName = "Volvo",
price = 200;
Rules for variable
• The general rules for constructing names for variables
(unique identifiers) are:
• Names can contain letters, digits, underscores, and
dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _ (but we will not use
it in this tutorial)
• Names are case sensitive (y and Y are different
variables)
• Reserved words (like JavaScript keywords) cannot be
used as names
Datatypes
• var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"};
// Object
JavaScript Has Dynamic Types
• var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JavaScript Strings
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
var answer = "It's alright";
// Single quote inside double quotes
var answer = "He is called 'Johnny'";
// Single quotes inside double quotes
var answer = 'He is called "Johnny"';
// Double quotes inside single quotes
JavaScript Strings functions
• String Length
– var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
– var sln = txt.length;
• Special Characters
–  escape character
– var x = 'It's alright';
– var y = "We are the so-called "Vikings" from the
north."
• Special Characters
JavaScript Strings functions
Code Outputs
' single quote
" double quote
 backslash
n new line
r carriage return
t tab
b backspace
f form feed
• equality operator
• var x = "John";
var y = "John”;
if(x == y) is true because x and y have equal
values
JavaScript Strings functions
Strings Can be Objects
• var x = "John";
• var y = new String("John");
– But this will slow the code and is not a good
programming practice.
– However if you use objects you can access string
properties and methods
Property Description
constructor
Returns the function that
created the String object's
prototype
length Returns the length of a string
prototype
Allows you to add properties
and methods to an object
Strings Can be Objects
Method
charAt()
Returns the character at the specified index (position)
charCodeAt()
Returns the Unicode of the character at the specified index
concat()
Joins two or more strings, and returns a copy of the joined strings
fromCharCode()
Converts Unicode values to characters
indexOf()
Returns the position of the first found occurrence of a specified value
in a string
Strings Can be Objects
lastIndexOf()
Returns the position of the last found occurrence of a specified value
in a string
localeCompare()
Compares two strings in the current locale
match()
Searches a string for a match against a regular expression, and returns
the matches
replace()
Searches a string for a value and returns a new string with the value
replaced
search()
Searches a string for a value and returns the position of the match
Strings Can be Objects
slice()
Extracts a part of a string and returns a new string
split()
Splits a string into an array of substrings
substr()
Extracts a part of a string from a start position through a number of
characters
substring()
Extracts a part of a string between two specified positions
toLocaleLowerCase()
Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase()
Strings Can be Objects
Converts a string to uppercase letters, according to the host's locale
toLowerCase()
Converts a string to lowercase letters
toString()
Returns the value of a String object
toUpperCase()
Converts a string to uppercase letters
trim()
Removes whitespace from both ends of a string
valueOf()
Returns the primitive value of a String object
JavaScript Numbers
• var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
• exponent notation
– var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
JavaScript Numbers
• Precision
• The maximum number of decimals is 17, but
floating point arithmetic is not always 100%
accurate:
– var x = 0.2 + 0.1; // x will be
0.30000000000000004
• Integers (numbers without a period or exponent
notation) are considered accurate up to 15 digits.
– var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000
JavaScript Numbers
• Hexadecimal
– var x = 0xFF; // x will be 255
• Infinity (or -Infinity) is the value JavaScript will
return if you calculate a number outside the
largest possible number.
– Like for example in an infinite loop
• NaN - Not a Number
JavaScript Numbers
• Numbers Can be Objects
– var y = new Number(123);
• Just like strings it has properties and methods
Property Description
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)
• Global Methods
JavaScript Numbers
Method Description
Number()
Returns a number, converted
from its argument.
parseFloat()
Parses its argument and
returns a floating point
number
parseInt()
Parses its argument and
returns an integer
• Number Methods
JavaScript Numbers
Method Description
toString() Returns a number as a string
toExponential()
Returns a string, with a
number rounded and written
using exponential notation.
toFixed()
Returns a string, with a
number rounded and written
with a specified number of
decimals.
toPrecision()
Returns a string, with a
number written with a
specified length
valueOf()
Returns a number as a
number
JavaScript Booleans
• var x = true;
var y = false;
JavaScript Arrays
• Syntax
• var array-name = [item1, item2, ...];
• Example
• var cars = ["Saab", "Volvo", "BMW"];
JavaScript Arrays
• Access the Elements of an Array using index
• var name = cars[0];
• cars[0] = "Opel";
• You can have different objects in array
• myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Arrays are Objects
• Array
• var person = ["John", "Doe", 46];
• Object
• var person = {firstName:"John", lastName:"Doe",
age:46};
• The Difference Between Arrays and Objects?
• In JavaScript, arrays use numbered indexes.
• In JavaScript, objects use named indexes.
Array Properties and Methods
Property Description
constructor
Returns the function that
created the Array object's
prototype
length
Sets or returns the number of
elements in an array
prototype
Allows you to add properties
and methods to an Array
object
Array Properties
Array Properties and Methods
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
lastIndexOf
()
Search the array for an element, starting at the end, and returns its position
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
valueOf() Returns the primitive value of an array
Array Methods
Associative Arrays?
• Many programming languages support arrays
with named indexes.
• Arrays with named indexes are called
associative arrays (or hashes).
• JavaScript does not support arrays with
named indexes.
• In JavaScript, arrays use numbered indexes.
JavaScript Objects
• var person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
JavaScript Objects
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function(c) {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
Accessing Object Properties
Syntax
objectName.propertyName
or
objectName[propertyName]
Example
person.lastName;
Or
person["lastName"];
Accessing Object Methods
Syntax
• objectName.methodName()
• Example
• name = person.fullName();
• Note: If () is omitted then function definition will be
returned
The typeof Operator
• typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
JavaScript Math Object
• Eg:-
• Math.random();
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x)
Returns the arctangent of x as a numeric value
between -PI/2 and PI/2 radians
atan2(y,x)
Returns the arctangent of the quotient of its
arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x)
Returns x, rounded downwards to the nearest
integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
Math Object Methods
JavaScript Dates
• To display date use the following function
– Date();
Creating Date Objects
• The Date object lets us work with dates.
• A date consists of a year, a month, a day, a
minute, a second, and a millisecond.
• Date objects are created with the new Date()
constructor.
• There are 4 ways of initiating a date:
– new Date()
– new Date(milliseconds)
– new Date(dateString)
– new Date(year, month, day, hours, minutes, seconds,
milliseconds)
Creating Date Objects
• Implementation
• <script>
var d = new Date();
document.getElementById("demo").innerHT
ML = d;
</script>
Date Methods
• The toDateString() method converts a date to
a more readable format
• The toUTCString() method converts a date to
a UTC string (a date display standard).
– Coordinated Universal Time (UTC)
• When you display a date object in HTML, it is
automatically converted to a string, with the
toString() method.
Date Get Methods
Method Description
getDate()
Get the day as a number (1-
31)
getDay()
Get the weekday as a number
(0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime()
Get the time (milliseconds
since January 1, 1970)
Date Set Methods
Method Description
setDate() Set the day as a number (1-31)
setFullYear()
Set the year (optionally month
and day yyyy.mm.dd)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime()
Set the time (milliseconds
since January 1, 1970)
Compare Dates
• Logical operations can be performed on dates
When to Use Arrays? When to use
Objects?
• You should use objects when you want the
element names to be strings (text).
• You should use arrays when you want the
element names to be numbers.
JavaScript Operators
• JavaScript Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
JavaScript Operators
• JavaScript Assignment Operators
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
JavaScript Operators
• Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
JavaScript Operators
• Logical Operators
Operator Description Example
&& and
(x < 10 && y > 1) is
true
|| or
(x == 5 || y == 5) is
false
! not !(x == y) is true
JavaScript Operators
• variablename = (condition) ? value1:value2
JavaScript Operators
• JavaScript Bitwise Operators
Operator Description Example
& AND x = 5 & 1
| OR x = 5 | 1
~ NOT x = ~ 5
^ XOR x = 5 ^ 1
<< Left shift x = 5 << 1
>> Right shift x = 5 >> 1
JavaScript If...Else Statements
• The if Statement
– if (condition) {
block of code to be executed if the condition is true
}
• The else Statement
– if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
JavaScript If...Else Statements
• The else if Statement
– if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is
false and condition2 is true
} else {
block of code to be executed if the condition1 is
false and condition2 is false
}
JavaScript Switch Statement
• switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
JavaScript Loops
• JavaScript supports different kinds of loops:
• for - loops through a block of code a number
of times
• for/in - loops through the properties of an
object
• while - loops through a block of code while a
specified condition is true
• do/while - also loops through a block of code
while a specified condition is true
JavaScript Loops
• The For Loop
– for (statement 1; statement 2; statement 3) {
code block to be executed
}
JavaScript Loops
• The For/In Loop
– The JavaScript for/in statement loops through the
properties of an object
– var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
JavaScript Loops
• The While Loop
– while (condition) {
code block to be executed
}
JavaScript Loops
• The Do/While Loop
– do {
code block to be executed
}
while (condition);
JavaScript Break and Continue
• JavaScript Labels
– break labelname;
continue labelname;
• The continue statement (with or without a label
reference) can only be used inside a loop.
• The break statement, without a label reference, can
only be used inside a loop or a switch.
• With a label reference, it can be used to "jump out of"
any JavaScript code block (like goto statement in c)
JavaScript Functions
• Syntax
• functionName(parameter1, parameter2, …)
{
code to be executed
}
• Implementation
• function myFunction(p1, p2)
{
return p1 * p2;
// the function returns the product of p1 and p2
}
New Keyword
• var x = new String();
// Declares x as a String object
var y = new Number();
// Declares y as a Number object
var z = new Boolean();
// Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They
complicate your code and slow down execution speed.
JavaScript Scope
• Local JavaScript Variables
• Global JavaScript Variables
• Automatically Global
– If you assign a value to a variable that has not
been declared, it will automatically become a
GLOBAL variable.
JavaScript Events
• HTML events are "things" that happen to
HTML elements.
• When JavaScript is used in HTML pages,
JavaScript can "react" on these events.
JavaScript Events
• An HTML event can be something the
browser does, or something a user
does.
• Here are some examples of HTML
events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
JavaScript Events Eg:-
• <button
onclick='getElementById("demo").innerHTML
=Date()'>The time is?</button>
Common HTML Events
Event Description
onchange
An HTML element has been
changed
onclick
The user clicks an HTML
element
onmouseover
The user moves the mouse
over an HTML element
onmouseout
The user moves the mouse
away from an HTML element
onkeydown
The user pushes a keyboard
key
onload
The browser has finished
loading the page
What does JavaScript do when these
events are fired?
• Event handlers can be used to handle, and verify,
user input, user actions, and browser actions:
– Things that should be done every time a page loads
– Things that should be done when the page is closed
– Action that should be performed when a user clicks a
button
– Content that should be verified when a user input
data
– And more ...
What does JavaScript do when these
events are fired?
• Many different methods can be used to let JavaScript
work with events:
• HTML event attributes can execute JavaScript code
directly
• HTML event attributes can call JavaScript functions
• You can assign your own event handler functions to
HTML elements
• You can prevent events from being sent or being
handled
• And more ...
Breaking Long Code Lines
• Screen size is 80 characters... Hence breaking the
long lines of code becomes a necessity
• Examples of breaking code lines
– document.getElementById("demo").innerHTML =
"Hello Dolly.";
• You can also break up a code line within a text
string with a single backslash:
– document.getElementById("demo").innerHTML = "Hello 
Dolly!";
• However, you cannot break up a code line
with a backslash:
• document.getElementById("demo").innerHTML = 
"Hello Dolly!";

More Related Content

What's hot

Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
Kang-min Liu
 
Class Intro / HTML Basics
Class Intro / HTML BasicsClass Intro / HTML Basics
Class Intro / HTML Basics
Shawn Calvert
 
Html,javascript & css
Html,javascript & cssHtml,javascript & css
Html,javascript & css
Predhin Sapru
 
Css
CssCss
1 03 - CSS Introduction
1 03 - CSS Introduction1 03 - CSS Introduction
1 03 - CSS Introduction
apnwebdev
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
GOPAL BASAK
 
HTML5
HTML5HTML5
Angular 9
Angular 9 Angular 9
Angular 9
Raja Vishnu
 
CSS
CSSCSS
Bootstrap.pptx
Bootstrap.pptxBootstrap.pptx
Bootstrap.pptx
vishal choudhary
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
Document object model(dom)
Document object model(dom)Document object model(dom)
Document object model(dom)
rahul kundu
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Edureka!
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
casestudyhelp
 
Css lecture notes
Css lecture notesCss lecture notes
Css lecture notes
Santhiya Grace
 
CSS - Text Properties
CSS - Text PropertiesCSS - Text Properties
CSS - Text Properties
hstryk
 
Web 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style SheetsWeb 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style Sheets
Mohammad Imam Hossain
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
DHTMLExtreme
 
Introduction to Cascading Style Sheets
Introduction to Cascading Style SheetsIntroduction to Cascading Style Sheets
Introduction to Cascading Style Sheets
Tushar Joshi
 

What's hot (20)

Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Class Intro / HTML Basics
Class Intro / HTML BasicsClass Intro / HTML Basics
Class Intro / HTML Basics
 
Html,javascript & css
Html,javascript & cssHtml,javascript & css
Html,javascript & css
 
Css
CssCss
Css
 
1 03 - CSS Introduction
1 03 - CSS Introduction1 03 - CSS Introduction
1 03 - CSS Introduction
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
HTML5
HTML5HTML5
HTML5
 
Angular 9
Angular 9 Angular 9
Angular 9
 
CSS
CSSCSS
CSS
 
Bootstrap.pptx
Bootstrap.pptxBootstrap.pptx
Bootstrap.pptx
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Document object model(dom)
Document object model(dom)Document object model(dom)
Document object model(dom)
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
 
Css lecture notes
Css lecture notesCss lecture notes
Css lecture notes
 
CSS - Text Properties
CSS - Text PropertiesCSS - Text Properties
CSS - Text Properties
 
Web 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style SheetsWeb 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style Sheets
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Introduction to Cascading Style Sheets
Introduction to Cascading Style SheetsIntroduction to Cascading Style Sheets
Introduction to Cascading Style Sheets
 

Similar to JavaScript.pptx

Java script basics
Java script basicsJava script basics
Java script basics
Shrivardhan Limbkar
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
Universe41
 
fundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.pptfundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.ppt
dejen6
 
Javascript
JavascriptJavascript
Javascript
Sunil Thakur
 
Variables
VariablesVariables
javascript client side scripting la.pptx
javascript client side scripting la.pptxjavascript client side scripting la.pptx
javascript client side scripting la.pptx
lekhacce
 
Java
JavaJava
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
Uchitha Bandara
 
Java ce241
Java ce241Java ce241
Java ce241
Minal Maniar
 
Javascript
JavascriptJavascript
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
AbdulRazaqAnjum
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
AmitSharma397241
 
Java script summary
Java script summaryJava script summary
Java script summary
maamir farooq
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
jason hu 金良胡
 
Php basics
Php basicsPhp basics
Php basics
hamfu
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
Ramamohan Chokkam
 
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
 

Similar to JavaScript.pptx (20)

Java script basics
Java script basicsJava script basics
Java script basics
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
fundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.pptfundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.ppt
 
Javascript
JavascriptJavascript
Javascript
 
Variables
VariablesVariables
Variables
 
javascript client side scripting la.pptx
javascript client side scripting la.pptxjavascript client side scripting la.pptx
javascript client side scripting la.pptx
 
Java
JavaJava
Java
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Java ce241
Java ce241Java ce241
Java ce241
 
Javascript
JavascriptJavascript
Javascript
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
Php basics
Php basicsPhp basics
Php basics
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
Learning core java
Learning core javaLearning core java
Learning core java
 

Recently uploaded

Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 

Recently uploaded (20)

Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 

JavaScript.pptx

  • 2. Outline • 1. HTML to define the content of web pages • 2. CSS to specify the layout of web pages • 3. JavaScript to program the behavior of web pages
  • 3. Intro • JavaScript is an object-based scripting language that is lightweight and cross- platform programming language. • JavaScript is not compiled but translated. The JavaScript Translator (embedded in browser) is responsible to translate the JavaScript code. • JavaScript is also used in environments that aren't web-based, such as PDF documents, site-specific browsers, and desktop widgets.
  • 4. Intro • It is used to create interactive websites. It is mainly used for: – Client-side validation – Dynamic drop-down menus – Displaying data and time – Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt dialog box) – Displaying clocks etc.
  • 5. Internal JavaScript • <script> . . . </script> • Any number of scripts can be given. • Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
  • 6. External JavaScript • <html> <body> <script type="text/javascript" src="script/sample.js"></script> </body> </html> • Placing JavaScripts in external files has some advantages: It separates HTML and code. • It makes HTML and JavaScript easier to read and maintain Cached JavaScript files can speed up page loads.
  • 7. JavaScript Display Possibilities • Writing into an alert box, using window.alert(). • Writing into the HTML output using document.write(). • Writing into an HTML element, using innerHTML. • Writing into the browser console, using console.log().
  • 8. • window.alert(5 + 6); • document.write(5 + 6); • <button onclick="document.write(5 + 6)">Try it</button> • <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> • console.log(5 + 6);
  • 9. Syntax and General Rules • JavaScript is a programming language. • JavaScript statements are separated by semicolon. • JavaScript statements are composed of: – Values, Operators, Expressions, Keywords, and Comments. • JavaScript Values comprise of – Fixed values are called literals. Variable values are called variables.
  • 10. JavaScript Literals • JavaScript Literals rules – Numbers are written with or without decimals – Strings are text, written within double or single quotes – Expressions can also represent fixed values
  • 11. JavaScript Variables • var x = 5; var y = 6; var z = x + y; • var pi = 3.14; var person = "John Doe"; var answer = 'Yes I am!';
  • 12. One Statement, Many Variables • var person = "John Doe", carName = "Volvo", price = 200;
  • 13. Rules for variable • The general rules for constructing names for variables (unique identifiers) are: • Names can contain letters, digits, underscores, and dollar signs. • Names must begin with a letter • Names can also begin with $ and _ (but we will not use it in this tutorial) • Names are case sensitive (y and Y are different variables) • Reserved words (like JavaScript keywords) cannot be used as names
  • 14. Datatypes • var length = 16; // Number var lastName = "Johnson"; // String var cars = ["Saab", "Volvo", "BMW"]; // Array var x = {firstName:"John", lastName:"Doe"}; // Object
  • 15. JavaScript Has Dynamic Types • var x; // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String
  • 16. JavaScript Strings var carName = "Volvo XC60"; // Using double quotes var carName = 'Volvo XC60'; // Using single quotes var answer = "It's alright"; // Single quote inside double quotes var answer = "He is called 'Johnny'"; // Single quotes inside double quotes var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
  • 17. JavaScript Strings functions • String Length – var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; – var sln = txt.length; • Special Characters – escape character – var x = 'It's alright'; – var y = "We are the so-called "Vikings" from the north."
  • 18. • Special Characters JavaScript Strings functions Code Outputs ' single quote " double quote backslash n new line r carriage return t tab b backspace f form feed
  • 19. • equality operator • var x = "John"; var y = "John”; if(x == y) is true because x and y have equal values JavaScript Strings functions
  • 20. Strings Can be Objects • var x = "John"; • var y = new String("John"); – But this will slow the code and is not a good programming practice. – However if you use objects you can access string properties and methods Property Description constructor Returns the function that created the String object's prototype length Returns the length of a string prototype Allows you to add properties and methods to an object
  • 21. Strings Can be Objects Method charAt() Returns the character at the specified index (position) charCodeAt() Returns the Unicode of the character at the specified index concat() Joins two or more strings, and returns a copy of the joined strings fromCharCode() Converts Unicode values to characters indexOf() Returns the position of the first found occurrence of a specified value in a string
  • 22. Strings Can be Objects lastIndexOf() Returns the position of the last found occurrence of a specified value in a string localeCompare() Compares two strings in the current locale match() Searches a string for a match against a regular expression, and returns the matches replace() Searches a string for a value and returns a new string with the value replaced search() Searches a string for a value and returns the position of the match
  • 23. Strings Can be Objects slice() Extracts a part of a string and returns a new string split() Splits a string into an array of substrings substr() Extracts a part of a string from a start position through a number of characters substring() Extracts a part of a string between two specified positions toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale toLocaleUpperCase()
  • 24. Strings Can be Objects Converts a string to uppercase letters, according to the host's locale toLowerCase() Converts a string to lowercase letters toString() Returns the value of a String object toUpperCase() Converts a string to uppercase letters trim() Removes whitespace from both ends of a string valueOf() Returns the primitive value of a String object
  • 25. JavaScript Numbers • var x1 = 34.00; // Written with decimals var x2 = 34; // Written without decimals • exponent notation – var x = 123e5; // 12300000 var y = 123e-5; // 0.00123
  • 26. JavaScript Numbers • Precision • The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate: – var x = 0.2 + 0.1; // x will be 0.30000000000000004 • Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits. – var x = 999999999999999; // x will be 999999999999999 var y = 9999999999999999; // y will be 10000000000000000
  • 27. JavaScript Numbers • Hexadecimal – var x = 0xFF; // x will be 255 • Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. – Like for example in an infinite loop • NaN - Not a Number
  • 28. JavaScript Numbers • Numbers Can be Objects – var y = new Number(123); • Just like strings it has properties and methods Property Description 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)
  • 29. • Global Methods JavaScript Numbers Method Description Number() Returns a number, converted from its argument. parseFloat() Parses its argument and returns a floating point number parseInt() Parses its argument and returns an integer
  • 30. • Number Methods JavaScript Numbers Method Description toString() Returns a number as a string toExponential() Returns a string, with a number rounded and written using exponential notation. toFixed() Returns a string, with a number rounded and written with a specified number of decimals. toPrecision() Returns a string, with a number written with a specified length valueOf() Returns a number as a number
  • 31. JavaScript Booleans • var x = true; var y = false;
  • 32. JavaScript Arrays • Syntax • var array-name = [item1, item2, ...]; • Example • var cars = ["Saab", "Volvo", "BMW"];
  • 33. JavaScript Arrays • Access the Elements of an Array using index • var name = cars[0]; • cars[0] = "Opel"; • You can have different objects in array • myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars;
  • 34. Arrays are Objects • Array • var person = ["John", "Doe", 46]; • Object • var person = {firstName:"John", lastName:"Doe", age:46}; • The Difference Between Arrays and Objects? • In JavaScript, arrays use numbered indexes. • In JavaScript, objects use named indexes.
  • 35. Array Properties and Methods Property Description constructor Returns the function that created the Array object's prototype length Sets or returns the number of elements in an array prototype Allows you to add properties and methods to an Array object Array Properties
  • 36. Array Properties and Methods Method Description concat() Joins two or more arrays, and returns a copy of the joined arrays indexOf() Search the array for an element and returns its position join() Joins all elements of an array into a string lastIndexOf () Search the array for an element, starting at the end, and returns its position pop() Removes the last element of an array, and returns that element push() Adds new elements to the end of an array, and returns the new length reverse() Reverses the order of the elements in an array shift() Removes the first element of an array, and returns that element slice() Selects a part of an array, and returns the new array sort() Sorts the elements of an array splice() Adds/Removes elements from an array toString() Converts an array to a string, and returns the result unshift() Adds new elements to the beginning of an array, and returns the new length valueOf() Returns the primitive value of an array Array Methods
  • 37. Associative Arrays? • Many programming languages support arrays with named indexes. • Arrays with named indexes are called associative arrays (or hashes). • JavaScript does not support arrays with named indexes. • In JavaScript, arrays use numbered indexes.
  • 38. JavaScript Objects • var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; <script> var person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" }; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script>
  • 39. JavaScript Objects <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function(c) { return this.firstName + " " + this.lastName; } }; document.getElementById("demo").innerHTML = person.fullName(); </script>
  • 41. Accessing Object Methods Syntax • objectName.methodName() • Example • name = person.fullName(); • Note: If () is omitted then function definition will be returned
  • 42. The typeof Operator • typeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name:'John', age:34} // Returns object
  • 43. JavaScript Math Object • Eg:- • Math.random(); Method Description abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y,x) Returns the arctangent of the quotient of its arguments ceil(x) Returns x, rounded upwards to the nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x,y,z,...,n) Returns the number with the highest value min(x,y,z,...,n) Returns the number with the lowest value pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle Math Object Methods
  • 44. JavaScript Dates • To display date use the following function – Date();
  • 45. Creating Date Objects • The Date object lets us work with dates. • A date consists of a year, a month, a day, a minute, a second, and a millisecond. • Date objects are created with the new Date() constructor. • There are 4 ways of initiating a date: – new Date() – new Date(milliseconds) – new Date(dateString) – new Date(year, month, day, hours, minutes, seconds, milliseconds)
  • 46. Creating Date Objects • Implementation • <script> var d = new Date(); document.getElementById("demo").innerHT ML = d; </script>
  • 47. Date Methods • The toDateString() method converts a date to a more readable format • The toUTCString() method converts a date to a UTC string (a date display standard). – Coordinated Universal Time (UTC) • When you display a date object in HTML, it is automatically converted to a string, with the toString() method.
  • 48. Date Get Methods Method Description getDate() Get the day as a number (1- 31) getDay() Get the weekday as a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) getMonth() Get the month (0-11) getSeconds() Get the seconds (0-59) getTime() Get the time (milliseconds since January 1, 1970)
  • 49. Date Set Methods Method Description setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day yyyy.mm.dd) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970)
  • 50. Compare Dates • Logical operations can be performed on dates
  • 51. When to Use Arrays? When to use Objects? • You should use objects when you want the element names to be strings (text). • You should use arrays when you want the element names to be numbers.
  • 52. JavaScript Operators • JavaScript Arithmetic Operators Operator Description + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment -- Decrement
  • 53. JavaScript Operators • JavaScript Assignment Operators Operator Example Same As = x = y x = y += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y
  • 54. JavaScript Operators • Comparison Operators Operator Description == equal to === equal value and equal type != not equal !== not equal value or not equal type > greater than < less than >= greater than or equal to <= less than or equal to
  • 55. JavaScript Operators • Logical Operators Operator Description Example && and (x < 10 && y > 1) is true || or (x == 5 || y == 5) is false ! not !(x == y) is true
  • 56. JavaScript Operators • variablename = (condition) ? value1:value2
  • 57. JavaScript Operators • JavaScript Bitwise Operators Operator Description Example & AND x = 5 & 1 | OR x = 5 | 1 ~ NOT x = ~ 5 ^ XOR x = 5 ^ 1 << Left shift x = 5 << 1 >> Right shift x = 5 >> 1
  • 58. JavaScript If...Else Statements • The if Statement – if (condition) { block of code to be executed if the condition is true } • The else Statement – if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false }
  • 59. JavaScript If...Else Statements • The else if Statement – if (condition1) { block of code to be executed if condition1 is true } else if (condition2) { block of code to be executed if the condition1 is false and condition2 is true } else { block of code to be executed if the condition1 is false and condition2 is false }
  • 60. JavaScript Switch Statement • switch(expression) { case n: code block break; case n: code block break; default: default code block }
  • 61. JavaScript Loops • JavaScript supports different kinds of loops: • for - loops through a block of code a number of times • for/in - loops through the properties of an object • while - loops through a block of code while a specified condition is true • do/while - also loops through a block of code while a specified condition is true
  • 62. JavaScript Loops • The For Loop – for (statement 1; statement 2; statement 3) { code block to be executed }
  • 63. JavaScript Loops • The For/In Loop – The JavaScript for/in statement loops through the properties of an object – var person = {fname:"John", lname:"Doe", age:25}; var text = ""; var x; for (x in person) { text += person[x]; }
  • 64. JavaScript Loops • The While Loop – while (condition) { code block to be executed }
  • 65. JavaScript Loops • The Do/While Loop – do { code block to be executed } while (condition);
  • 66. JavaScript Break and Continue • JavaScript Labels – break labelname; continue labelname; • The continue statement (with or without a label reference) can only be used inside a loop. • The break statement, without a label reference, can only be used inside a loop or a switch. • With a label reference, it can be used to "jump out of" any JavaScript code block (like goto statement in c)
  • 67. JavaScript Functions • Syntax • functionName(parameter1, parameter2, …) { code to be executed } • Implementation • function myFunction(p1, p2) { return p1 * p2; // the function returns the product of p1 and p2 }
  • 68. New Keyword • var x = new String(); // Declares x as a String object var y = new Number(); // Declares y as a Number object var z = new Boolean(); // Declares z as a Boolean object Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.
  • 69. JavaScript Scope • Local JavaScript Variables • Global JavaScript Variables • Automatically Global – If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
  • 70. JavaScript Events • HTML events are "things" that happen to HTML elements. • When JavaScript is used in HTML pages, JavaScript can "react" on these events.
  • 71. JavaScript Events • An HTML event can be something the browser does, or something a user does. • Here are some examples of HTML events: • An HTML web page has finished loading • An HTML input field was changed • An HTML button was clicked
  • 72. JavaScript Events Eg:- • <button onclick='getElementById("demo").innerHTML =Date()'>The time is?</button>
  • 73. Common HTML Events Event Description onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page
  • 74. What does JavaScript do when these events are fired? • Event handlers can be used to handle, and verify, user input, user actions, and browser actions: – Things that should be done every time a page loads – Things that should be done when the page is closed – Action that should be performed when a user clicks a button – Content that should be verified when a user input data – And more ...
  • 75. What does JavaScript do when these events are fired? • Many different methods can be used to let JavaScript work with events: • HTML event attributes can execute JavaScript code directly • HTML event attributes can call JavaScript functions • You can assign your own event handler functions to HTML elements • You can prevent events from being sent or being handled • And more ...
  • 76. Breaking Long Code Lines • Screen size is 80 characters... Hence breaking the long lines of code becomes a necessity • Examples of breaking code lines – document.getElementById("demo").innerHTML = "Hello Dolly."; • You can also break up a code line within a text string with a single backslash: – document.getElementById("demo").innerHTML = "Hello Dolly!";
  • 77. • However, you cannot break up a code line with a backslash: • document.getElementById("demo").innerHTML = "Hello Dolly!";