SlideShare a Scribd company logo
1 of 77
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

Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Gil Fink
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Adnan Sohail
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? EdurekaEdureka!
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xmlmussawir20
 
Introduction to JavaScript.pptx
Introduction to JavaScript.pptxIntroduction to JavaScript.pptx
Introduction to JavaScript.pptxAxmedMaxamuud4
 
CS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question BankCS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question Bankpkaviya
 
What Is Php
What Is PhpWhat Is Php
What Is PhpAVC
 
Big Data technology Landscape
Big Data technology LandscapeBig Data technology Landscape
Big Data technology LandscapeShivanandaVSeeri
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and responseSahil Agarwal
 
Introduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptxIntroduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptxKADAMBARIPUROHIT
 

What's hot (20)

Web servers
Web serversWeb servers
Web servers
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? Edureka
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
Json
JsonJson
Json
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
 
Jsp(java server pages)
Jsp(java server pages)Jsp(java server pages)
Jsp(java server pages)
 
Java script
Java scriptJava script
Java script
 
Introduction to JavaScript.pptx
Introduction to JavaScript.pptxIntroduction to JavaScript.pptx
Introduction to JavaScript.pptx
 
CS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question BankCS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question Bank
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Big Data technology Landscape
Big Data technology LandscapeBig Data technology Landscape
Big Data technology Landscape
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 
Structure of Semantic web
Structure of Semantic web Structure of Semantic web
Structure of Semantic web
 
Php
PhpPhp
Php
 
Introduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptxIntroduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptx
 

Similar to JavaScript.pptx

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
 
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
 
Java Fx
Java FxJava Fx
Java Fx
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 

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!";