Assist. Prof. Dr.
Fatih ABUT
Introduction to JavaScript
Variables and Data Types
Operator Basics
2
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,
Firefox, Netscape, Opera, Safari.
3
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
4
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++.
Java code is compiled whereas JavaScript code is
interpreted (->next slides)
5
Nat 4/5
All programs convert High Level
Language Source code into machine
code (binary)
◦ Interpreter
Translates and executes one line at a time
◦ Compiler
Translates and executes the entire program at
once
This program can then be ran repeatedly
6
Nat 4/5
All programs convert High Level Language
Source code into machine code (binary)
Think complete!
Compilers translate source code once into an
executable program
◦ Only has to be translated once!
◦ Cannot see the source code in a compiled program
Interpreters translate source code line by line
◦ Always has to be re-interpreted
◦ Spots errors line by line
7
Nat 4/5
Functions like a spoken language
interpreter.
◦ Translates and executes a single line at a time
◦ The interpreter is ALWAYS loaded in memory
◦ Error feedback is provided line by line
Like in Smallbasic
◦ Interpreted programs have to be re-interpreted
every single execution
8
Nat 4/5
Original Source Code
Pctoutput.visible = true
Pctoutput.print “Hello” Interpreter
1001 1000 1100 1110 0011
Syntax Error
9
Nat 4/5
Can be saved and
Original Source Code
ran later
Pctoutput.visible = true
Pctoutput.print “Hello”
Object Code
1001 1000 1100 1110 0011
Compiler
1010 1010 1010 0111 0011
Syntax Error
10
<html>
<head
<script type="text/javascript">
document.write("Hello World!")
</script>
</head>
<body>
</body>
</html>
11
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
It is vitally important to distinguish between the name of the
variable and the value of the variable
For example, in the expression var color=“red”, color is
the name of the variable and red is the value. In other words,
color is the name of the box while red is what is inside the
box
12
In JavaScript Example:
variables are
created using the var x = 10;
keyword var
var y = 17;
var color = “red”;
var name = “Katie”;
13
Primitive Data Types
◦ Numbers
◦ Strings
◦ Boolean (True, False)
Composite Data Types
◦ Arrays
◦ Objects
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
14
Numbers - A number can be either an
integer or a decimal (real)
◦ Integers are used to count whole (i.e. complete)
things
1 person, 4 balls, 12 moons
◦ Decimal (real) numbers are used to describe both
integer and fractional portions of wholes
Pi = 3.14159 (approx) is the ratio of the circle
circumference and its diameter
The average number of children per Canadian family
is 1.4
The set of integers forms a proper subset of the set of
real numbers.
15
Strings - A string is a sequence of letters or
numbers enclosed in single or double quotes
Boolean - True or False
16
JavaScript is untyped; It does not have
explicit data types
For instance, there is no way to specify
that a particular variable represents an
integer, string, or real number
The same variable can have different data
types in different contexts
17
Although JavaScript does not have explicit
data types, it does have implicit data types
If you have an expression which combines
two numbers, it will evaluate to a number
If you have an expression which combines a
string and a number, it will evaluate to a
string
18
var x = 4; Ans = x + y;
Ans => 15
var y = 11;
Ans = z + x;
var z = “cat”; Ans => cat4
var q = “17”; Ans = x + q;
Ans => 417
19
var x = 4; Ans = x + y + z;
Ans => 15cat
var y = 11;
Ans = q + x + y;
var z = “cat”; Ans => 17411
var q = “17”;
20
// 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
21
JavaScript is case sensitive
Variable names cannot contain spaces,
punctuation, or start with a digit
Variable names cannot be reserved words
22
A statement is a Examples:
section of JavaScript Last_name = “Dunn”;
that can be x = 10 ;
evaluated by a Web y = x*x ;
browser
A script is simply a
collection of
statements
23
Assignment, Arithmetic,
Relations, Logical, Bitwise and
Expressions
24
+ Addition ! Logical NOT
- Subtraction && Logical AND
* Multiplication || Logical OR
/ Division ~ Bitwise NOT
% Modulus & Bitwise AND
++ Increment | Bitwise OR
-- Decrement << Bitwise Left Shifting
== Equality >> Bitwise Right Shifting
!= Inequality ?: Conditional Selection
Possible categorizations of JavaScript operators
◦ Assignment ▪ Unary
◦ Arithmetic ▪ Binary
◦ Relational ▪ Ternary
◦ Logical
◦ Bitwise 25
Arithmetic operators (all numbers are floating-point):
+ - * / % ++ --
Comparison operators:
< <= == != >= >
Logical operators:
&& || !
Bitwise operators:
& | ^ ~ << >> >>>
(Augmented) Assignment operators:
= += -= *= /= %=
<<= >>= >>>=
&= ^= |=
26
The assignment operator must be used with
care and attention to detail
◦ Avoid using = where you intend to perform a
comparison for equivalence (equality) using ==
◦ You may use = more than once in a statement
This may be confusing and should be avoided when it
is necessary to assure clarity of codes.
Right-to-Left evaluation: A = B = C
27
Arithmetic operators are used to express the
logic of numerical operations
The operators may be grouped as follows:
◦ Addition and Subtraction : + -
◦ Multiplication : *
◦ Integer Division : / %
◦ Floating point Division : /
◦ Auto-Increment and Auto-Decrement
++ and --
Pre- versus Post-
28
Unary versus Binary
◦ It is meaningful to say –X (negative X) so JavaScript
permits use of the minus symbol (hyphen) as a
unary operator. It also permits use of + as unary.
Ex. A = -3 ;
◦ All operators have typical use as binary operators in
arithmetic expression units of the general form
Operand1 arith_op Operand2
29
There are two division operators in JavaScript
◦ / (quotient) and % (modulus)
◦ Both are binary operators
◦ Modulus division is used almost exclusively for
division of integers, since it evaluates to the
remainder
Division : / %
◦ var X=5, Y=3, N, M ;
◦ N=X/Y ; /* evaluates to 1.6666666 */
◦ M=X%Y; /* evaluates to 2 */
30
A common programming statement involves
adding (or subtracting) 1 to (from) a variable
used for counting
◦ N = N+1; N = N–1;
◦ The addition of 1 to an integer variable is called
incrementation
◦ Similarly, subtracting 1 from an integer variable is
called decrementation
31
The JavaScript language supports two
operators that automatically generate
increment or decrement statements on
integer variables
◦ Auto-Increment ++
◦ Auto-Decrement --
◦ Examples: (Equivalent statements)
Explicit Post-auto Pre-auto
◦ N = N+1; N++ ; ++N ;
◦ N = N–1; N-- ; --N ;
32
There is a very important difference between
using these operators before versus after a
variable symbol
◦ AFTER (POST) :
If an expression contains N++, the expression is evaluated
using the value stored at the location N. After the
expression is evaluated, the value at N is incremented by 1.
◦ BEFORE (PRE) :
If an expression contains ++N, the value at N is incremented
by 1 and stored at N, before any other parts of the
expression are evaluated. The expression is then evaluated
using the new value at N.
33
Assume the declarations with initial values
specified
◦ var A, B, N = 4, M = 3 ;
What are the final values of A, B, N and M ?
◦ A = N++ ;
◦ B = ++M + N-- ; /* watch out ! */
◦ A = --A ;
◦ ANSWER: A=3 B=9 N=4 M=4
34
Operator augmentation involves combining two
operator symbols to form a new symbol with
extended meaning
Arithmetic Assignment operators combine the
expressiveness of arithmetic and assignment and
permit abbreviation of coding
◦ += and -=
◦ *=
◦ /= and %=
◦ In some cases they may lead to hardware optimization of
executable code.
35
Although these operations have a certain kind
of elegance, they may create ambiguity.
◦ However, programmers should ensure that
programs have clarity.
◦ Examples:
◦ Longhand Shorthand
X=X+Y; X += Y ;
X=X*Y; X *= Y ;
X=X%Y; X %= Y ;
36
Relational operators are used to express the
concept of comparison of two values
◦ Based on the Boolean notions of True and False
This is vital to decision making logic where
we do something – or not – based on
evaluating an expression
◦ while ( Age > 0 ) .....
◦ if ( Num <= 0 ) .....
37
Formally, these operators are defined as
◦ Equivalence (Equal to) : ==
◦ Non-equivalance (Not equal to) : !=
◦ Open Precursor (Less than) : <
◦ Closed Precursor (Less than or equal to) : <=
◦ Open Successor (Greater than) : >
◦ Closed Successor (Greater than or equal to) : >=
38
Each matching colour pair is complementary.
◦ Equivalence (Equal to) : ==
◦ Non-equivalance (Not equal to) : !=
◦ Open Precursor (Less than) : <
◦ Closed Precursor (Less than or equal to) : <=
◦ Open Successor (Greater than) : >
◦ Closed Successor (Greater than or equal to) : >=
39
Each relational operator is a binary operator,
with an operand on the left and another on
the right of the operator symbol(s)
Relational expressions are formed using
units of the form:
◦ Operand1 rel_op Operand2
The value of a relational expression is always
0 (meaning false) or 1 (meaning true).
40
Boolean Set Theory defines several operations
that act on values 0 and 1
◦ These values apply to relational expressions and also
integer variables (limited to these two values)
Complement (Not) : !
◦ Unary !(X<Y)
Intersection (And) : &&
◦ Binary ( X < Y ) && ( Age > 20 )
Union (inclusive Or) : ||
◦ Binary ( X < Y ) || ( Age > 20 )
41
The logical operators considered at this time
are a subset of the logic operators. There
PROPOSITION
are many other operators
I will available.
go to the movies if:
( I have $20 in my pocket
The main ANDuse Iof these
have operators
enough is )in forming
gas in my car
OR ( it is $10 Tuesday special night
complex decision logic
AND I have $10 in my pocket
◦ Several
ANDlogical sub-expressions
I am able can be
to walk to the movie combined
theater )
into a single expression
◦ This is very useful in the condition expressions that
appear in if or while structures
42
& | ^ >> >>> <<
All bitwise operators require numeric operands that
have integer values.
Javascript is working with floating point numbers,
which means that the first step is to convert a floating
point to an integer.
The bitwise operators convert the operand to a 32-
bit signed integer, and turn the result back into 64-
bit floating point.
43
JavaScript is one of only a few languages that
contains a ternary operator, an operator that acts
on three operands
This operator is used for simplified expression of
decision logic intended to provide a result
(A > B ) ? 10 : 20
If it is true that A > B, the expression evaluates to
10 – otherwise 20.
44
String operator:
+
Special equality tests:
◦ == and != try to convert their operands to the same
type before performing the test
◦ Not in C or Java: === and !== consider their operands
unequal if they are of different types
Additional operators (to be discussed):
new typeof void delete
45
45
Complex expressions can be constructed
using the various operators seen so far
◦ Such expressions must be constructed with care,
taking into account the issue of data type
compatibility
◦ It is also important to avoid ambiguity in how the
expression is to be interpreted (both by the
compiler and by the programmer)
Parentheses ( ) are often used to encapsulate
sub-expression terms
◦ Sub-expressions within parentheses are compiled
before other terms.
46
When an expression is constructed using
parenthesized sub-expressions, these sub-
expressions themselves may be further
broken down into parenthesized sub-sub-
expressions
This is referred to as nesting of expressions
◦ Innermost nested sub-expressions are evaluated
first by interpreters
47
Example:
(1+5)*3–(4–2)%3
48
Example:
(1+5)*3–(4–2)%3
(6)*3 - (2)%3
18 - 2
16
49
Example:
(1+5)* (3–(4–2)/(5–1))%3
50
Example:
(1+5)* ( 3–(4–2)/(5–1) ) %3
(6) * ( 3- (2) / (4) )%3
6 * ( 3 - 0.5 ) % 3
6 * 2.5 % 3
15 % 3 = 0
51