0% found this document useful (0 votes)
2 views45 pages

Chapter 4 Javascript

The document provides an overview of JavaScript, detailing its purpose for client-side and server-side programming, as well as its integration with HTML documents. It covers JavaScript's syntax, variable declaration, primitive types, operators, and methods for output and input. Additionally, it discusses the Math and Date objects, along with type conversions and string manipulation techniques.

Uploaded by

lujainalkousheh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views45 pages

Chapter 4 Javascript

The document provides an overview of JavaScript, detailing its purpose for client-side and server-side programming, as well as its integration with HTML documents. It covers JavaScript's syntax, variable declaration, primitive types, operators, and methods for output and input. Additionally, it discusses the Math and Date objects, along with type conversions and string manipulation techniques.

Uploaded by

lujainalkousheh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The University of Jordan

Chapter 4 JavaScript
Overview of JavaScript

• The original goal of JavaScript was to provide programming capability


at both the server and the client ends of a Web connection.
• Client-side JavaScript is embedded in HTML documents and is
interpreted by the browser.
• Interactions with users through form elements, such as buttons and
menus, can be conveniently described in JavaScript.
• Because button clicks and mouse movements are easily detected with
JavaScript.
• For example, when a user moves the mouse cursor from a text box, JavaScript can
detect that movement and check the appropriateness of the text box’s value

The University of Jordan


Browsers and HTML-JavaScript Documents

• If an HTML document does not include embedded scripts, the


browser reads the lines of the document and renders its window
according to the tags, attributes, and content it finds.
• When a JavaScript script is encountered in the document, the
browser uses its JavaScript interpreter to execute the script.
• When the end of the script is reached, the browser goes back
to reading the HTML document and displaying its content.

The University of Jordan


Browsers and HTML-JavaScript Documents

• There are two different ways to embed JavaScript in an


HTML document: internal and external.
• In internal JavaScript, the code physically resides in the
HTML document.
• In external JavaScript, the code is placed in its own file,
separate from the HTML document.

The University of Jordan


General Syntactic Characteristics
• Scripts can appear directly as the content of a <script> tag.
• The type attribute of <script> must be set to "text/javascript".
• The JavaScript script can be indirectly embedded in an HTML
document with the src attribute of a <script> tag, whose value is the
name of a file that contains the script.
<script type = "text/javascript" src = "tst_number.js" > </script>
• The script element requires the closing tag.
• In JavaScript, identifiers, or names, are similar to those of other
common programming languages.
• They must begin with a letter, an underscore (_), or a dollar sign ($).
The University of Jordan
General Syntactic Characteristics
• The letters in a variable name in JavaScript are case sensitive,
meaning that FRIZZY, Frizzy, FrIzZy, frizzy, and friZZy are all distinct
names.
• JavaScript has 25 reserved words

The University of Jordan


General Syntactic Characteristics
• JavaScript has two forms of comments, (//) for single line and (/*)(*/) for
multi-line.
• The JavaScript interpreter tries to make semicolons unnecessary, but it
does not always work.
• When the end of a line coincides with what could be the end of a statement,
the interpreter effectively inserts a semicolon there.
• But this implicit insertion can lead to problems.
• For example, consider the following lines of code:
return
x;
• The interpreter will insert a semicolon after return, because return need
not be followed by an expression, making x an invalid.
• The best way is to add the semicolon explicitly.
The University of Jordan
Primitives, Operations, and Expressions:
Primitive Types

• JavaScript has five primitive types: Number, String,


Boolean, Undefined, and Null.
• JavaScript includes predefined objects that are closely
related to the Number, String, and Boolean types, named
Number, String, and Boolean, respectively.
• Each contains a property that stores a value of the
corresponding primitive type.

The University of Jordan


Primitives, Operations, and Expressions:
Primitive Types

• The difference between primitives and objects is shown in


the following example. Suppose that prim is a primitive
variable with the value 17 and obj is a Number object whose
property value is 17.

The University of Jordan


Primitives, Operations, and Expressions: Other
Primitive Types

• The only value of type Null is the reserved word null, which
indicates no value.
• The only value of type Undefined is undefined.
• Unlike null, there is no reserved word undefined.
• If a variable has been explicitly declared, but not assigned a
value, it has the value undefined. If the value of an undefined
variable is displayed, the word undefined is displayed.
• The only values of type Boolean are true and false.
The University of Jordan
Declaring Variables

• Variables are not typed; values are.


• A variable can have the value of any primitive type, or it can be a
reference to any object.
• A variable can be declared either by assigning it a value, in which case
the interpreter implicitly declares it to be a variable, or by listing it in a
declaration statement that begins with the reserved word var.
<script>
x = 10;
var y = 5;
</script>

The University of Jordan


Numeric Operators

• JavaScript has the typical collection of numeric operators: the binary operators +
for addition, - for subtraction, * for multiplication, / for division, and % for
modulus.
• The unary operators are plus (+), negate (-), decrement (--), and increment (++).
• For the increment and decrement operators, if the operator follows the variable, the
expression evaluates to the current value of the variable and then the value of the
variable is changed.
<script>
x = 10;
x = ++x * 2 // =22
x = x++ * 2 // =44
</script>

The University of Jordan


Numeric Operators

• The precedence rules of a language specify which operator is evaluated first when two
operators with different precedence are adjacent in an expression.
<script>
a*b+1
</script>

• The associativity rules of a language specify which operator is evaluated first when two
operators with the same precedence are adjacent in an expression.
<script>
a*b/1
</script>

The University of Jordan


Numeric Operators

• Parentheses can be used to force any desired precedence.


<script>
var a = 2,
b = 4,
c,
d;
c = 3 + a * b; // * is first, so c is now 11 (not 24)
d = b / a / 2; // / associates left, so d is now 1 (not 4)
e = (3+a) * b // () is first, so e is now 20
</script>

The University of Jordan


Screen Output and Keyboard Input
• The output can be displayed in different ways.
• The first one is using document object.
• The most interesting and useful method that can be used with document
object is write, which is used to create output, which is dynamically created
HTML document content.
[Link](“ Hello"); // the output is Hello
x = 10;
[Link]("X = ", x); // the output is X = 10

• To add a new line, <br/> tag can be used with this method.
x = 10;
y = 5;
[Link]("X = ", x, "<br/>", "Y = ", y);
The University of Jordan
Screen Output and Keyboard Input

• The second way of displaying outputs is using the Window object.


• Three main methods can be used with the Window object, including alert, confirm,
and prompt.
• The alert method opens a dialog window and displays its parameter in that window.
• It also displays an OK button.
• To add a new line, "\n" can be used with this method.
• To add many components (+) sign can be used instead of (,).
x = 10;
y = 5;
[Link]("X = " + x+ "\n"+ "Y = "+ y);

The University of Jordan


Screen Output and Keyboard Input

• The confirm method opens a dialog window in which the method displays its string
parameter, along with two buttons: OK and Cancel.
• confirm returns a Boolean value that indicates the user’s button input: true for OK
and false for Cancel.
var question = [Link]("Do you want to continue this download?");

[Link](“question = “ + question);

• If press ok, the value of question will be true. If press cancel, its value will be false.

The University of Jordan


Screen Output and Keyboard Input

• The prompt method creates a dialog window that contains a text box used
to collect a string of input from the user, which prompt returns as its value.
• As with confirm, this window also includes two buttons: OK and Cancel.
• The collected string will be stored in a variable.
name = prompt("What is your name?");
[Link]("My name is ", name);

• If press ok, the string you entered will be stored


in the name variable.

The University of Jordan


Screen Output and Keyboard Input

• The third way of displaying outputs is innerHTML.


• This method is used to access an HTML element and display it.
• innerHTML can be used with the [Link](id) method.
• The id attribute defines the HTML element. The innerHTML property defines the
HTML content.
<p>5 + 4 = </p>
<p id="demo"> </p>
<script>
[Link]("demo").innerHTML = 5 + 4;
</script>

• The browser will display the number 9 (result of 5 + 4) at the same position of id
demo
The University of Jordan
The Math Object

• The Math object provides a collection of properties of Number objects and methods
that operate on Number objects.
• The most common Math objects are:
• sin for sine. [Link](0);
• cos for cosine. [Link](0);
• floor to truncate a number. [Link](2.7); // =2
• round to round a number. [Link](2.7); // =3
• max to return the largest of two given numbers. [Link](2,3); // =3
• min to return the smallest of two given numbers. [Link](2,3); // =2

The University of Jordan


The Math Object
Method Description Example Constant Description Value
[Link](x) Returns the absolute value of x [Link](-5.6) = 5.6 Base of natural
Math.E ≈ 2.718
Rounds x up to the nearest logarithm (e)
[Link](x) [Link](9.2) = 10
integer
Natural logarithm
[Link](x) Returns cosine of x (in radians) [Link](0) = 1 Math.LN2 ≈ 0.693
of 2
[Link](x) Returns e raised to the power x [Link](1) = 2.71828 Natural logarithm
Math.LN10 ≈ 2.302
Rounds x down to the nearest of 10
[Link](x) [Link](9.2) = 9
integer
Base 2 logarithm
Returns natural logarithm of x Math.LOG2E ≈ 1.442
[Link](x) [Link](2.71828) = 1 of e
(base e)
Base 10
Math.LOG10E ≈ 0.434
[Link](x, y) Returns the larger of two values [Link](2.3, 12.7) = 12.7 logarithm of e
Ratio of a circle’s ≈
Returns the smaller of two
[Link](x, y) [Link](2.3, 12.7) = 2.3 [Link] circumference to 3.141592653589
values
diameter 793
[Link](x, y) Returns x raised to the power y [Link](2, 7) = 128
Square root of
[Link](x) Rounds x to the nearest integer [Link](9.75) = 10 Math.SQRT1_2 ≈ 0.707
0.5
[Link](x) Returns sine of x (in radians) [Link](0) = 0
Math.SQRT2 Square root of 2 ≈ 1.414
[Link](x) Returns square root of x [Link](9) = 3
[Link](x) Returns tangent of x (in radians) [Link](0) = 0

The University of Jordan


The Number Object

• The Number object includes a collection of useful properties that have


constant values.
Number.MIN_VALUE

The University of Jordan


The Number Object

• To determine whether a variable has the NaN value, the predefined


predicate function isNaN() must be used.
X=2;
isNaN(x); // =false

• The toString method converts the number through which it is called to a


string.
x=2;
y = [Link]();

The University of Jordan


The String Catenation Operator

• String catenation is specified with the operator denoted by a plus sign (+).
x="First ";
y = x + "Name"; // First Name

x="First ";
z = " and ";
y = "Last Name";
k = x + z+ y; // First and Last Name

The University of Jordan


Implicit Type Conversions

• In general, when a value of one type is used in a position that requires a value of a
different type, JavaScript attempts to convert the value to the type that is required.
• For example:
"August " + 1977
• In this expression, because the left operand is a string, the operator is considered to
be a catenation operator. This forces string context on the right operand, so the right
operand is implicitly converted to a string.
• Therefore, the expression evaluates to:
"August 1997"

The University of Jordan


Implicit Type Conversions

• The number 1977 in the following expression is also coerced to


a string, because August can’t be converted to a number:
1977 + "August"
• Now consider the following expression:
7 * "3"
• In this expression, the operator is one that is used only with
numbers. This forces numeric context on the right operand.
Therefore, JavaScript attempts to convert it to a number. The
output will be 21.

The University of Jordan


Explicit Type Conversions
• There are several different ways to force type conversions, primarily between
strings and numbers.
• Numbers can be converted to string with the String constructor, as in the
following statement:
x=5;
y = String(x) + 10; // y = 510
• This conversion can also be done with the toString method:
x=5;
y = [Link]()+ 10; // y = 510
• Strings can be explicitly converted to numbers in several different ways. One way
is with the Number constructor:
x="5";
y = Number(x)+ 10; // 15

The University of Jordan


String Properties and Methods

• Several Methods can be used with the String.


• length property to return the number of characters in a string:
x="Welcome";
y = [Link]; // y = 7 (number of characters in x)
• The most commonly used String methods:
x="Welcome";
y = [Link](3); // y= c
y=[Link]('W'); // y= 0
y=[Link](2, 4); // y= lc
y=[Link](); // y= welcome

The University of Jordan


The typeof Operator

• The typeof operator returns the type of its single operand.


• typeof produces "number", "string", or "boolean" if the operand is of
primitive type Number, String, or Boolean, respectively.
• If the operand is a null, typeof produces "object".
• If the operand is a variable that has not been assigned a value, typeof
produces "undefined“.
• y = typeof("Welcome"); // y= string
• y = typeof(123); // y= number
• y = typeof(false); // y= boolean
• y = typeof(null); // y= object

The University of Jordan


The Date Object

• Sometimes it is convenient to be able to create objects that represent a


specific date and time and then manipulate them.
• These capabilities are available in JavaScript through the Date object
and its rich collection of methods.
• A Date object is created with the new operator and the Date constructor,
which has several forms.
• When we focus on the current date and time, we use only the simplest
Date constructor, which takes no parameters and builds an object with
the current date and time for its properties.
today = new Date();

The University of Jordan


The Date Object
• The date and time properties of a Date object are in two
forms: local and Coordinated Universal Time (UTC).
• We deal in this section with local time only.

The University of Jordan


Usage of The Date Object
var today = new Date();
var dateString = [Link]();
var year = [Link]();
var timeMilliseconds = [Link]();
var hour = [Link]();
var minute = [Link]();
var second = [Link]();
var millisecond = [Link]();

[Link]("Date: " + dateString + "<br />",


"Year: " + year + "<br />",
"Time in milliseconds: " + timeMilliseconds + "<br />",
"Hour: " + hour + "<br />",
"Minute: " + minute + "<br />",
"Second: " + second + "<br />",
"Millisecond: " + millisecond + "<br />");

The University of Jordan


Control Statements

• The expressions upon which statement flow control can be based include primitive
values, relational expressions, and compound expressions.
• The result of evaluating a control expression is one of the Boolean values true or
false.
• Lists the relational operators.

▪ The last two operators in Table


disallow type conversion of either
operand.
▪ Thus, the expression "3" === 3
evaluates to false, while "3" == 3
evaluates to true.

The University of Jordan


Control Statements
• JavaScript has operators for the AND, OR, and NOT Boolean operations. These are &&
(AND), || (OR), and ! (NOT).
• The precedence and associativity of all operators are shown in the Table.

The University of Jordan


Selection Statements

• The selection statements (if-then and if-then-else) of JavaScript are


similar to those of the common programming languages.
• The general format:
if (expression){
}
else if(expression){
}
else {}

The University of Jordan


Selection Statements: Example
Write a JavaScript program that declares two variables a and b, assigns
them values, and displays a message indicating whether a is greater than b
or less than b.
<script>
a = 5;
b = 10;
if (a > b){
[Link]("a is greater than b <br />");}
else if (a < b){
[Link]("a is less than b <br />"); }
</script>

The University of Jordan


Selection Statements: Example
<h2>Student Grade Result</h2>
<p id="result"></p>
<script>
• Write a JavaScript program that var score = prompt("Enter your score:");
asks the user to enter a numeric score = Number(score);
score, then determines the grade var grade;
based on the following if (score >= 90) {
conditions: grade = "A";
} else if (score >= 80) {
• 90 and above → A grade = "B";

• 80–89 → B } else if (score >= 70) {


grade = "C";
• 70–79 → C } else if (score >= 60) {

• 60–69 → D grade = "D";


} else {
• Below 60 → F grade = "F"; }
[Link]("result").innerHTML = "Score: " + score + "<br>Grade: " + grade;
• Display the grade in the browser.
</script>

The University of Jordan


Exercise

• Develop a JavaScript program that calculates a discount based


on the purchase amount entered by the user:
• Above 100 → 20% discount
• 50–100 → 10% discount
• Below 50 → No discount
• Display the final message.

The University of Jordan


The switch Statement
• JavaScript has a switch statement that is similar to that of Java.
• The form of this construct is as follows:
switch (expression) {
case value_1:
// statement(s)
case value_2:
// statement(s)
...
[default:
// statement(s) ]
}
The University of Jordan
The switch Statement
<script>
• Write a JavaScript program that asks the user to Num = prompt("What is your Number?", "");
enter a number and displays its corresponding switch (Num) {
word using a switch statement.
case "0": [Link]("Zero");
The program should handle the following cases:
break;
0 → "Zero" case "1": [Link]("One");
1 → "One" break;
4 → "Four" case "4": [Link]("Four");
8 → "Eight" break;
case "8": [Link]("Eight");
For any other value, display an error message.
break;
default: {
[Link]("Error - invalid choice: ", Num, "<br />");}}
</script>

The University of Jordan


Loop Statements

• The general form of the while statement is as follows:


while (control expression)
statement
• The general form of the for statement is as follows:
for (initial expression; control expression; increment expression)
statement
• The initial expression of a for statement can include variable
declarations.

The University of Jordan


Loop Statements: Example
<script>
var sum = 0,
count = 0;
Write a JavaScript program that
while (count <= 10){
computes the sum of integers
sum += count;
from 0 to 10 using:
count++;}
[Link](sum);
• A while loop //-----------------------------------------------------------------------------
var sum = 0,
• A for loop
count;
Display the result for both for (count = 0; count <= 10; count++)
cases. sum += count;
[Link](sum); // 55
</script>

The University of Jordan


Loop Statements: Example
<h2>Student Grade Result</h2>
<p id="result"></p>
<script>
var num = prompt("Enter a number:");
• Develop a JavaScript num = Number(num); // convert to number

program that uses a for var factorial = 1;


if (num < 0) {
loop to calculate the [Link]("result").innerHTML = "Factorial is not defined for
negative numbers.";
factorial of a given } else {
number entered by the for (var i = 1; i <= num; i++) {

user. factorial *= i; }
[Link]("result").innerHTML =
"Factorial of " + num + " is " + factorial; }
</script>

The University of Jordan


Loop Statements
• In addition to the while and for loop statements, JavaScript has a do while statement,
whose form is as follows:
do statement
while (control expression)
• The do-while statement is related to the while statement, but the test for completion is
logically (and physically) at the end, rather than at the beginning, of the loop construct.
• The body of a do-while construct is always executed at least once.
do{
sum += count;
count++;
}while (100 <= 10);
[Link](sum); // 55

The University of Jordan

You might also like