0% found this document useful (0 votes)
10 views

02. Javascript Introduction

Uploaded by

Anjali Chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

02. Javascript Introduction

Uploaded by

Anjali Chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

INTRODUCTION TO

JAVASCRIPT

IT1702 WTWS 1
Server side and Client side
Programming
► Server-side Programming
 It is the program that runs on server dealing
with the generation of content of web page.
► Querying the database
► Operations over databases
► Access/Write a file on server.
► Interact with other servers.
► Structure web applications.
► Process user input. For example if user input is a text in search
box, run a search algorithm on data stored on server and send
the results.

IT1702 WTWS 2
Examples: server-side
programming:
► PHP
► C++
► Java and JSP
► Python
► Ruby on Rails

IT1702 WTWS 3
Client-side Programming
► It is the program that runs on the client
machine (browser).
► It deals with the user interface/display, or
any other processing that can happen on
client machine like reading/writing cookies.

IT1702 WTWS 4
Client-side Programming Contd..
► Interact with temporary storage
► Make interactive web pages
► Interact with local storage
► Sending request for data to server
► Send request to server
► work as an interface between server and
user

IT1702 WTWS 5
Examples of Client-side
Programming
► Javascript
► VBScript
► HTML
► CSS
► AJAX

IT1702 WTWS 6
Introduction to JavaScript (Client-
Side Programming)
► JavaScript (JS), is a high-level, interpreted
programming language.
► Alongside HTML and CSS, JavaScript is one of the
three core technologies of the World Wide Web.
► JavaScript enables interactive web pages and thus
is an essential part of web applications.
 The vast majority of websites use it, and all major web
browsers have a dedicated JavaScript engine to execute
it.
IT1702 WTWS 7
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.
IT1702 WTWS 8
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 IT1702 WTWS 9
Are Java and JavaScript the Same?

► NO!
► Java and JavaScript are two completely
different languages in both concept and
design!
► Java (developed by Sun Microsystems) is a
powerful and much more complex
programming language - in the same
category as C and C++.
IT1702 WTWS 10
Javascript vs Java
► interpreted,
not compiled
► more relaxed syntax and rules
 fewer and "looser" data types
 variables don't need to be declared
 errors often silent (few exceptions)
► key construct is the function rather than the class
 "first-class" functions are used in many situations
► contained within a web page and integrates with
its HTML/CSS content
IT1702 WTWS 11
How to Put a JavaScript Into an
HTML Page?
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

IT1702 WTWS 12
Ending Statements With a
Semicolon?
► With traditional programming languages,
like C++ and Java, each code statement has
to end with a semicolon (;).
► Many programmers continue this habit
when writing JavaScript, but in general,
semicolons are optional! However,
semicolons are required if you want to put
more than one statement on a single line.

IT1702 WTWS 13
JavaScript Variables
► Variables are used to store data.
► A variable is a "container" for information you
want to store. A variable's value can change
during the script. You can refer to a variable by
name to see its value or to change its value.
► Rules for variable names:
 Variable names are case sensitive
 They must begin with a letter or the underscore
character
► strname – STRNAME (not same)
IT1702 WTWS 14
JavaScript Operators
Arithmetic Operators Operator

+
Description

Addition
Example

x=2
Result

4
(İşleçler, iki ya da daha fazla değer y=2

üzerinde işlem yapılmasını x+y

sağlar. JavaScript içinde - Subtraction x=5


y=2
3

aritmetik ve hesaplama işleçleri x-y


olmak üzere iki tür işleç * Multiplication x=5 20

kullanılır) y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division 5%2 1
remainder)
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
IT1702 WTWS 15
JavaScript Operators – 2
Assignment Operators Operator Example Is The Same As
(Atama deyimi (=), bir değişkene
bir değerin atanmasını sağlar. = x=y x=y
Değişkenlere türlerine ve
tanımlamalarına uygun olan += x+=y x=x+y
herhangi bir değer atanabilir.)
-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y

IT1702 WTWS 16
JavaScript Operators - 3
Comparison Operators Operator

==
Description

is equal to
Example

5==8 returns false


(Karşılaştırma işleci, iki ya da daha
=== is equal to (checks for x=5
çok değeri birbiriyle both value and
y="5"
type)
karşılaştırarak True ya da False
olarak mantıksal bir değer x==y returns true
döndürür.)
x===y returns
false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal 5>=8 returns false


to

<= is less than or equal to 5<=8 returns true

IT1702 WTWS 17
JavaScript Operators - 4
Logical Operators
Operator Description Example

&& and x=6

(İkili işleçler birden çok y=3

karşılaştırma işlemini tek bir


koşul ifadesi olarak birleştirirler.) (x < 10 && y > 1)
returns true

|| or x=6

y=3

(x==5 || y==5)
returns false

! not x=6

y=3

!(x==y) returns
true

IT1702 WTWS 18
JavaScript Basic Examples
<script>
document.write("Hello World!")
</script>  format text with HTML code - heading

<script>
alert("Hello World!")
</script>

IT1702 WTWS 19
Example
<script>
x=“Hello World!”
document.write(x)
</script>

<script>
x=“İsminizi Yazın….”
document.write(“Merhaba” +x)
</script>  use line break html code
IT1702 WTWS 20
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>
IT1702 WTWS 21
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.

IT1702 WTWS 22
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.
IT1702 WTWS 23
Prompt Box Example
<script>
x=prompt (“Adınızı Yazınız”, “ ”)
document.write(“Merhaba <br>”,+x)
</script>

IT1702 WTWS 24
JS Examples -1

<script>
x=3
y=20*x+12
alert(y)
</script>
IT1702 WTWS 25
Examples -2
<script>
s1=12
s2=28
sum=s1+s2
document.write(“sum: "+sum)
</script>

IT1702 WTWS 26
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.

In JavaScript we have the following conditional statements:


► if statement - use this statement if you want to execute some code
only if a specified condition is true
► if...else statement - use this statement if you want to execute some
code if the condition is true and another code if the condition is false
► if...else if....else statement - use this statement if you want to
select one of many blocks of code to be executed
► switch statement - use this statement if you want to select one of
many blocks of code to be executed

IT1702 WTWS 27
Conditional Statements - 2
if (condition)
{
code to be executed if condition is true
}

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
IT1702 WTWS 28
Conditional Statements Examples
<script>
x=3
if(x<0)
{
alert (“negative”)
}
else
{
alert (“positive”)
}
</script>

IT1702 WTWS 29
JavaScript functions
30

function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS

 the above could be the contents of example.js


linked to our HTML page
 statements placed into functions can be evaluated in
response to user events
IT1702 WTWS
Event handlers
31

<element attributes onclick="function();">...


HTML

<button onclick="myFunction();">Click me!</button>


HTML

 JavaScript functions can be set as event handlers


 when you interact with the element, the function will execute
 onclick is just one of many event HTML attributes we'll
use
 but popping up an alert window is disruptive and
annoying
 A better user experience would be to have the message
appear on the page...
IT1702 WTWS
Document Object Model (DOM)
32

 most JS code manipulates


elements on an HTML page
 we can examine elements'
state
 e.g. see whether a box is
checked
 we can change state
 e.g. insert some new text into
a div
 we can change styles
e.g. make a paragraph red
IT1702 WTWS

DOM element objects
33

IT1702 WTWS
Accessing elements:
document.getElementById
34

var name = document.getElementById("id");


JS

<button onclick="changeText();">Click me!</button>


<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML

function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");

textbox.style.color = "red";

} JS

IT1702 WTWS
Accessing elements:
document.getElementById
35

 document.getElementById returns the DOM object


for an element with a given id
 can change the text inside most elements by setting
the innerHTML property
 can change the text in form controls by setting the
value property

IT1702 WTWS
Changing element style:
element.style
36

Attribute Property or style object


color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
IT1702 WTWS
Preetify
37

function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
} JS

IT1702 WTWS
38 More Javascript Syntax

IT1702 WTWS
Variables
39

var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS

 variables are declared with the var keyword (case


sensitive)
 types are not specified, but JS does have types
("loosely typed")
 Number, Boolean, String, Array, Object,
Function, Null, Undefined
 can find out a variable's type by calling typeof
IT1702 WTWS
Number type
40

var enrollment = 99;


var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

 integers and real numbers are the same type (no int
vs. double)
 same operators: + - * / % ++ -- = += -= *= /=
%=
 similar precedence to Java
 many operators auto-convert types: "2" * 3 is 6
IT1702 WTWS
Comments (same as Java)
41

// single-line comment
/* multi-line comment */
JS

 identical to Java's comment syntax


 recall: 4 comment syntaxes
 HTML: <!-- comment -->
 CSS/JS/PHP: /* comment */

 Java/JS/PHP: // comment
 PHP: # comment

IT1702 WTWS
Math object
42

var rand1to10 = Math.floor(Math.random() * 10 + 1);


var three = Math.floor(Math.PI);
JS

 methods: abs, ceil, cos, floor, log,


max, min, pow, random, round, sin,
sqrt, tan
 properties: E, PI

IT1702 WTWS
Special values: null and undefined
43

var ned = null;


var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS

 undefined : has not been declared, does not


exist
 null : exists, but was specifically assigned an
empty or null value
 Why does JavaScript have both of these?
IT1702 WTWS
Logical operators
44

 > < >= <= && || ! == != === !==


 most logical operators automatically convert types:
5 < "7" is true
 42 == 42.0 is true

 "5.0" == 5 is true

 === and !== are strict equality tests; checks both


type and value
 "5.0" === 5 is false

IT1702 WTWS
if/else statement (same as Java)
45

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
 identical structure to Java's if/else statement
 JavaScript allows almost anything as a condition

IT1702 WTWS
Boolean type
46

var iLike190M = true;


var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS

 any value can be used as a Boolean


 "falsey" values: 0, 0.0, NaN, "", null, and undefined
 "truthy" values: anything else

 converting a value into a Boolean explicitly:


 var boolValue = Boolean(otherValue);
 var boolValue = !!(otherValue);

IT1702 WTWS
for loop (same as Java)
47

var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS

var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS

IT1702 WTWS
while loops (same as Java)
48

while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

 break and continue keywords also behave as in


Java

IT1702 WTWS
Popup boxes
49

alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS

IT1702 WTWS
Arrays
50

var name = []; // empty array


var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var ducks = ["Huey", "Dewey", "Louie"];


var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS

IT1702 WTWS
Array methods
51

var a = ["Stef", "Jason"]; // Stef, Jason


a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS
 array serves as many data structures: list, queue,
stack, ...
 methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front

 shift and pop return the element that is removed


IT1702 WTWS
String type
52

var s = "Connie Client";


var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
 methods: charAt, charCodeAt, fromCharCode,
indexOf, lastIndexOf, replace, split,
substring, toLowerCase, toUpperCase
 charAt returns a one-letter String (there is no char type)
 length property (not a method as in Java)
 Strings can be specified with "" or ''
 concatenation with + :
IT1702 WTWS
1 + 1 is 2, but "1" + 1 is "11"
More about String
53

 escape sequences behave as in Java: \' \" \& \n \t


\\
 converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS

 accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1); JS
IT1702 WTWS
Splitting strings: split and join
54

var s = "the quick brown fox";


var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a
delimiter between them

IT1702 WTWS

You might also like