SIT 322 - Scripting Languages
Part II - JavaScript Syntax
JavaScript - Variables
JavaScript Datatypes
• One of the most fundamental characteristics of a programming language is the set of
data types it supports. These are the type of values that can be represented and
manipulated in a programming language.
• JavaScript allows you to work with three primitive data types −
✓ Numbers, eg. 123, 120.50 etc.
✓ Strings of text e.g. "This text string" etc.
✓ Boolean e.g. true or false.
• JavaScript also defines two trivial data types, null and undefined, each of which defines
only a single value. In addition to these primitive data types, JavaScript supports a
composite data type known as object. We will cover objects in detail in a separate
chapter.
• Note − JavaScript does not make a distinction between integer values and floating-point
values. All numbers in JavaScript are represented as floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 754
standard.
SIT 322 - Scripting Languages 2
• Like many other programming languages, JavaScript has variables.
Variables can be thought of as named containers. You can place data
into these containers and then refer to the data simply by naming the
container.
• Before you use a variable in a JavaScript program, you must declare it.
Variables are declared with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
SIT 322 - Scripting Languages 3
• Storing a value in a variable is called variable initialization. You can do
variable initialization at the time of variable creation or at a later point in
time when you need that variable.
• For instance, you might create a variable named money and assign the
value 2000.50 to it later. For another variable, you can assign a value at the
time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
SIT 322 - Scripting Languages 4
• JavaScript is untyped language.
• This means that a JavaScript variable can hold a value of any data
type.
• Unlike many other languages, you don't have to tell JavaScript during
variable declaration what type of value the variable will hold.
• The value type of a variable can change during the execution of a
program and JavaScript takes care of it automatically.
SIT 322 - Scripting Languages 5
JavaScript Variable Scope
• The scope of a variable is the region of your program in which it is
defined. JavaScript variables have only two scopes.
• Global Variables − A global variable has global scope which means it
can be defined anywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function
where it is defined. Function parameters are always local to that
function.
• Within the body of a function, a local variable takes precedence over
a global variable with the same name. If you declare a local variable
or function parameter with the same name as a global variable, you
effectively hide the global variable.
SIT 322 - Scripting Languages 6
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
[Link](myVar);
}
//-->
</script>
</body>
</html>
SIT 322 - Scripting Languages 7
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in
mind.
• You should not use any of the JavaScript reserved keywords as a
variable name. These keywords are mentioned in the next section.
For example, break or boolean variable names are not valid.
• JavaScript variable names should not start with a numeral (0-9). They
must begin with a letter or an underscore character. For
example, 123test is an invalid variable name but _123test is a valid
one.
• JavaScript variable names are case-sensitive. For
example, Name and name are two different variables.
SIT 322 - Scripting Languages 8
JavaScript Reserved Words
• A list of all the reserved words in JavaScript are given in the following
table. They cannot be used as JavaScript variables, functions,
methods, loop labels, or any object names.
SIT 322 - Scripting Languages 9
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
SIT 322 - Scripting Languages 10
JavaScript - Operators
What is an Operator?
• Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and ‘+’ is called the operator. JavaScript supports the
following types of operators.
✓Arithmetic Operators
✓Comparison Operators
✓Logical (or Relational) Operators
✓Assignment Operators
✓Conditional (or ternary) Operators
SIT 322 - Scripting Languages 11
[Link]. Operator & Description
Arithmetic Operators 1 + (Addition)
Adds two operands
Ex: A + B will give 30
Assume variable A holds 10 2 - (Subtraction)
and variable B holds 20, Subtracts the second operand from the first
Ex: A - B will give -10
then − 3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Note − Addition operator (+) works for Increases an integer value by one
Ex: A++ will give 11
Numeric as well as Strings. e.g. "a" +
10 will give "a10". 7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
SIT 322 - Scripting Languages 12
[Link]("a % b = ");
Example result = a % b;
[Link](result);
<html>
[Link](linebreak);
<body>
[Link]("a + b + c = ");
<script type = "text/javascript">
result = a + b + c;
<!--
[Link](result);
var a = 33;
[Link](linebreak);
var b = 10;
a = ++a;
var c = "Test";
[Link]("++a = ");
var linebreak = "<br />";
result = ++a;
[Link]("a + b = ");
[Link](result);
result = a + b;
[Link](linebreak);
[Link](result);
b = --b;
[Link](linebreak);
[Link]("--b = ");
[Link]("a - b = ");
result = --b;
result = a - b;
[Link](result);
[Link](result);
[Link](linebreak);
[Link](linebreak);
//-->
[Link]("a / b = ");
</script>
result = a / b;
Set the variables to different values and then try...
[Link](result);
</body>
[Link](linebreak);
</html>
SIT 322 - Scripting Languages 13
Output
• a + b = 43
• a - b = 23
• a / b = 3.3
• a%b=3
• a + b + c = 43Test
• ++a = 35
• --b = 8
SIT 322 - Scripting Languages 14
[Link]. Operator & Description
1 = = (Equal)
Comparison Operators Checks if the value of two operands are equal or not, if yes, then the condition
becomes true. Ex: (A == B) is not true.
2 != (Not Equal)
• JavaScript supports Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true. Ex: (A != B) is true.
the following 3 > (Greater than)
comparison operators Checks if the value of the left operand is greater than the value of the right operand,
− if yes, then the condition becomes true. Ex: (A > B) is not true.
• Assume variable A 4 < (Less than)
Checks if the value of the left operand is less than the value of the right operand, if
holds 10 and variable yes, then the condition becomes true. Ex: (A < B) is true.
B holds 20, then − 5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true. Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true. Ex: (A <= B) is true.
SIT 322 - Scripting Languages 15
Example
<html> [Link]("(a != b) => ");
<body> result = (a != b);
<script type = "text/javascript"> [Link](result);
<!-- [Link](linebreak);
var a = 10; [Link]("(a >= b) => ");
var b = 20; result = (a >= b);
var linebreak = "<br />"; [Link](result);
[Link]("(a == b) => "); [Link](linebreak);
result = (a == b); [Link]("(a <= b) => ");
[Link](result); result = (a <= b);
[Link](linebreak); [Link](result);
[Link]("(a < b) => "); [Link](linebreak);
result = (a < b); //-->
[Link](result); </script>
[Link](linebreak); Set the variables to different values and
[Link]("(a > b) => "); different operators and then try...
result = (a > b); </body>
[Link](result); </html>
[Link](linebreak);
SIT 322 - Scripting Languages 16
Output
• (a == b) => false
• (a < b) => true
• (a > b) => false
• (a != b) => true
• (a >= b) => false
• a <= b) => true
SIT 322 - Scripting Languages 17
Logical Operators [Link]. Operator & Description
1 && (Logical AND)
If both the operands are non-zero,
• JavaScript supports the then the condition becomes true.
following logical Ex: (A && B) is true.
operators − 2 || (Logical OR)
• Assume variable A holds If any of the two operands are non-
10 and variable B holds zero, then the condition becomes
20, then − true. Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its
operand. If a condition is true, then
the Logical NOT operator will make it
false. Ex: ! (A && B) is false.
SIT 322 - Scripting Languages 18
Example
<html> [Link](result);
<body> [Link](linebreak);
<script type = "text/javascript"> [Link]("!(a && b) => ");
<!-- result = (!(a && b));
var a = true; [Link](result);
[Link](linebreak);
var b = false;
//-->
var linebreak = "<br />";
</script>
[Link]("(a && b) => ");
<p>Set the variables to different values and
result = (a && b); different operators and then try...</p>
[Link](result); </body>
[Link](linebreak); </html>
[Link]("(a || b) => ");
result = (a || b);
•
SIT 322 - Scripting Languages 19
Output
• (a && b) => false
• (a || b) => true
• !(a && b) => true
SIT 322 - Scripting Languages 20
[Link]. Operator & Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.
Bitwise Operators 2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
• JavaScript supports the It performs a Boolean exclusive OR operation on each bit of its integer arguments.
following bitwise Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
operators −
4 ~ (Bitwise Not)
• Assume variable A holds It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.
2 and variable B holds 3, 5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in the
then − second operand. New bits are filled with zeros. Shifting a value left by one position is
equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4,
and so on. Ex: (A << 1) is 4.
6 >> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of bits
specified by the right operand. Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero. Ex: (A >>> 1) is 1.
SIT 322 - Scripting Languages 21
[Link](result);
Example [Link](linebreak);
<html> [Link]("(~b) => ");
<body> result = (~b);
<script type = "text/javascript"> [Link](result);
<!-- [Link](linebreak);
var a = 2; // Bit presentation 10 [Link]("(a << b) => ");
var b = 3; // Bit presentation 11 result = (a << b);
var linebreak = "<br />"; [Link](result);
[Link]("(a & b) => "); [Link](linebreak);
result = (a & b); [Link]("(a >> b) => ");
[Link](result); result = (a >> b);
[Link](linebreak); [Link](result);
[Link]("(a | b) => "); [Link](linebreak);
result = (a | b); //-->
[Link](result); </script>
[Link](linebreak); <p>Set the variables to different values and different operators
and then try...</p>
[Link]("(a ^ b) => ");
</body>
result = (a ^ b);
</html>
SIT 322 - Scripting Languages 22
Output
• (a & b) => 2
• (a | b) => 3
• (a ^ b) => 1
• (~b) => -4
• (a << b) => 16
• (a >> b) => 0
SIT 322 - Scripting Languages 23
Assignment Operators [Link]. Operator & Description
1 = (Simple Assignment )
• JavaScript supports Assigns values from the right side operand to the left side operand
the following Ex: C = A + B will assign the value of A + B into C
assignment 2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result
operators − to the left operand. Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the
result to the left operand. Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the
result to the left operand. Ex: C *= A is equivalent to C = C * A
5 /= (Divide and Assignment)
It divides the left operand with the right operand and assigns the
result to the left operand. Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the
left operand. Ex: C %= A is equivalent to C = C % A
SIT 322 - Scripting Languages 24
Example
<html> [Link]("Value of a => (a *= b) => ");
<body> result = (a *= b);
<script type = "text/javascript"> [Link](result);
<!-- [Link](linebreak);
var a = 33;
var b = 10; [Link]("Value of a => (a /= b) => ");
var linebreak = "<br />"; result = (a /= b);
[Link]("Value of a => (a = b) => "); [Link](result);
result = (a = b); [Link](linebreak);
[Link](result); [Link]("Value of a => (a %= b) => ");
[Link](linebreak); result = (a %= b);
[Link]("Value of a => (a += b) => "); [Link](result);
result = (a += b); [Link](linebreak);
[Link](result); //-->
[Link](linebreak);
[Link]("Value of a => (a -= b) => "); </script>
result = (a -= b); <p>Set the variables to different values and different
[Link](result); operators and then try...</p>
[Link](linebreak); </body>
</html>
SIT 322 - Scripting Languages 25
Output
• Value of a => (a = b) => 10
• Value of a => (a += b) => 20
• Value of a => (a -= b) => 10
• Value of a => (a *= b) => 100
• Value of a => (a /= b) => 10
• Value of a => (a %= b) => 0
SIT 322 - Scripting Languages 26
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript:
the conditional operator (? :) and the typeof operator.
• Conditional Operator (? :)
• The conditional operator first evaluates an expression for a true or
false value and then executes one of the two given statements
depending upon the result of the evaluation.
[Link] Operator and Description
.
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
SIT 322 - Scripting Languages 27
Example
<html> [Link] ("((a < b) ? 100 : 200) => ");
<body> result = (a < b) ? 100 : 200;
<script type = "text/javascript"> [Link](result);
<!-- [Link](linebreak);
var a = 10; //-->
var b = 20; </script>
var linebreak = "<br />"; <p>Set the variables to different values
[Link] ("((a > b) ? 100 : 200) => "); and different operators and then try...</p>
result = (a > b) ? 100 : 200; </body>
[Link](result); </html>
[Link](linebreak);
•
Output:
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
SIT 322 - Scripting Languages 28
typeof Operator
Type String Returned by typeof
• The typeof operator is a unary
operator that is placed before its Number "number"
single operand, which can be of any
type. Its value is a string indicating String "string"
the data type of the operand. Boolean "boolean"
• The typeof operator evaluates to Object "object"
"number", "string", or "boolean" if its
operand is a number, string, or Function "function"
boolean value and returns true or
Undefined "undefined"
false based on the evaluation.
• Here is a list of the return values for Null "object"
the typeof Operator.
SIT 322 - Scripting Languages 29
Example
<html> [Link](linebreak);
<body> result = (typeof a == "string" ? "A is String" :
<script type = "text/javascript"> "A is Numeric");
<!-- [Link]("Result => ");
var a = 10; [Link](result);
var b = "String"; [Link](linebreak);
var linebreak = "<br />"; //-->
result = (typeof b == "string" ? "B is String" : </script>
"B is Numeric"); <p>Set the variables to different values and
[Link]("Result => "); different operators and then try...</p>
[Link](result); </body>
</html>
SIT 322 - Scripting Languages 30
JavaScript - if...else Statement
• While writing a program, there may be a situation when you need to
adopt one out of a given set of paths. In such cases, you need to use
conditional statements that allow your program to make correct
decisions and perform right actions.
• JavaScript supports conditional statements which are used to perform
different actions based on different conditions. Here we will explain
the if..else statement.
SIT 322 - Scripting Languages 31
Flow Chart of if-else
The following flow chart shows how
the if-else statement works.
• JavaScript supports the following
forms of if..else statement −
✓if statement
✓if...else statement
✓if...else if... statement.
SIT 322 - Scripting Languages 32
if statement
if statement
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
SIT 322 - Scripting Languages 33
Example
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
[Link]("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html
SIT 322 - Scripting Languages 34
if...else statement
• The 'if...else' statement is the next form of control statement that
allows JavaScript to execute statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
SIT 322 - Scripting Languages 35
Example
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
if( age > 18 ) {
[Link]("<b>Qualifies for driving</b>");
} else {
[Link]("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
SIT 322 - Scripting Languages 36
if...else if... statement
• The if...else if... statement is an advanced form of if…else that allows JavaScript to
make a correct decision out of several conditions.
Syntax : The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
SIT 322 - Scripting Languages 37
<html> [Link]("<b>Economics
<body> Book</b>");
<script type = "text/javascript"> } else {
<!-- [Link]("<b>Unknown
Book</b>");
var book = "maths"; }
if( book == "history" ) { //-->
[Link]("<b>History </script>
Book</b>");
} else if( book == "maths" ) { <p>Set the variable to different value and
then try...</p>
[Link]("<b>Maths </body>
Book</b>");
} else if( book == "economics" ) { <html>
SIT 322 - Scripting Languages 38
JavaScript - While Loops
• While writing a program, you may encounter a situation where you need to
perform an action over and over again. In such situations, you would need to
write loop statements to reduce the number of lines.
• JavaScript supports all the necessary loops to ease down the pressure of
programming.
• The while Loop
• The most basic loop in JavaScript is the while loop which would be discussed in
this chapter. The purpose of a while loop is to execute a statement or code block
repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.
SIT 322 - Scripting Languages 39
• Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
SIT 322 - Scripting Languages 40
<html> [Link]("Loop stopped!");
<body> //-->
<script type = "text/javascript"> </script>
<!-- <p>Set the variable to different
var count = 0; value and then try...</p>
[Link]("Starting Loop "); </body>
while (count < 10) { </html>
[Link]("Current Count :
" + count + "<br />");
count++;
}
SIT 322 - Scripting Languages 41
The do...while Loop
• The do...while loop is similar to
the while loop except that the condition
check happens at the end of the loop. This
means that the loop will always be
executed at least once, even if the
condition is false.
• Flow Chart
• The flow chart of a do-while loop would be
as follows −
SIT 322 - Scripting Languages 42
• Syntax : The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
• Note − Don’t miss the semicolon used at the end of the do...while loop.
SIT 322 - Scripting Languages 43
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
[Link]("Starting Loop" + "<br />");
do {
[Link]("Current Count : " + count + "<br />");
count++;
}
while (count < 5);
[Link] ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
SIT 322 - Scripting Languages 44