Java Scriptv1.0
Java Scriptv1.0
What is JavaScript
Object based (not object oriented) programming
language
very limited object creation
a set of pre-defined objects associated with
HTML document structure
many HTML tags constitute JS Objects
Browser functionality
provides a limited API to Browser functionality
Where did it come from
Originally called LiveScript at Netscape
started out to be a server side scripting language for
providing database connectivity and dynamic HTML
generation on Netscape Web Servers
Netscape decided it would be a good thing for their
browsers and servers to speak the same language so it
got included in Navigator
Netscape in alliance w/Sun jointly announced the
language and its new name Java Script
Because of rapid acceptance by the web community
Microsoft forced to include in IE Browser
Browser compatibility
For the most part Java Script runs the same way in all
popular browsers
There are a number of areas where there are slight
differences in how Java Script will run
There will be a separate set of slides addressing these
differences and making your pages browser neutral.
JavaScript…Java ?
There is no relationship other than the fact that
Java and JavaScript resemble each other (and C++)
syntactically
JavaScript is pretty much the de-facto standard for
client-side scripting (Internet Explorer also
provides VBScript & JScript)
In Netscape browsers there is an API (Live
Connect) that allows JavaScript and Java applets
embedded in the same page to communicate.
What can it be used for
Some pretty amazing things….
Text animation
graphic animation
simple browser based application
HTML forms submission
client-side forms data validation (relieving the server of
this task)
web site navigation
What do I need to get started
A web browser
Netscape Navigator 4.x or later
MS Internet Explorer 3.x or later
A text Editor
Wordpad, Notepad
Vi, Emacs, xemacs
what happens when a browser
loads a website
1. Fetch the HTML page (e.g. index.html)
2. Begin parsing the HTML
3. The parser encounters a <script> tag referencing an
external script file.
4. The browser requests the script file. Meanwhile, the
parser blocks and stops parsing the other HTML on
your page.
5. After some time the script is downloaded and
subsequently executed.
6. The parser continues parsing the rest of the HTML
document.
Step #4 causes a bad user experience. Your website
basically stops loading until you've downloaded
all scripts. If there's one thing that users hate it's
waiting for a website to load.
If your website doesn't load within 2
seconds, people will go to another
website.
The modern approach
Today, browsers support the async and defer attributes
on scripts. These attributes tell the browser it's safe to
continue parsing while the scripts are being
downloaded.
async
<script src="path/to/script1.js" async>
</script>
<script src="path/to/script2.js" async>
</script>
Scripts with the async attribute are executed
asynchronously. This means the script is executed as
soon as it's downloaded, without blocking the browser
in the meantime.
This implies that it's possible to script 2 is downloaded
& executed before script 1.
defer
<script src="path/to/script1.js" defer>
</script>
<script src="path/to/script2.js" defer>
</script>
Document.write(greeter);
var greeter = "say hello"
it is interpreted as this:
var greeter;
console.log(greeter); // greeter is undefined
greeter = "say hello“
We see that using hello outside its block (the curly braces
where it was defined) returns an error. This is
because let variables are block scoped
let can be reassigned and take new value. It creates
a mutable variable.
let is the same as const in that both are blocked-scope.
It means that the variable is only available within its
scope.
JavaScript Operators
Assignment Operators(=,+=,-=,*=,/=):
An assignment operator assigns a value to its left
operand based on the value of its right operand. The
basic assignment operator is equal (=), which assigns
the value of its right operand to its left operand. That
is, x = y assigns the value of y to x.
x += y means x = x + y
x -= y means x = x - y
x *= y means x = x * y
x /= y means x = x / y
x %= y means x = x % y
Arithmetic Operators
Arithmetic operators take numerical values (either
literals or variables) as their operands and return a
single numerical value.
Standard Arithmetic Operators
The standard arthmetic operators are addition (+),
subtraction (-), multiplication (*), and division (/).
These operators work in the standard way.
Modulus (%)
The modulus operator is used as follows:
var1 % var2
The modulus operator returns the first operand
modulo the second operand, that is, var1 modulo var2,
in the statement above, where var1 and var2 are
variables. The modulo function is the remainder of
integrally dividing var1 by var2. For example, 12 % 5
returns 2.
Unary negation (-)
The unary negation operator must precede its
operand. It negates its operand. For example,
x = -x
negates the value of x; that is if x were 3, it would
Bitwise Logical Operators
The bitwise logical operators work conceptually as
follows:
The operands are converted to 32-bit integers, and
expressed a series of bits (zeros and ones).
Each bit in the first operand is paired with the
corresponding bit in the second operand: first bit to
first bit, second bit to second bit, and so on.
The operator is applied to each pair of bits, and the
result is constructed bitwise.
The bitwise operators are:
Bitwise AND & returns a one if both operands are
ones.
Bitwise OR | returns a one if either operand is one.
Bitwise XOR ^ returns a one if one but not both
operands are one.
For example, the binary representation of 9 is 1001, and
the binary representation of 15 is 1111. So, when the
bitwise operators are applied to these values, the
results are as follows:
15 & 9 yields 9 (1111 & 1001 = 1001)
15 | 9 yields 15 (1111 | 1001 = 1111)
15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
Conditional Statements
In JavaScript we have three conditional statements:
if statement - use this statement if you want to
execute a set of code when a condition is true
if...else statement - use this statement if you want to
select one of two sets of lines to execute
switch statement - use this statement if you want to
select one of many sets of lines to execute
If and If...else Statement
You should use the if statement if you want to execute
some code if a condition is true.
Syntax
if (condition) { code to be executed if condition is true }
var i = 0;
do {
i++;
document.writeln("i=" + i + "<br>");
} while (i <= 5);
</script>
Outputi=1
i=2
i=3
i=4
i=5
i=6
While Loop Example
<script type="text/javascript">
var i = 0;
while (i <= 5) {
i++;
document.writeln("i=" + i + "<br>");
};
</script>
Output:i=1
i=2
i=3
i=4
i=5
i=6
Label
The labeled statement can be used with break or
continue statements. It is prefixing a statement with
an identifier which you can refer to.
O/P: ??
User Input
The prompt() method displays a dialog box that
prompts the visitor for input.
A prompt box is often used if you want the user to
input a value before entering a page.
Example:
var name=prompt(“Enter Your Name”);
Document.writeln(“Hello ”+name);
while (1) {
var n = prompt("Please enter a number in the range
0…100");
if (n>=0 && n<=100) break;
document.writeln(n +" is out of range. Try again.");
}
Output:
Arrays
The Array object, as with arrays in other programming
languages, enables storing a collection of multiple
items under a single variable name, and has members
for performing common array operations.
let vegetables = []; // blank array
let fruits = ["Mango", "Apple", "Banana"];// assigned
elements
Console.log(fruits) O/P:
Arrays
One dimensional arrays
var myarray = new Array( )
console.log(+i+"")
}
Array Function
array.concat() method
var arr1 = ['Batman', 'Robin'];
var arr2 = ['Joker', 'Bane'];
var comp = arr1.concat(arr2);
console.log(comp);
array.slice() method
console.log(names.slice(2, 4)); //
console.log(names.slice(1, 5)); //
console.log(names.slice(-2)); //
console.log(names.slice(2, -1)); //
array.includes() method
array.includes(itemToSearch[, fromIndex]) returns a
boolean whether array contains itemToSearch. The
optional argument fromIndex, defaulting to 0,
indicates the index to start searching.
onst numbers = [1, 2, 3, 4, 5];
numbers.includes(2); // => true
numbers.includes(99); // => false
Sample Code:
let names = ['Batman', 'Catwoman', 'Joker', 'Bane',
'Superman', 'Angryman'];
names.sort();
console.log(names);
O/P:
Using Comparator in sort:
log()Returns the natural logarithm (base E) of a
number.
max()Returns the largest of zero or more numbers.
min()Returns the smallest of zero or more numbers
pow()Returns base to the exponent power, that is, base
exponent.
random()Returns a pseudo-random number between
0 and 1.
sqrt()Returns the square root of a number.
Spread syntax
Spread syntax (...)
The spread (...) syntax allows an iterable, such as an
array or string, to be expanded in places where zero or
more arguments (for function calls) or elements (for
array literals) are expected.
Max/Min of array using spread
const arr = [2, 4, 5, 7, 8, 0, 12,
4];
console.log(Math.max(...arr)); //
spread
O/P:12
console.log(Math.min(...arr)); // spread
O/P:0
String Object
The String object lets you work with a series of
characters; it wraps Javascript's string primitive data
type with a number of helper methods.
var val = new String(string);
Methods:
charAt()Returns the character at the specified index.
concat()Combines the text of two strings and returns a
new string.
indexOf()Returns the index within the calling String
object of the first occurrence of the specified value, or
-1 if not found.
slice()Extracts a section of a string and returns a new
string.
split()Splits a String object into an array of strings by
separating the string into substrings.
substr()Returns the characters in a string beginning at
the specified location through the specified number of
characters
toLowerCase()Returns the calling string value
converted to lower case.
toString()Returns a string representing the specified
object.
Object Based not Object Oriented
Javascript treats the browser’s objects as a pre-defined
set of objects to which Javascript provides an API.
Javascript, in addition to being a programming
language, is meant to be a way to program a user’s
browser
Object Hierarchy
window
password submit
Objects
window - the current browser window
window.history - the Netscape history list
window.history.back-move to back page if available
window.document - the html document currently in the browser client
area
history.length- property can be used to get the number of pages in the
session history of the browser for the current window.
window.document.form - a named form or the default form
A few examples...
window.location = “http://www.yahoo.com”
will take you to the specified URL (like a goto)
window.history.back()
back( ) is a method on history
will be like clicking the back button in Nav 3
in Nav 4 will take you back to prev window
window.history.go(1)
takes you back to first URL in history array
window.history.forward();- one step forward
More Example
window.history.go(-2); // Go back two pages
window.history.go(-1); // Go back one page
window.history.go(0); // Reload the current page
window.history.go(1); // Go forward one page
window.history.go(2); // Go forward two pages
The Object Model
It is very important to understand the object model
each object has its own properties, some of which are
read only some of which you can be set directly by
assignment (as location)
each object also has a set of behaviors called methods
Object Event Handlers
Most of the objects that make up the Document Object Model
respond to asynchronous, user generated events through
predefined event handlers that handle the event and transfer
control to a user provided event handling function
Each object has particular events that they will respond to
the way you specify an event handler is by adding an additional
attribute to the HTML tag that specifies the event and the
particular handler
<input name=bt1 type=button value=ok onClick=“acb( );”>
if the button is click the function abc( ) will be run
Alert
The “Alert” function is useful in user notification and debugging of
Javascripts.
<map name=flower>
<area name=top coords=“0,0,200,300 href=“javascript:displayMessage()”
onMouseOver=“self.status=‘when you see this message click your left mouse button’ ;
return true”
onMouseOut=“self.status = ‘’ ; return true”>
onReset
Used with form objects
Methods:
blur( ) * - unselects any selected text
handleEvent( ) *