Javascript Fund1
Javascript Fund1
Table of Content
• Brief Introduction
• Embedding JavaScript in HTML
• Statements/Expressions
• Functions - Defining - Calling
• Event Handlers
Introduction
• JavaScript is Netscape’s cross-platform,
object-based scripting language for client
and server applications
• JavaScript is not Java. They are similar in
some ways but fundamentally different in
others.
JAVASCRIPT
• JavaScript is used in millions of Web
pages to improve the design, validate
forms, detect browsers, create cookies,
and much more.
• JavaScript is the most popular scripting
language on the internet, and works in all
major browsers, such as Internet
Explorer, Mozilla, Firefox, Netscape,
Opera.
WHAT IS JAVASCRIPT?
• JavaScript was designed to add interactivity to HTML
pages
• JavaScript is a scripting language (a scripting language is a
lightweight programming language)
• A JavaScript consists of lines of executable computer code
• A JavaScript is usually embedded directly into HTML
pages
• JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license
JavaScript Types
There’re 2 types:
* Navigator’s JavaScript, also called client-
side JavaScript
* LiveWire JavaScript, also called server-side
JavaScript
Embedding JavaScript in HTML
• By using the SCRIPT tag
• By specifying a file of JavaScript code
• By specifying a JavaScript expression as
the value for an HTML attribute
• By using event handlers within certain other
HTML tags
SCRIPT Tag
The <SCRIPT> tag is an extension to HTML
that can enclose any number of JavaScript
statements as shown here:
<SCRIPT>
JavaScript statements...
</SCRIPT>
A document can have multiple SCRIPT tags,
and each can enclose any number of
JavaScript statements.
How to Put a JavaScript Into an
HTML Page?
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Hiding scripts in comment tags
<SCRIPT>
<!-- Begin to hide script contents from old
browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
Famous “Hello World” Program
<html>
<body>
<script language="JavaScript">
document.write(“Hello, World!”)
</script>
</body>
</html>
JavaScript code in a file
• The SRC attribute of the <SCRIPT> tag lets
you specify a file as the JavaScript source
(rather than embedding the JavaScript in the
HTML).
• This attribute is especially useful for
sharing functions among many different
pages.
Example
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
………….
</SCRIPT>
</HEAD>
<BODY>
………….
Statements
• Conditional Statement: if…else
if (condition) {
statements1
} else {
statements2
}
Loop Statements
• for statement:
for ([initial-expression]; [condition]; [increment-
expression]) {
statements
}
• while statement:
while (condition) {
statements
}
Expressions
• An expression is any valid set of literals,
variables, operators, and expressions that
evaluates to a single value; the value can be
a number, a string, or a logical value.
Expressions (cont’d)
• JavaScript has the following types of
expressions:
* Arithmetic: evaluates to a number, for
example 3.14159
* String: evaluates to a character string, for
example, "Fred" or "234"
* Logical: evaluates to true or false
Datatype conversion
• JavaScript is a loosely typed language. That
means you do not have to specify the data type of
a variable when you declare it, and data types are
converted automatically as needed during script
execution. So, for example, you could define a
variable as follows: var answer = 42
• And later, you could assign the same variable a
string value, for example, answer = "Thank
you"
Datatype conversion (cont’d)
In expressions involving numeric and string
values, JavaScript converts the numeric
values to strings. For example, consider the
following statements:
x = "The answer is " + 42
y = 42 + " is the answer."
Defining and calling Functions
• Functions are one of the fundamental building
blocks in JavaScript. A function is a JavaScript
procedure--a set of statements that performs a
specific task. A function definition has these
basic parts:
* The function keyword.
* A function name.
* A comma-separated list of arguments to the function in
parentheses.
* The statements in the function in curly braces.
Functions example
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function square(number) {
return number * number
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
document.write("The function returned ", square(5), ".")
</SCRIPT>
<P> All done.
</BODY>
Event handlers
JavaScript applications in the Navigator are
largely event-driven. Events are actions that
occur usually as a result of something the
user does. For example, clicking a button is
an event, as is changing a text field or
moving the mouse over a hyperlink. You
can define event handlers, such as
onChange and onClick, to make your
script react to events.
Event Handler (cont’d)
Here’re a few event handler function
onAbort: user aborts the loading
onClick: user clicks on the link
onChange: user changes value of an element
onFocus: user gives input focus to window
onLoad: user loads page in Navigator
An example of event handler
<HEAD> <SCRIPT>
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
else
alert("Please come back again.")
}
</SCRIPT> </HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
Variables
• A variable is a name associated with a piece
of data
• Variables allow you to store and manipulate
data in your programs
• Think of a variable as a mailbox which
holds a specific piece of information
Variables
• In JavaScript variables • Example:
are created using the
keyword var var x = 10;
var y = 17;
var q = “17”;
Arrays
• An array is a compound data type that
stores numbered pieces of data
• Each numbered datum is called an element
of the array and the number assigned to it is
called an index.
• The elements of an array may be of any
type. A single array can even store elements
of different type.
Creating an Array
• There are several different ways to create an
array in JavaScript
• Using the Array() constructor:
- var a = new Array(1, 2, 3, 4, 5);
- var b = new Array(10);
• Using array literals:
- var c = [1, 2, 3, 4, 5];
Accessing Array Elements
• Array elements are accessed using the [ ]
operator
• Example:
– var colors = [“red”, “green”, “blue”];
– colors[0] => red
– colors[1] => green
Adding Elements
• To add a new element to an array, simply
assign a value to it
• Example:
var a = new Array(10);
a[50] = 17;
Array Length
• All arrays created in JavaScript have a
special length property that specifies how
many elements the array contains
• Example:
– var colors = [“red”, “green”, “blue”];
– colors.length => 3
Primitive Data Types versus
Composite Data Types
• Variables for primitive data types hold the
actual value of the data
• Variables for composite types hold only
references to the values of the composite
type
Variable Names
• JavaScript is case sensitive
• Variable names cannot contain spaces,
punctuation, or start with a digit
• Variable names cannot be reserved words
Programming Tips
• It is bad practice to change the implicit type
of a variable. If a variable is initialized as a
number, it should always be used as an
number.
• Choose meaningful variable names
Statements
• A statement is a Examples:
section of
JavaScript that can Last_name = “Dunn”;
be evaluated by a x = 10 ;
Web browser
y = x*x ;
• A script is simply a
collection of
statements
Programming Tips
• It is a good idea to • Recommended:
a = 3;
end each program b = 4;
statement with a • Acceptable:
semi-colon; a = 3; b = 4;
Although this is not • Wrong:
necessary, it will a =
3;
prevent coding
errors
Operators
+ Addition == Equality
- Subtraction != Inequality
* Multiplication ! Logical NOT
/ Division && Logical AND
% Modulus || Logical OR
++ Increment ? Conditional
- - Decrement Selection
Aggregate Assignments
• Aggregate assignments provide a shortcut
by combining the assignment operator with
some other operation
• The += operator performs addition and
assignment
• The expression x = x + 7 is equivalent to
the expression x += 7
Increment and Decrement
• Both the increment (+ x = 10; x = 10;
+) and decrement (- y = ++ x; z = x ++;
-) operator come in
two forms: prefix and
y = 11
postfix
z = 10
• These two forms yield
different results x = 11 in both cases
Control Structures
• There are three basic types of control
structures in JavaScript: the if statement,
the while loop, and the for loop
• Each control structure manipulates a block
of JavaScript expressions beginning with
{ and ending with }
The If Statement
• The if statement If ( x = = 10)
allows JavaScript { y = x*x;
programmers to a }
make decision
else
• Use an if statement
whenever you come to { x = 0;
a “fork” in the }
program
Repeat Loops
• A repeat loop is a group of statements that
is repeated until a specified condition is met
• Repeat loops are very powerful
programming tools; They allow for more
efficient program design and are ideally
suited for working with arrays
The While Loop
• The while loop is used count = 0;
to execute a block of while (count <= 10) {
code while a certain document.write(count);
condition is true
count++;
}
The For Loop
• The for loop is used when there is a need to
have a counter of some kind
• The counter is initialized before the loop
starts, tested after each iteration to see if it
is below a target value, and finally updated
at the end of the loop
Example: For Loop
// Print the numbers 1 i=1 initializes the counter
through 10
i<=10 is the target
for (i=1; i<= 10; i++) value
document.write(i);
i++ updates the
counter at the end
of the loop
Example: For Loop
<SCRIPT <SCRIPT
LANGUAGE= LANGUAGE=
"JavaScript"> "JavaScript">
document.write("1");
document.write("2");
for (i=1; i<=5; i++)
document.write("3");
document.write(i);
document.write("4");
document.write("5");
</SCRIPT>
Functions
• Functions are a collection of JavaScript
statement that performs a specified task
• Functions are used whenever it is necessary
to repeat an operation
Functions
• Functions have inputs and outputs
• The inputs are passed into the function and
are known as arguments or parameters
• Think of a function as a “black box” which
performs an operation
Defining Functions
• The most common way to define a function
is with the function statement.
• The function statement consists of the
function keyword followed by the name of
the function, a comma-separated list of
parameter names in parentheses, and the
statements which contain the body of the
function enclosed in curly braces
Example: Function
function square(x) Name of Function: square
{return x*x;}
Input/Argument: x
z = 3;
sqr_z = square(z); Output: x*x
Example: Function
function sum_of_squares(num1,num2)
{return (num1*num1) + (num2*num2);}
function sum_of_squares(num1,num2)
{return (square(num1) + square(num2));}
JavaScript Operators
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Operators - 3
Comparison Operators Operator
==
Description
is equal to
Example
x===y returns
false
|| or x=6
y=3
(x==5 || y==5)
returns false
! not x=6
y=3
!(x==y) returns
true
JavaScript Basic Examples
<script>
document.write("Hello World!")
</script> format text with HTML code - heading
<script>
alert("Hello World!")
</script>
Example
<script>
x=“Hello World!”
document.write(x)
</script>
<script>
x=“İsminizi Yazın….”
document.write(“Merhaba” +x)
</script> use line break html code
JavaScript Popup Boxes
• Alert Box
– An alert box is often used if you want to make
sure information comes through to the user.
– When an alert box pops up, the user will have
to click "OK" to proceed.
<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes - 2
• Confirm Box
– A confirm box is often used if you want the
user to verify or accept something.
– When a confirm box pops up, the user will have
to click either "OK" or "Cancel" to proceed.
– If the user clicks "OK", the box returns true. If
the user clicks "Cancel", the box returns false.
JavaScript Popup Boxes - 3
• Prompt Box
– A prompt box is often used if you want the user
to input a value before entering a page.
– When a prompt box pops up, the user will have
to click either "OK" or "Cancel" to proceed
after entering an input value.
– If the user clicks "OK“, the box returns the
input value. If the user clicks "Cancel“, the box
returns null.
Prompt Box Example
<script>
x=prompt (“Adınızı Yazınız”, “ ”)
document.write(“Merhaba <br>”,+x)
</script>
JS Examples -1
Y=20x+12 ve x=3 ise, sonucu açılan pencerede
gösteren kod nasıl yazılmalıdır?
<script>
x=3
y=20*x+12
alert(y)
</script>
Examples -2
<script>
s1=12
s2=28
toplam=s1+s2
document.write("Sayıların toplamı: "+toplam)
</script>
s1=12, s2=28 Examples -3
Bu değişkenlere ait sayıların toplamlarını, farklarını, çarpımlarını ve
bölümlerini ayrı satırlarda gösteren ve son olarak ekrana
“Hesaplamalar sona erdi” yazısını çıkaran js kodunu oluşturunuz.
<script>
s1=12
s2=28
toplam=s1+s2
fark=s1-s2
carp=s1*s2
bol=s1/s2
document.write("<br>Değişkenlerdeki sayılarla ilgili aritmetik işlemler...<br>")
document.write("<br>Sayıların toplamı: "+toplam)
document.write("<br>Sayıların farkı: "+fark)
document.write("<br>Sayıların çarpımı: "+carp)
document.write("<br>1.sayının 2.sayıya bölümü: "+bol)
alert("Hesaplamalar sona erdi!")
</script >
Conditional Statements
• Very often when you write code, you want to perform different actions
for different decisions. You can use conditional statements in your
code to do this.
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Conditional Statements Examples
<script>
x=3
if(x<0)
{
alert (“negatif”)
}
else
{
alert (“pozitif”)
}
</script>
Conditional Statements Examples - 2
<script>
c=confirm(“Kitap Okuyor musunuz?”)
if(c)
{
alert (“tebrikler walla”)
}
else
{
alert (“ayıp ettiniz ama”)
}
</script>
Conditional Statements Examples - 3
<script>
p=prompt("Ankara'nın plaka numarası nedir?", " ")
if(p=="06")
{
alert("Doğru")
}
else
{
alert("Yanlış")
}
</script>