Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Javascript: Language Fundamentals I

This document provides an overview of client-side and server-side programming with JavaScript. It discusses that client-side programs run in the web browser and do not require traveling through the network, which reduces burden on the network and increases performance. Server-side programs run on the web server and require a connection to the server. It also summarizes the differences between static and dynamic web pages and provides examples of JavaScript functions like alert(), confirm(), and prompt().
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Javascript: Language Fundamentals I

This document provides an overview of client-side and server-side programming with JavaScript. It discusses that client-side programs run in the web browser and do not require traveling through the network, which reduces burden on the network and increases performance. Server-side programs run on the web server and require a connection to the server. It also summarizes the differences between static and dynamic web pages and provides examples of JavaScript functions like alert(), confirm(), and prompt().
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 53

JavaScript

Language Fundamentals I

1-Mar-19
Server-Side Programs

 Server- Side programs run at server. user must be


connected to the Web server to run the server-side
script.
 user need to travel through the network to execute this
program.
 only the programmer can create or alter the script
 the system administrator has to be concerned about
users continually accessing the server and potentially
overloading the system

2
Client-Side Programs
 It executes in the web browser with the help of browser
interpreters. That’s why user did not need to travel
through the network to execute this script.
 It reduces the burden on network and increases the
performance of application
 can be tested locally without first uploading it to a Web
server
 are likely to be more responsive to the user
 can never completely replace server-side scripts

3
Client-side programming Server-side programming
1. It provides the front-end to a web site 1. It provides the back-end to a web site
for handling client requests by for performing all the processing
providing basic validations and related to client requests on the web
calculations. server
Eg: mobile no validation, e-mail Eg: data base validations such as valid
validation user or not

2. It is used to perform calculations of 2. It handles the functions such as data


sum, multiply and divide. base querying, database handling and
database manipulations.

3. It is interpreted by web browser 3. It is executed by web server

4. Client-Side Scripts are visible in the 4. Server-side scripts are not visible to the
client’s computer. client. The client can view only the output
of the program.

4
Static web page
 Static Web pages display the exact same information
whenever anyone visits it. Static Web pages do not
have to be simple plain text. They can feature
detailed multimedia design and even videos.
However, every visitor to that page will be greeted
by the exact same text, multimedia design or video
every time he visits the page until you alter that
page's source code.

5
Dynamic web page
 Dynamic Web pages are capable of producing
different content for different visitors from the same
source code file. The website can display different
content based on what operating system or browser
the visitor is using, whether she is using a PC or a
mobile device, or even the source that referred the
visitor. A dynamic Web page is not necessarily better
than a static Web page. The two simply serve
different purposes.

6
Introduction to JavaScript
 JavaScript is an interpreted programming or script
language from Netscape corporation in 1995. The original
name is “Live Script”
 JavaScript is used in Web site development to such things
as:
 Client side validations
 automatically change a formatted date on a Web page
 cause a linked-to-page to appear in a popup window
 cause text or a graphic image to change during a mouse
rollover

7
features of JavaScript
 Scripting language: A scripting language is a simple
programming language designed to enable computer
users to write useful programs easily.
 Object -based language. An object-oriented program is
a collection of individual objects that perform different
functions, rather than a sequence of statements that
collectively perform a specific task.
 Event driven: the user is in control the web page for
move the mouse or not moves the mouse.

8
 Create pages dynamically
Based on the user's choices, the date, or
other external data, JavaScript can produce pages
that are customized to the user.
 Interact with the user
It can do some processing of forms and can
validate user input when the user submits the form.
 Platform-independent: - JavaScript programs are
designed to run within HTML documents, they are not
tied to any specific hardware platform or operating
system.
9
Writing a JavaScript Program

 The Web browser runs a JavaScript program


when the Web page is first loaded, or in response
to an event.
 JavaScript programs can either be placed directly
into the HTML file or they can be saved in
external files.
 placing a program in an external file allows
you to hide the program code from the user
 source code placed directly in the HTML file
can be viewed by anyone
10
Using JavaScript in a browser
 JavaScript code is included within <script> tags:
 <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
 Notes:
 The type attribute is to allow you to use other scripting
languages (but JavaScript is the default)
 This simple code does the same thing as just putting
<h1>Hello World!</h1> in the same place in the HTML
document
 The semicolon at the end of the JavaScript statement is
optional
 You need semicolons if you put two or more statements on the
same line
 It’s probably a good idea to keep using semicolons
11
Writing a JavaScript Program

 A JavaScript program can be placed anywhere


within the HTML file.
 Many programmers favor placing their
programs between <head> tags in order to
separate the programming code from the Web
page content and layout.
 Some programmers prefer placing programs
within the body of the Web page at the location
where the program output is generated and
displayed.
12
A Simple Script
<html>
<head><title>First JavaScript
Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
</html> Inside your_source_file.js
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");

 Use the src attribute to include JavaScript codes


from an external file.
 The included code is inserted in place.
Functions
 Functions should be defined in the <head> of an
HTML page, to ensure that they are loaded first
 The syntax for defining a function is:
function name(arg1, …, argN) { statements }
 The function may contain return value; statements
 Any variables declared within the function are local to it
 The syntax for calling a function is just
name(arg1, …, argN)
 Simple parameters are passed by value, objects are
passed by reference

15
JavaScript buitin functions
 With functions, you can give a name to a whole
block of code, allowing you to reference it from
anywhere in your program. JavaScript has built-in
functions for several predefined operations. Here are
three some functions.
• alert("message")
• confirm("message")
• prompt("message")

16
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");

 Display a message in a dialog box.


 The dialog box will block the browser.

var answer = confirm("Are you sure?");

 Display a message in a dialog box with two buttons: "OK"


or "Cancel".
 confirm() returns true if the user click "OK".
Otherwise it returns false.
prompt()
prompt("What is your student id number?");
prompt("What is your name?”, "No name");

 Display a message and allow the user to enter a value


 The second argument is the "default value" to be displayed
in the input textfield.
 Without the default value, "undefined" is shown in the
input textfield.

 If the user click the "OK" button, prompt() returns the


value in the input textfield as a string.
 If the user click the "Cancel" button, prompt() returns
null.
20
Mouse evevent

21
Primitive data types
 JavaScript has three “primitive” types: number, string, and
boolean
 Everything else is an object
 Numbers are always stored as floating-point values
 Hexadecimal numbers begin with 0x
 Some platforms treat 0123 as octal, others treat it as decimal
 Since you can’t be sure, avoid octal altogether!
 Strings may be enclosed in single quotes or double quotes
 Strings can contains \n (newline), \" (double quote), etc.
 Booleans are either true or false
 0, "0", empty strings, undefined, null, and NaN are false ,

other values are true

22
Variables
 Variables are declared with a var statement:
 var pi = 3.1416, x, y, name = "Dr. Dave" ;
 Variables names must begin with a letter or
underscore
 Variable names are case-sensitive
 Variables are untyped (they can hold values of any
type)
 The word var is optional (but it’s good style to use it)
 Variables declared within a function are local to
that function (accessible only within that
function)
 Variables declared outside a function are global
(accessible from anywhere on the page) 23
To declare a varible in java script

var varname;

var x = 5;

var y = 6;

var z = x + y;

In this example, x, y, and z, are variables:

24
<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var x=100;
var y=200; Output : 300
document.write(x+y);
Suppose y=“200”
</SCRIPT>
Output= 100200
</BODY>
</HTML>

25
parseInt(), parseFloat(), ….etc
<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var x=100;
var y="200";
document.write(x+parseInt(y));
</SCRIPT>
</BODY> Output : 300
</HTML>

26
Loacal variables and global variables
 Local Variables : Variables declared inside a
function.
The scope of local variables is up to that
function.

Global Variables: Variables declared out side of all the


functions. We can access this variable from any
location

27
arrays
 Array is a collection of heterogeneous data types.
 Java Script is loosely typed language that’s why it
can store any type of values in variables.
 In Java Script array is an object.

The declaration is
var arr=new Array(val1,valu2,val3,…..);
Eg: var arr=new Array(10, 20, 30);
alert(arr); output: 10, 20, 30
alert(arr[0]); output: 10

28
var arr=new Array(10,”amar”, 20.5);
ot
var arr=new Array();
arr[0]=10;
arr[1]=“amar”;
arr[2]=20.5;

29
Operators, I

 Because most JavaScript syntax is borrowed from C (and is


therefore just like Java), we won’t spend much time on it
 Arithmetic operators (all numbers are floating-point):
+ - * / % ++ --
 Comparison operators:
< <= == != >= >
 Logical operators:
&& || ! (&& and || are short-circuit operators)
 Bitwise operators:
& | ^ ~ << >> >>>
 Assignment operators:
+= -= *= /= %= <<= >>= >>>= &= ^= |=

30
Operators, II
 String operator:
+
 The conditional operator:
condition ? value_if_true : value_if_false
 Special equality tests:
 == and != try to convert their operands to the same type
before performing the test
 === and !== consider their operands unequal if they are of
different types
 Additional operators (to be discussed):
new typeof void delete

31
Comments
 Comments are as in C or Java:
 Between // and the end of the line
 Between /* and */
 Java’s javadoc comments, /** ... */, are treated just the
same as /* ... */ comments; they have no special
meaning in JavaScript

32
Statements, I

 Most JavaScript statements are also borrowed from C


 Assignment: greeting = "Hello, " + name;
 Compound statement:
{ statement; ...; statement }
 If statements:
if (condition) statement;
if (condition) statement; else statement;
 Familiar loop statements:
while (condition) statement;
do statement while (condition);
for (initialization; condition; increment) statement;

33
Statements, II
 The switch statement:
switch (expression) {
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
 Other familiar statements:
 break;
 continue;
 The empty statement, as in ;; or { }

34
<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
document.write("<h2>Table of Factorials</h2>");
for(i = 1, fact = 1; i < 10; i++, fact *= i)
{
document.write(i + "! = " + fact);
document.write("<br>");
}
</SCRIPT>
</BODY>
</HTML>

35
Java Script Objects
1.Date object

2.Math object

3.String object

36
Creating Date object
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds,
milliseconds)

37
Date object
getTime() getMinutes()
getDate() getUTCMinutes()
getSeconds()
getUTCDate() getUTCSeconds()
getDay() setDate(value)
getUTCDay()
getHours()
getUTCHours()
getMilliseconds()
getUTCMilliseconds()

38
Date()
Returns today's date and time
getDate()
Returns the day of the month for the specified date
according to local time.
getDay()
Returns the day of the week for the specified date
according to local time.
getFullYear()
Returns the year of the specified date according to local
time
39
getHours()
Returns the hour in the specified date according to local
time.
getMilliseconds()
Returns the milliseconds in the specified date according to
local time.
getMinutes()
Returns the minutes in the specified date according to
local time.
getMonth()
Returns the month in the specified date according to local
time 40
getSeconds()
Returns the seconds in the specified date according to
local time.
getTime()
Returns the numeric value of the specified date as the
number of milliseconds since January 1, 1970, 00:00:00
UTC.
getTimezoneOffset()
Returns the time-zone offset in minutes for the current
locale.
getUTCDate()
Returns the day (date) of the month in the specified date 41
settDate()
Sets the day of the month for a specified date according to
local time
setFullYear()
Sets the full year for a specified date according to local
time.
setHours()
Sets the hours for a specified date according to local time
setMilliseconds()

Sets the milliseconds for a specified date according to
local time
42
setMinutes()
Sets the minutes for a specified date according to local time.
setMonth()
Sets the month for a specified date according to local time
setSeconds()
Sets the seconds for a specified date according to local time.
setTime()
Sets the Date object to the time represented by a number of
milliseconds since January 1, 1970, 00:00:00 UTC.

43
setUTCDate()
Sets the day of the month for a specified date according to
universal time.
setUTCFullYear()
Sets the full year for a specified date according to
universal time.
setUTCHours()
Sets the hour for a specified date according to universal
time.
setUTCMilliseconds()
Sets the milliseconds for a specified date according to
universal time. 44
Math Object
max(x,y,z,...,n)
abs(x) min(x,y,z,...,n)
acos(x) pow(x,y)
random()
asin(x) round(x)
atan(x) sin(x)
ceil(x) sqrt(x)
tan(x)
cos(x)
exp(x)
floor(x)
log(x)
max(x,y,z,...,n)
45
String Object
charAt()
concat()
match()
replace()
search()
substr()
toLowerCase()
toUpperCase()

46
<html> Defining objects
<body>
<p>Creating and using an object method.</p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

47
document.write(person.firstName);
document.write(person.id);
document.write(person.fullName());

</script>
</body>
</html>

48
Reading the data from html form

49
JavaScript is not Java
 By now you should have realized that you already know a
great deal of JavaScript
 So far we have talked about things that are the same as in Java
 JavaScript has some features that resemble features in Java:
 JavaScript has Objects and primitive data types
 JavaScript has qualified names; for example,
document.write("Hello World");
 JavaScript has Events and event handlers
 Exception handling in JavaScript is almost the same as in Java
 JavaScript has some features unlike anything in Java:
 Variable names are untyped: the type of a variable depends on the
value it is currently holding
 Objects and arrays are defined in quite a different way
 JavaScript has with statements and a new kind of for statement

50
Object literals
 You don’t declare the types of variables in JavaScript
 JavaScript has object literals, written with this syntax:
 { name1 : value1 , ... , nameN : valueN }

 Example (from Netscape’s documentation):


 car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
 The fields are myCar, getCar, 7 (this is a legal field name) , and

special
 "Saturn" and "Mazda" are Strings

 CarTypes is a function call

 Sales is a variable you defined earlier

 Example use: document.write("I own a " + car.myCar);

51
Three ways to create an object
 You can use an object literal:
 var course = { number: "CIT597", teacher: "Dr. Dave" }
 You can use new to create a “blank” object, and add fields to it
later:
 var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
 You can write and use a constructor:
 function Course(n, t) { // best placed in <head>
this.number = n; // keyword "this" is required, not optional
this.teacher = t;
}
 var course = new Course("CIT597", "Dr. Dave");

52
The End

53

You might also like