Basics of Javascript: Unit-3
Prepared by,
Divya
Asst. Prof. ISE dept.
VCET, Puttur
Overview of Javascript,
Object orientation & Javascript,
Syntactic characteristics,
Primitives, operations, &expressions,
Screen output and keyboard input,
Control statements,
Object creation and modification,
Arrays,
Functions,
Constructors,
Pattern matching using regular expressions,
Errors in scripts,
Examples.
1. OVERVIEW OF
JAVASCRIPT
Origins
The official name of the standard language is ECMAScript.
JavaScript can be divided into three parts:
the core, client side, and server side.
The core is the heart of the language, including its operators,
expressions, statements, and subprograms.
Client-side JavaScript is a collection of objects that support
the control of a browser and interactions with users.
Server-side JavaScript is a collection of objects that make the
language useful on a Web server.
OVERVIEW OF
JAVASCRIPT
OVERVIEW OF
JAVASCRIPT
Uses Of Javascript
JavaScript is implemented at 2 ends:
Client end - is embedded in XHTML documents
Server end
JavaScript support DOM [Document Object Model] which enables
JavaScript to access and modify CSS properties and content of any
element of a displayed XHTML document
OVERVIEW OF
JAVASCRIPT
Event-driven Computation Of Javascript
supports user interactions through the XHTML form elements
on the client display
to check the values provided in forms by users
perform input checks at the client side itself which saves both
server time and internet time.
OVERVIEW OF
JAVASCRIPT
Browsers And Xhtml/Javascript Documents
When a JavaScript script is encountered in the document, the browser
uses its JavaScript interpreter to execute the script.
2. OBJECT ORIENTATION AND JAVASCRIPT:
JavaScript is an object-based language
Does not have classes- no class-based inheritance
JavaScript cannot support polymorphism.
It supports prototype-based inheritance
JAVASCRIPT OBJECTS
Objects are collections of properties
Each property is either a data property or a function or method property.
Data properties :
primitive values and references to other objects
JavaScript uses non-object types for some of its simplest types; these nonobject types : primitives.
Strings, Numbers, Booleans, null, undefined
Objects are variables too.
var car = "Fiat";
The objects are written as name:value pairs
var car = {type:"Fiat", model:500, color:"white"};
The name : values pairs (in JavaScript objects) are called properties.
Object Properties Accessing :
objectName.propertyName
Object Methods
Methods are stored in properties as function definitions.
objectName.methodName()
3. GENERAL SYNTACTIC CHARACTERISTICS
Inline (embedded) JavaScript code:
<input type="button" id="hello" value="Hello" onClick = "window.alert('Hello
World!')">
Internal JavaScript code:
<script language="JavaScript">
<!-- // hide from the older browsers [The actual script commands] //--> // stop
hiding
</script>
External JavaScript code:
<script language="JavaScript" src="examples/externaljs.js"></script>
Comments: // or /* .*/
Identifiers/names, must begin with a letter, an underscore
( _ ), or a dollar sign ($).
4. PRIMITIVES, OPERATIONS, AND EXPRESSIONS
1.
.
primitive types
JavaScript has five primitive types: Number, String, Boolean, Undefined, and
Null.
JavaScript includes predefined objects
EG: Number, String, Boolean etc
var x = false;
Boolean(x);
.
var y = new String("John");
2. Numeric And String Literals
All numeric literals are values of type Number.
Integer literals :Integer literals are strings of digits.
var x = 0xFF;
// x will be 255 hexadecimal
Floating-point literals
var y = 123e-5;
string literal
You\re the most lovely person I\ve ever met
D:\\bookfiles
-------------------------------------------------------- 3.
Null :
Undefined
var p=null;
var p1;
alert(p) //null
alert(p1) //undefined
Boolean
OTHER PRIMITIVE TYPES :
4. DECLARING VARIABLES
A variable that has been declared but
not assigned a value, has the value
undefined.
5. NUMERIC OPERATORS
6. THE Math OBJECT
Math.max(0, 150, 30, 20, -8)
Math.round(5.3); //5
Math.sqrt(9);
Write js program to accept 3 numbers using prompt and find the largest
of three using alert method. Use predefined function Math.max.
7. The Number Object
<html>
<head><script language="JavaScript">
<!--//
function sq()
{ var a=prompt( "Enter first number " , "" );
a=parseInt(a);
var b=prompt( "Enter first number " , "" );
b=parseInt(b);
var c=prompt( "Enter first number " , "" );
b=parseInt(b);
var max=Math.max(a,b,c);
alert("largest of three input number:"+max);
} //-->
</script></head>
<body><form><input type="button" value="sq" onclick="sq();"/>
</form>
</body></html>
<html><head>
<script language="JavaScript">
<!--//
var val = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
document.write ("Value of Number.MAX_VALUE : " + val +"<br />");
document.write ("Value of smallestNum : " + smallestNum+"<br />" );
document.write ("Value of infiniteNum : " + infiniteNum +"<br />");
document.write ("Value of negInfiniteNum : " + negInfiniteNum +"<br />");
var dayOfMonth=231;
if (dayOfMonth < 1 || dayOfMonth > 31)
{
dayOfMonth = Number.NaN
alert("Day of Month must be between 1 and 31.")
}
//-->
</script></head><body></body></html>
8. The String Catenation Operator : +
9. Implicit Type Conversions :coercions
Example1: August + 1977 // August 1997
Example2: 7 * 3 // 21
10. Explicit Type Conversions :
To string conversion : String constructor string() , toString()
The global method Number() can convert strings to numbers.
The parseInt() function parses a string and returns an integer.
var e = parseInt("60") //60
var g = parseInt("He was 40") //NAN
The parseFloat() function parses a string and returns a floating
point number.
var c = parseFloat("10.33") //10.33
parseFloat("He was 40") //NAN
11.String Properties And Methods
var str = George;
var len = str.length; //now, len=6
var str = George;
str.charAt(2) is o
str.indexOf(r) is 3
str.substring(2, 4) is org
str.toLowerCase() is george
12. THE typeof OPERATOR
The typeof operator returns the type of its single operand
typeof "john
//string
Var x;
typeof(x) //undefined
13. Assignment Statements
. a
+= 7; means the same as a = a + 7;
var x = 10;
x /= 5;
//2
THE Date OBJECT :
var today = new Date();
14.
5. SCREEN OUTPUT AND KEYBOARD INPUT
<html><head><script language="JavaScript">
<!--//
function myFunction() {
alert("Hello! I am an alert box!!");
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.write(person); }
confirm("Do you want to continue this download?");
}
//-->
</script></head>
<body><form><button onclick="myFunction()">Try it</button>
</form></body></html>
A table of numbers from 5-15 and their squares , cubes using alert
The quadratic equation is given by:
ax2 + bx + c = 0
The expression inside the square root is called discriminant and is
denoted by :
= b2 - 4ac
When >0, there are 2 real roots
x1=(-b+)/(2a) and x2=(-b-)/(2a).
Create an XHTML and JavaScript to compute the
real roots of a given quadratic equation
6. CONTROL STATEMENTS :
1. Control Expressions :
Relational operators
2. Selection Statements
Write
a javacript code:
To find reverse of a given number.
..\web_exercises
\chapter4_js\4.14reverse.html
Use if and if-else statement to check
number is prime or not
..\..\web_lab\js\prime_wrong.html
..\..\web_lab\js\prime.html
N==1 //not prime
N==2// prime
For(x=2; x<n;x++)
{If(n%x==0)
Return not prime
}
Else
prime
3. switch Statements
<html><head><script language="JavaScript">
<!--//
var bs=prompt(" select border size");
switch(bs) {
case "1": document.write("<table>"); break;
case "2": document.write("<table border='1'>"); break;
Case "3": document.write("<table border='8'>"); break;
default: document.write("invalid choice");break;
}
document.write("<caption>table1</caption>");
document.write("<tr><th>A</th><th>B</th>");
document.write("<tr><td>a</td><td>b</td></table>");
//-->
</script></head><body></body></html>
4. LOOP STATEMENTS
while
for and do-while
1. Using document.write(), write code that displays the
results of the 12 times table. Its output should be the
results of the calculations.
..\..\web_lab\js\12_tables.html
2. To print factorial of a number
..\..\web_lab\js\factorial.html
7. OBJECT CREATION AND MODIFICATION
new operator creates a blank object: no properties.
constructor
var my_object = new Object();
The variable my_object references the new object
var my_car = {make: Ford, model: Contour SVT};
Properties can be accessed in two ways.
var prop1 = my_car.make;
var prop2 = my_car[make];
the variables prop1 and prop2 both have the value ?.
The number of properties in a JavaScript object is dynamic
delete my_car.model;
loop statement, for-in, for listing the properties of an object.
for (var a in my_car )
document.write(Name:, a, value: my_car[a]);
8. ARRAYS
1.
a.
b.
Array OBJECT CREATION
Var a=new Array(1, 2, three);
Var b=new Array(100);
var my_list_2 = [1, 2, three, four];
CHARACTERISTICS OF Array OBJECTS
a[47] = 2222;
the new length of my_list will be 48?
2.
length property:
my_list_2.length = 1002;
Array example: This script has an array of names, which are in
alphabetical order. It uses prompt to get new names, one at a time,
and inserts them into the existing array
<html><head><script language="JavaScript">
<!--//
var name_list = new Array("baby", c-man", "Kasper, "Michael", "Roberto");
var new_name, index, last;
while (new_name = prompt("Please type a new name", "")) {
last = name_list.length - 1;
while (last >= 0 && name_list[last] > new_name) {
name_list[last + 1] = name_list[last];
last--;
}
name_list[last + 1] = new_name;
document.write("<p><b>The new name list is:</b> , "<br />");
for (index = 0; index < name_list.length; index++)
document.write(name_list[index], "<br />");
document.write("</p>");
}
//-->
</script></head><body></body></html>
3. Array Methods
Join Method
Reverse Method no parameter
Sort Method arrange-no parameter
Concat Method: to the end of the Array object
Slice Method : returns 4 and 6
Slice(2) //6, 8,10
toString method: These strings are catenated, separated by commas.
push, pop, unshift, and shift methods
shift and unshift methods
var deer = list.shift(); // deer is now Dasher
list.unshift(Dasher); // This puts Dasher back on list
To find number of zeros, negatives and positives in a
given array using switch statement
..\web_exercises
\chapter4_js\4.11_array_switch.html
FUNCTIONS
Return statement: returns control to the function caller..
One or more return statements in function body
function fun()
{
Alert(hi)
}
//no return or (doesnot include any expression) is undefined
LOCAL VARIABLES
The scope of a variable is the range of statements over which it is visible.
used only within a function ---have local scope
global variable scopethey are visible in the entire XHTML document.
If a variable that is defined both --- local variable has precedence
PARAMETERS
..\..\Web
Notes by Divya .pdf
The
parameter values that appear in a call to a function are called
actual parameters.
The parameter names in calls to the function, are called formal
parameters.
JavaScript
uses the pass-by-value parameter-passing method.
In the function, excess actual parameters that are passed are
ignored;
excess formal parameters are set to undefined.
arguments.length - can determine the number of actual
parameters that were passed.
9 FUNCTIONS : Sort Method, Revisited
<html>
<head>
<script language="JavaScript">
<!--//
var letters = ["Rs","Os","Fs","Ls"];
var numbers = [28,5,34];
letters.sort();
numbers .sort();
alert(letters);
alert(numbers );
numbers .sort(function number_sort(a, b){
alert(numbers ); //ascending
//-->
</script></head><body></body></html>
return a - b; });
10 Median of an array:
<html><head><script language="JavaScript"> <!--//
function median(list) {
list.sort(function (a, b) {return a - b;});
Math.floor(1.6);
//1
var list_len = list.length;
//6 or 7
Math.round(1.6)
//2
if ((list_len % 2) == 1)
//0 or 1
return list[Math.floor(list_len / 2)];
else
return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2); //even
}
var my_list_1 = [8, 3, 9, 1, 4, 7];
var my_list_2 = [10, -2, 0, 5, 3, 1, 7];
var med = median(my_list_1);
document.write("Median of [", my_list_1, "] is: ", med, "<br />");
med = median(my_list_2);
document.write("Median of [", my_list_2, "] is: ,
med, "<br />");
//--></script></head><body></body></html>
i) To print the position in the string of the leftmost
vowel.
..\web_exercises\chapter4_js\4.10_vowel.html
..\web_exercises
\chapter4_js\4.8_remove_zero
s.html
1.
Given array must be modified to remove all zero values.
. The
splice() method adds/removes items to/from an array, and
returns the removed item(s).
arr.splice(i, 1);
Index: An integer that specifies at what position to
add/remove items
howmany. The number of items to be removed. If set to 0,
no items will be removed
Input: Array of numbers
Output: average of each rows of matrix
..\web_exercises\chapter4_js\4.13_matrix.html
input your sentence
2. Sort based on user input(ascending or descending)
1. The split() method is used to split a string into an array of
substrings, and returns the new array.
2. ..\web_exercises\chapter4_js\4.7_sort_userinput.html
1.
11.
In JavaScript, almost "everything" is an object.
Booleans, Strings ,Numbers can be objects (or primitive data treated as
objects)
Dates are always objects
Maths are always objects
Arrays are always objects
Functions are always objects....
Objects are variables too. But objects can contain many values.
var person = "John Doe";
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The named values, in JavaScript objects, are called properties.
var
person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Above
creates a single object.
11.
With JavaScript, you can define and create your own objects.
create and initialize the properties of newly created objects.
When the constructor is called, this is a reference to the newly
created object.
The this variable is used to construct and initialize the
properties of the object.
<html><head><script language="JavaScript"> <!--//
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
myFather.display();
myMother.display();
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.display=display;
}
function display(){
document.write("father is " + this.age + ". mother is " +
this.firstName+"<br>");
}
//-->
</script></head><body></body></html>
12
PATTERN MATCHING BY USING
REGULAR EXPRESSIONS
2 approaches:
RegExp
String object
search method returns the position in the String object
(through which it is called) at which the pattern matched
The position of the first character in the string is 0.
If there is no match, search returns 1.
Var str=hi hello;
Var position=str.search(/hi/); //0
CHARACTER AND CHARACTER-CLASS PATTERNS
Metacharacters are characters that have special meanings in some contexts in
patterns.
The following are the pattern metacharacters:
\|()[]{}^$*+?.
Metacharacters can themselves be matched by being immediately preceded
by a backslash.
A period matches any character except newline.
Example: /snow./ matches snowy, snowe, and snowd
Example: /3\.4/ matches 3.4. but /3.4/ would match 3.4 and 374, among
others.
Example: [abc] matches a , b & c
Example: [a-h] matches any lowercase letter from a to h
Example: [^aeiou] matches any lowercase letter except a, e, i, o & u
/^pearl/
/gold$/
Pattern Modifiers
The i modifier makes the letters in the pattern match either uppercase
or lowercase letters in the string.
/Apple/i
matches APPLE, apple, APPle,
The x modifier allows white space to appear in the pattern.
OTHER PATTERN-MATCHING METHODS OF String
var str = Fred, Freddie, and Frederica were siblings;
str.replace(/Fre/g, Boy);
Matches returns array [4, 3].
var str = grapes:apples:oranges; var fruit = str.split(:);
/^\w+/
[\.-]?
([\.-]?\w+)*
Simple regular expression to validate email address
personal_info@domain
The personal_info part contains the following ASCII characters.
Uppercase (A-Z) and lowercase (a-z) English letters.
Digits (0-9).
Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
Character . ( period, dot or fullstop) provided that it is not the first or
last character and it will not come one after the other.
domain name [for example com, org, net, in, us, info] part contains
letters, digits, hyphens and dots.
[email protected] [email protected] [email protected]var reg =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
\.\w{2,3}----------It matches a . followed by two or three word characters,
e.g., .edu, .org, .com, .uk, .us, .co etc.
13
1.
2.
3.
Write a Javascript that contains, a function named test_
phoneno_num, which tests the phone number of the format ddd
dddd <091 - 8256> and display whether the given number is valid
or not using document.write.
..\..\web_lab\js\phone_num_validate.html
Write a JavaScript to validate the name, the name should be
entered using prompt. The first and last name should not be more
than 10 characters and middle name must contain only initial. If
so display validation corresponding name. The format is the
first_name, second_name and third_name. There should be single
white space between First_name, Second_name and third_name.
14 ERRORS IN SCRIPTS
Spot the error..
var userAge = prompt(Please enter your age);
if (userAge = 0);
{
alert(So youre a baby!);
}
else if ( userAge < 0 | userAge > 200)
alert(I think you may be lying about your age);
else
{
alert(Thats a good age);
}
ERRORS IN SCRIPTS
Write XHTML document and java script code to
implement the following :
i) To count the number of names in the given array
that end in either "ie" or "y".
ii) ..\web_exercises\chapter4_js\4.9_ie_y.html
True if the string has the form:
string1, string2 letter
string1, string2-------must be lowercase except the first letter
letter-------------must be uppercase
..\web_exercises\chapter4_js\4.12_stringpattern.html
Venkatesh Anant Naik,
Prasanna Kumari M, Pavan K