ZeePedia

DATA TYPES & OPERATORS

<< Software Design and Development Methodologies
SPREADSHEETS >>
img
Introduction to Computing ­ CS101
VU
LESSON 21
DATA TYPES & OPERATORS
(Web Development Lesson 7)
·
Everything that JavaScript manipulates, it treats as an object ­ e.g. a window or a button
·
An object has properties ­ e.g. a window has size, position, status, etc.
·
An object can be manipulated with methods that are associated with that object ­ e.g. a resize a
window with resizeTo(150, 200)
Object: A named collection of properties (data, state) & methods (instructions, behavior)
During the last lecture
we had a discussion on Objects, Properties, Methods
All objects have the
A collection of
"name" property: it
properties &
holds the name of
methods
the object (collection)
name
prop 1
method 2
prop 2
prop 5
prop 3
method 1
method 3
prop 4
Types of Objects
·
JavaScript objects
­
Objects that are part of JavaScript
­
Examples: window, document
·
Browser objects
­
Objects that contain info not about the contents of the display, but the browser itself
­
Examples: history, navigator
·
User-defined object
·
JavaScript is not a true object-oriented language like C++ or Java
·
It is so because it lacks two key features:
­
A formal inheritance mechanism
­
Strong typing
132
img
Introduction to Computing ­ CS101
VU
·
Nevertheless, JavaScript shares many similarities with object-oriented languages, and therefore is
called an object-based language
21.1 JavaScript Data Types
Unlike in C, C++ and Java, there are no explicit data types in JavaScript
Nevertheless, it recognizes & distinguishes among the following types of values:
Numbers,
e.g., 23, 4.3, -230, 4.4e-24
Booleans,
e.g., true, false
Strings, e.g., "hello", "What's the time?"
Undefined
We'll comeback to these data types, but before that we have to have to define a few new terms
First, variables:
Variables
Variables give us the ability to manipulate data through reference instead of actual value.
Variables are names assigned to values.
Variables are containers that hold values (Example: Hotel guest name, Guest room no).
Generally, the value of a variable varies during code execution (that is why the term "variable.
x = 1;
Example
while (x < 6) {
document.write (x);
x = x + 1;
}
x is a
variable
Try Doing the Same Without Using A Variable
5 lines of code
replacing 5 lines
document.write ("1"); document.write ("2");
of code!
document.write ("3"); document.write ("4");
document.write ("5");
Why use
variables?
Another Situation
x = 1;
while (x < 6000) {
document.write (x);
x = x + 1;
}
21.2 Declaring Variables
Many languages require that a variable be declared (defined) before it is first used
Although JavaScript allows variable declaration, it does not require it - except in the case when we want
to declare a variable being local (more on local variables later in the course!)
However, it is good programming practice to declare variables before using them
Declaring Variables
var height
var name, address, phoneNumber
JavaScript Variables are Dynamically Typed
133
img
Introduction to Computing ­ CS101
VU
Any variable in JavaScript can hold any type of value, and that type can change midway through the
program.
This is unlike the case for C, C++ and Java, where a variable's type is defined before usage.
The untyped feature makes JavaScript simpler to program in when developing short programs.
However, this feature brings in a few problems as well. Can you describe any?
JavaScript Variables are Dynamically Typed
After the execution of the 1st
statement, the data type of the variable
"sum" is "undefined"
var sum ;
After the execution of
sum = 43 ;
the 2nd statement,
sum = "empty" ;
the data type
After the execution of the 3rd
statement, the data type changes to
"string"
Identifiers
·  Identifiers are names used by JavaScript to refer to variables (as well as objects,
properties, methods, and functions!)
·
An identifier must begin with an alphabetical character (a-z or A-Z) or the
underscore "_" character
·
Subsequent characters can be an alphabetical (a-z or A-B) or numeric character (0-9)
or an underscore
numberOneUniversity ,N99umber_one_University
_5numberoneuniversity,x,reallyReallyLongIndentifier12345678901234
Another Restriction on Identifiers
·
Do not use any of the JavaScript keywords as identifiers
·
For example, do not name a variable as "while". When the browser sees this term in
JavaScript code, it will get confused as it already knows this keyword as part of a loop
statement. Same is the case for "var" or "if" or any of the other keywords.
JavaScript (Java) Reserved Words
Names that can't be used for variables, functions, methods, objects
Identifiers
Identifiers are names used by JavaScript to refer to variables (as well as objects, properties, methods,
and functions!)
An identifier must begin with an alphabetical character (a-z or A-Z) or the underscore "_" character
Subsequent characters can be an alphabetical (a-z or A-B) or numeric character (0-9) or an underscore
numberOneUniversity ,N99umber_one_University
134
img
Introduction to Computing ­ CS101
VU
_5numberoneuniversity,x,reallyReallyLongIndentifier12345678901234
Another Restriction on Identifiers
Do not use any of the JavaScript keywords as identifiers
For example, do not name a variable as "while". When the browser sees this term in JavaScript code, it
will get confused as it already knows this keyword as part of a loop statement. Same is the case for
"var" or "if" or any of the other keywords.
JavaScript (Java) Reserved Words
Names that can't be used for variables, functions, methods, objects
finally
byte
import
throws finally
else
protected
goto
with
default
new
abstract
static
class
interface
var
float
case
in
transient
extends
if
this
public
do
null
Boolean
super
long
void
const
instanceof
false
for
catch
true
return
private
package
double
throw
while
native
break
switch
continue
function
char
int
try
final
????
synchronized
implements
Avoid These Special Names As Well (1)
Names that should not be used for variables, functions, methods, objects
close
confirm
assign
Window
JavaClass
History
Image
Form
java
onfocus
navigator
Number
location
onblur
Select
prompt
Radio
Packages
Reset
Element
unescape
valueOf
sun
window
JavaObject
closed
Date
blur
Document
onload
history
isNaN
Frame
JavaArray
Self
netscape
Object
Math
onerror
untaint
prototype
ref
parent
scroll
taint
defaultStatus
clearTimeout
document
135
img
Introduction to Computing ­ CS101
VU
alert
Area
assign
Boolean
Checkbox
escape
FileUpload
Form
frames
getClass
status
Link
location
MimeType
navigate
onunload
opener
Packages
parseFloat
Password
setTimeout
String
sun
Text
top
Anchor
Array
blur
Button
Submit
eval
focus
Frame
Function
Hidden
length
Location
Math
name
Navigator
open
Option
parent
parseInt
Plugin
JavaPackage
taint
Textarea
toString
Identifiers appear in JavaScript statements
Let us now discuss a few other elements that appear in those statements
Elements of JavaScript Statements
b=2;
Identifiers
sum = sum + 49 ;
Operators
name = "Bhola" + " Continental" ;
Literals
x = Math.floor ( x )
Punctuation
JavaScript Literals
A data value that appears directly in a statement
Literals can be of several types. Some of them are:
Number
String
Boolean
Numeric Literals
24,-230000000000000000,9.80665,1.67e-27,
JavaScript stores all numbers, even integers, as floating-point numbers
String Literals
"" , '`Bhola" , "Where is the Bhola Continental Hotel?"
String literals are always enclosed in a matching pair of single or double quotes
Boolean Literals
True, false ,
if ( tankFull == false)
addMoreWater = true
21.3 JavaScript Operators
Operators operate on operands to achieve the desired results
136
img
Introduction to Computing ­ CS101
VU
JavaScript has numerous operators, classified in many categories. We will look at only a few of them
belonging to the following categories:
Assignment operators  -- Arithmetic operators
Comparison operators -- String operators
Logical operators
We'll look at a few more during future lectures, but understand that there are many more. Even you text
book does not cover all of them!
Assignment Operator "="
Changes the value of what is on the LHS, w.r.t. what is on the RHS
total_number_of_students = 984 ;
title = "Understanding Computers" ;
swapFlag = false ;
x = y + 33 ;
Arithmetic Operators
Multiply 2 * 4 8
Divide 2 / 4 0.5
Modulus 5 % 2 1
Add 2 + 4 6
Subtract 2 - 4 -2
Not the same as the
Negate  -(5) -5
assignment "=" operator
21.4 Comparison Operators
The "equal to (==)" Comparison Operator
if ( today == "Sunday" )
document.write("The shop is closed");
The string "The shop is closed" will be written to the document only if the variable today has a value
equal to "Sunday"
Comparison Operators
a == b  True if a and b are the same
a != b
True if a and b are not the same
a>b
True if a is greater than b
a >= b  True if a is greater than or equal to b
a<b
True if a is less than b
a <= b  True if a is less than or equal to b
Example
if ( x != 0 )
result = y / x;
else
result = "not defined";
21.5 Logical Operators
a && b AND
True if both are true
a || b OR True of either or both are true
!a  NOT
True if a is false
The "AND (&&)" Logical Operator
if ( (pitch == "hard") && (bowler == "fast") )
myStatus = "Pulled muscle";
The value of the variable myStatus will be set to "Pulled muscle" if both of the conditions are true
Example
137
img
Introduction to Computing ­ CS101
VU
if ( x || y )
document.write ("Either or both are true");
else
document.write ("Both are false");
So far we have looked at the assignment operator, arithmetic operators, comparison operators and
logical operators
The final category that we are going to look at is string operators
In that category, we look at only one, the concatenation operator
The "+" String Operator
The "+" operator can be used to concatenate two strings
title = "bhola" + "continental"
The value of the variable title becomes "bholacontinental"
21.6 Elements of JavaScript Statements
Semicolon ;
Terminate all JavaScript statements with a semicolon. It is not always necessary, but highly
recommended.
Identifiers
b = 2;
Operators
sum = sum + 49;
Literals
name = "Bhola" + " Continental";
Punctuation
x = Math.floor ( x );
White Spaces & Line Breaks
White spaces: The space & the tab characters
JavaScript ignores any extra white spaces or line breaks that you put in the code
This gives you the freedom of using them for making your code appear neat and readable
while ( x > 0) {
remaind = x % 2;
y = remaind + y;
}
while ( x > 0) {remaind = x % 2; y = remaind + y;}
while ( x > 0) {
remaind = x % 2;
y = remaind + y;
}
Now let's talk about a very special type of JavaScript statement that does not really do anything, but is
found in most pieces of code!
Comments
Comments are included on a Web page to explain how and why you wrote the page the way you did
Comments can help someone other than the author to follow the logic of the page in the author's
absence
The commented text is neither displayed in the browser nor does it have any effect on the logical
performance of the Web page, and is visible only when the actual code is viewed
JavaScript Comments
Single-line comments (two options)
// Author: Bhola
<!-- Creation Date: 24 March 2003
Multi-line comments
/* Author: Bhola
138
img
Introduction to Computing ­ CS101
VU
Creation Date: 24 March 2003 */
HTML Comments
<!-- Author: Bhola
Creation Date: 24 March 2003 -->
Note : comments let the code speak for itself!
Comments add clarity
Decimal to Binary Conversion in JavaScript
x = 75 ; // x is the decimal number
y = "" ; // y is the binary equivalent
while ( x > 0) {
remainder = x % 2 ;
quotient = Math.floor( x / 2 ) ;
y = remainder + y ;
x = quotient ;
}
document.write("y = " + y) ;
During Today's Lesson ...
We found out about JavaScript data types
About variables and literals
We also discussed several operators supported by JavaScript
Next (the 8th) Web Dev Lecture:
Flow Control and Loops
To be able to understand the concept of flow control using the "if" and "switch" structures
To be able to understand the concept of behind the "while" and "for" looping structures
To be able to solve simple problems using flow control and loop statements
139
Table of Contents:
  1. INTRODUCTION
  2. EVOLUTION OF COMPUTING
  3. World Wide Web, Web’s structure, genesis, its evolution
  4. Types of Computers, Components, Parts of Computers
  5. List of Parts of Computers
  6. Develop your Personal Web Page: HTML
  7. Microprocessor, Bus interface unit, Data & instruction cache memory, ALU
  8. Number systems, binary numbers, NOT, AND, OR and XOR logic operations
  9. structure of HTML tags, types of lists in web development
  10. COMPUTER SOFTWARE: Operating Systems, Device Drivers, Trialware
  11. Operating System: functions, components, types of operating systems
  12. Forms on Web pages, Components of Forms, building interactive Forms
  13. APPLICATION SOFTWARE: Scientific, engineering, graphics, Business, Productivity, Entertainment, Educational Software
  14. WORD PROCESSING: Common functions of word processors, desktop publishing
  15. Interactivity to Forms, JavaScript, server-side scripts
  16. ALGORITHMS
  17. ALGORITHMS: Pseudo code, Flowcharts
  18. JavaScript and client-side scripting, objects in JavaScript
  19. Low, High-Level, interpreted, compiled, structured & object-oriented programming languages
  20. Software Design and Development Methodologies
  21. DATA TYPES & OPERATORS
  22. SPREADSHEETS
  23. FLOW CONTROL & LOOPS
  24. DESIGN HEURISTICS. Rule of thumb learned through trial & error
  25. WEB DESIGN FOR USABILITY
  26. ARRAYS
  27. COMPUTER NETWORKS: types of networks, networking topologies and protocols
  28. THE INTERNET
  29. Variables: Local and Global Variables
  30. Internet Services: FTP, Telnet, Web, eMail, Instant messaging, VoIP
  31. DEVELOPING PRESENTATIONS: Effective Multimedia Presentations
  32. Event Handlers
  33. GRAPHICS & ANIMATION
  34. INTELLIGENT SYSTEMS: techniques for designing Artificial Intelligent Systems
  35. Mathematical Functions in JavaScript
  36. DATA MANAGEMENT
  37. DATABASE SOFTWARE: Data Security, Data Integrity, Integrity, Accessibility, DBMS
  38. String Manipulations:
  39. CYBER CRIME
  40. Social Implications of Computing
  41. IMAGES & ANIMATION
  42. THE COMPUTING PROFESSION
  43. THE FUTURE OF COMPUTING
  44. PROGRAMMING METHODOLOGY
  45. REVIEW & WRAP-UP of Introduction to Computing