HTML5 XP - Session 13 PDF
HTML5 XP - Session 13 PDF
nl
O
se
U
tre
en
Session: 13
C
h
ec
nl
Explain regular expressions in JavaScript
O
Explain decision-making statements in JavaScript
se
U
tre
en
C
h
ec
pt
rA
Fo
se
U
JavaScript provides different types of operators to perform simple to complex
tre
calculations and evaluations.
en
C
Certain operators are also used to construct relational and logical statements.
These statements allow implementing decision and looping constructs.
h
ec
pt
rA
Fo
se
The specified action either changes the value of the variable or generates a new
U
value.
tre
en
An operation requires minimum one symbol and some value.
C
Symbol is called an operator and it specifies the type of action to be performed
h
on the value.
ec
pt
rA
nl
O
Unary operators - Operates on a single operand.
se
U
Binary operators - Operates on two operands.
tre
en
Ternary operators - Operates on three operands.
C
h
ec
pt
rA
Fo
O
se
JavaScript provides a predefined set of operators that allow performing different
operations.
U
tre
JavaScript operators are classified into six categories based on the type of
en
action they perform on operands.
C
Six categories of operators are as follows:
h
ec
Arithmetic operators
Relational operators
pt
Logical operators
rA
Assignment operators
Bitwise operators
Fo
Special operators
nl
O
Perform basic arithmetic operations on two operands.
se
Operator appears in between the two operands, which allow you to perform
computations on numeric and string values.
U
Following table lists arithmetic operators.
tre
Arithmetic Description Example
en
Operator
+ (Addition)
C
Performs addition. In case of string values, it behaves as a string
concatenation operator and appends a string at the end of the other
45 + 56
h
ec
- (Subtraction) Performs subtraction. If a larger value is subtracted from a smaller value, it 76-78
returns a negative numeric value
pt
rA
/ (Division) Divides the first operand by the second operand and returns the quotient 24 / 8
Divides the first operand by the second operand and returns the remainder 90 % 20
Fo
% (Modulo)
y
The Code Snippet demonstrates the use of arithmetic operators.
nl
O
<SCRIPT>
var loanAmount = 34500;
se
var interest = 8;
var interestAmount, totalAmount;
U
interestAmount = loanAmount * (interest / 100);
totalAmount = loanAmount + interestAmount;
tre
document.write(“<B>Total amount to be paid ($):</B>” +
totalAmount + “<BR />”);
en
</SCRIPT>
C
h
ec
pt
rA
Fo
nl
O
Increment operator (++) increases the value by 1, while the decrement operator (--)
decreases the value by 1.
se
These operators can be placed either before or after the operand.
U
Operator if placed before the operand, expression is called pre-increment or pre-
tre
decrement. Operator if placed after the operand, expression is called post-increment or
post-decrement.
en
Following table lists arithmetic operators.
y
The Code Snippet demonstrates the use of unary operators in JavaScript.
nl
O
<SCRIPT>
var number = 3;
se
alert(‘Number after increment = ‘ + ++number);
alert(‘Number after decrement = ‘ + number--);
U
</SCRIPT>
tre
en
C
h
ec
pt
rA
Fo
nl
O
After making a comparison, they return a boolean value namely, true or false.
se
U
Expression consisting of a relational operator is called as the relational
expression or conditional expression.
tre
Following table lists the relational operators.
en
Relational Description Example
Operators
C
h
90 == 91
ec
== (Equal) Verifies whether the two operands are equal
99 != 98
pt
=== (Strict Equal) Verifies whether the two operands are equal and are of the same type numTwo = 1
Fo
!== (Strict Not Verifies whether the two operands are unequal and whether are not 90 % 20
Equal) of the same type
nl
O
Relational Description Example
Operators
se
> (Greater Than) Verifies whether the left operand is greater than the right operand 97 > 95
U
94 < 96
tre
< (Less Than) Verifies whether the left operand is less than the right operand
92 >= 93
en
>= (Greater Than Verifies whether the left operand is greater than or equal to the right
or Equal) operand
O
<SCRIPT>
se
var firstNumber = 3;
var secondNumber = 4;
U
document.write(‘First number is greater than the second
number: ‘ + (firstNumber > secondNumber));
tre
document.write(‘<br/>First number is less than the
second number: ‘ + (firstNumber < secondNumber));
en
document.write(‘<br/>First number is equal to the second
number: ‘ + (firstNumber == secondNumber));
</SCRIPT>
C
h
ec
pt
rA
Fo
nl
O
They belong to the category of relational operators, as they return a boolean
value.
se
U
Following table lists the logical operators.
tre
Logical Description Example
Operators
en
&& (AND) Returns true, if either of the operands are evaluated to true. If first (x == 2) &&
C
operand evaluates to true, it will ignore the second operand (y == 5)
Returns false
h
ec
|| (OR) Returns true, if either of the operands are evaluated to true. If first (x == 2) || (y ==
rA
nl
The Code Snippet demonstrates the use of logical AND operator in JavaScript.
O
<SCRIPT>
se
var name = “John”;
var age = 23;
U
alert(‘John\’s age is greater than or equal to 23 years : ‘ +
((name==”John”) && (age >= 23)));
tre
</SCRIPT>
en
C
h
ec
pt
rA
Fo
nl
on the left side by using the equal to operator (=).
O
Simple assignment operator - Is the ‘=’ operator which is used to assign a value
or result of an expression to a variable.
se
U
Compound assignment operator - Is formed by combining the simple
assignment operator with the arithmetic operators.
tre
Following table lists the assignment operators.
en
Expressions Description Example
C numOne = 12
h
numOne += 6; numOne = numOne + 6
ec
O
se
They return standard decimal values.
U
Compound assignment operator - Is formed by combining the simple
tre
assignment operator with the arithmetic operators.
en
C
h
ec
pt
rA
Fo
y
Following table lists the bitwise operators in JavaScript.
nl
O
Bitwise Description Example
Operators
se
& (Bitwise Compares two bits and returns 1 if both of them are 1 or else 00111000
U
AND) returns 0 Returns 00011000
tre
~ (Bitwise Inverts every bits of the operand and is a unary operator ~00010101
NOT) Returns 11101010
en
| (Bitwise OR) Compares two bits and returns 1 if the corresponding bits of either 00111000
C
or both the operands is 1
h Returns 00111100
O
categories of JavaScript operators.
se
Such operators are referred to as the special operators.
U
tre
Following table lists the special operators in JavaScript.
en
Special Description
Operators
C
h
ec
, (comma) Combines multiple expressions into a single expression, operates on them in
the left to right order and returns the value of the expression on the right.
pt
?: (conditional) Operates on three operands where the result depends on a condition. It is also
rA
called as ternary operator and has the form condition, ? value1:value2. If the
condition is true, the operator obtains value1 or else obtains value2.
Fo
typeof Returns a string that indicates the type of the operand. The operand can be a
string, variable, keyword, or an object.
nl
O
<SCRIPT>
var age = parseInt(prompt(“Enter age”, “Age”))
se
status = ((typeof(age) == “number” && (age >= 18))
?“eligible” : “not eligible”;
U
document.write(‘You are ‘ + age + ‘ years old, so you are ‘
+status + ‘ to vote.’);
tre
</SCRIPT>
en
C
h
ec
pt
rA
Fo
y
Following table lists the precedence of the operators from the highest to the
nl
lowest and their associativity.
O
se
U
tre
en
C
h
ec
pt
rA
Fo
nl
particular textual content.
O
Allow handling of textual data effectively as it allows searching and replacing
se
strings.
U
Allows handling of complex manipulation and validation, which could otherwise
be implemented through lengthy scripts.
tre
There are two ways to create regular expressions which are as follows:
en
Literal Syntax:
RegExp() Constructor:
rA
• Is useful when the Web page designer does not know the pattern at the time of
scripting.
• Method dynamically constructs a regular expression when the script is
Fo
executed.
• Syntax is as follows:
• var variable_name = new RegExp(“regular_expression_pattern”,“flag”);
© Aptech Ltd. Operators and Statements / Session 13 22
y
RegExp object supports methods that are used for searching the pattern in a
nl
string. They are as follows:
O
se
test(string) - Tests a string for matching a pattern and returns a Boolean value
of true or false. The Boolean value indicates whether the pattern exists or not in
U
the string. The method is commonly used for validation.
tre
exec(string) - Executes a string to search the matching pattern within it. The
en
method returns a null value, if pattern is not found. In case of multiple matches,
it returns the matched result set.
C
h
ec
pt
rA
Fo
y
nl
regarding the string.
O
Following table lists the properties of the RegExp object:
se
Audio
Attributes Description
U
tre
$n Represents the number from 1 to 9. It stores the recently handled parts of a
parenthesized pattern of a regular expression.
en
aif Indicates whether the given regular expression contain a g flag. The g flag specifies that
all the occurrences of a pattern will be searched globally, instead of just searching for
the first occurrence.
C
h
aifc Indicates whether the given regular expression contains an i flag.
ec
Stores the location of the starting character of the last match found in the string. In case
pt
aiff
of no match, the value of the property is -1.
rA
y
The Code Snippet displays the use of a regular expression.
nl
O
<SCRIPT>
var zipcodepattern = /^\d{5}$/;
se
var zipcode = zipcodepattern.exec(prompt(‘Enter ZIP Code:’));
if(zipcode != null)
U
{
alert(‘Valid ZIP Code.’);
tre
alert(‘Regular Expression Pattern: ‘ + zipcodepattern.source);
}
en
else
{
} C
alert(‘Invalid ZIP Code – Format xxxxx.’);
h
</SCRIPT>
ec
pt
rA
Fo
O
regular expression pattern are as follows:
se
Position Matching
U
Character Classes
Repetition
tre
Alternation and Grouping
Back Reference
en
C
h
ec
pt
rA
Fo
O
a specific position within a string.
se
Following table lists the various position matching symbols.
U
Symbol Description Example
tre
^ Denotes the start of a string /^Good/ matches “Good” in “Good
en
night”, but not in “A Good Eyesight”
\B
not in “anomaly”
Fo
nl
for specifying patterns.
O
se
These classes are formed by placing a set of characters within the square
brackets.
U
tre
Following table lists the various character classes symbols.
en
Symbol Description Example
[xyz]
C
Matches one of the characters specified
within the character set
/^Good/ matches “Good” in “Good night”,
but not in “A Good Eyesight”
h
ec
nl
O
Symbol Description Example
se
\W Matches a non-word character /\W/
Matches “%” in “800%”
U
\d Matches a digit between 0 to 9 /\d/
tre
Matches “4” in “A4”
en
\D Searches for a non-digit /\D/
Matches “ID” in “ID 2246”
\s
C
Searches any single space character including
space, tab, form feed, and line feed
/\s\w*/
Matches “ bar” in “scroll bar”
h
ec
O
frequently in a string.
se
Following table lists the various repetition matching symbols.
U
Symbol Description Example
tre
{x} Matches x number of occurrences of a regular /\d{6}/
Matches exactly 6 digits”
en
expression
/\s{4,}/
C
{x, } Matches either x or additional number of
occurrences of a regular expression Matches minimum 4 whitespace characters
h
ec
O
individual entity or adding the ‘OR’ logic for pattern matching.
se
Following table lists the various alternation and grouping character symbols.
U
Symbol Description Example
tre
() Organizes characters together in a group to /(xyz)+(uvw)/
Matches one or more number of
en
specify a set of characters in a string
occurrences of “xyz” followed by one
occurrence of “uvw”
| C
Combines sets of characters into a single /(xy)|(uv)|(st)/
h
regular expression and then matches any of Matches “xy” or “uv” or “st”
ec
O
individual entity or adding the ‘OR’ logic for pattern matching.
se
Following table lists the various alternation and grouping character symbols.
U
Symbol Description Example
tre
()\n Matches a parenthesized set within the /(\w+)\s+\1/
Matches any word occurring twice in a line,
en
pattern, where n is the number of the
parenthesized set to the left such as “hello hello”. The \1 specifies that
the word following the space should match
pattern
Fo
O
keywords that perform a specific action to fulfill a required task.
se
Statements help you build a logical flow of the script.
U
tre
In JavaScript, a statement ends with a semicolon.
en
C
JavaScript is written with multiple statements, wherein the related statements
are grouped together are referred to as block of code and are enclosed in curly
h
braces.
ec
pt
O
if
se
if-else
if-else if
U
switch
tre
en
C
h
ec
pt
rA
Fo
nl
O
If this condition is true, the block following the if statement is executed.
se
U
If the condition is false, the block after the if statement is not executed and the
immediate statement after the block is executed.
tre
en
C
h
ec
pt
rA
Fo
y
nl
O
<SCRIPT>
var quantity = prompt(‘Enter quantity of product:’,0);
se
if(quantity < 0 || isNaN(quantity))
{
U
alert(‘Please enter a positive number.’);
}
tre
</SCRIPT>
en
C
h
ec
pt
rA
Fo
O
Sometimes it is required to define a block of statements to be executed when a
se
condition is evaluated to false.
U
if-else statement begins with the if block, which is followed by the else block.
tre
en
The else block begins with the else keyword followed by a block of statements to
be executed upon the false condition.
C
h
ec
pt
rA
Fo
y
nl
O
<SCRIPT>
var firstNumber = prompt(‘Enter first number:’,0);
se
var secondNumber = prompt(‘Enter second number’,0);
var result = 0;
U
if (secondNumber == 0)
{
tre
alert(‘ERROR Message: Cannot divide by zero.’);
}
en
else
{
C
result = firstNumber/secondNumber;
alert(“Result: “ + result);
h
}
ec
</SCRIPT>
pt
rA
Fo
O
executed for each condition.
se
Flow of these statements begins with the if statement followed by multiple else if
statements and finally by an optional else block.
U
tre
Entry point of execution in these statements begins with the if statement.
en
If the condition in the if statement is false, the condition in the immediate else if
statement is evaluated.
C
h
Also referred to as the if-else-if ladder.
ec
pt
rA
Fo
y
nl
O
<SCRIPT>
var percentage = prompt(‘Enter percentage:’,0);
se
if (percentage >= 60)
{
U
alert (‘You have obtained the A grade.’);
}
tre
else if (percentage >= 35 && percentage < 60)
{
en
alert (‘You have obtained the B class.’);
}
else
{ C
h
alert (‘You have failed’);
ec
}
</SCRIPT>
pt
rA
Fo
O
se
Flow of the nested-if statements starts with the if statement, which is referred to
as the outer if statement.
U
Outer if statement consists of multiple if statements, which are referred to as the
tre
inner if statements.
en
Inner if statements are executed only if the condition in the outer if statement is
true.
C
h
Each of the inner if statements is executed but, only if the condition in its
ec
y
nl
O
<SCRIPT>
var username = prompt(‘Enter Username:’);
se
var password = prompt(‘Enter Password:’);
if (username != “” && password != “”)
U
{
if (username == “admin” && password == “admin123”)
tre
{
alert(‘Login Successful’);
en
}
else
{
alert (‘Login Failed’); C
h
}
ec
}
</SCRIPT>
pt
rA
Fo
O
statements.
se
To simplify coding and to avoid using multiple if statements, switch-case
statement can be used.
U
tre
switch-case statement allows comparing a variable or expression with multiple
values.
en
C
h
ec
pt
rA
Fo
y
nl
O
<SCRIPT>
var designation = prompt(‘Enter designation:’);
se
switch (designation)
{
U
case ‘Manager’:
alert (‘Salary: $21000’);
tre
break;
case ‘Developer’:
en
alert (‘Salary: $16000’);
break;
default:
C
alert (‘Enter proper designation.’);
h
break;
ec
}
</SCRIPT>
pt
rA
Fo
y
An operator specifies the type of operation to be performed on the values of
nl
variables and expressions.
O
JavaScript operators are classified into six categories based on the type of
se
action they perform on operands.
U
There are six category of operators namely, Arithmetic, Relational, Logical,
tre
Assignment, Bitwise, and Special operators.
en
Operators in JavaScript have certain priority levels based on which their
execution sequence is determined.
C
h
A regular expression is a pattern that is composed of set of strings, which is to
ec
In JavaScript, there are two ways to create regular expressions namely, literal
rA