0% found this document useful (0 votes)
12 views53 pages

Lec12 JS

Uploaded by

oomaarhmed2005
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)
12 views53 pages

Lec12 JS

Uploaded by

oomaarhmed2005
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
You are on page 1/ 53

Spring 23-24

Semester 4

Web Technology

Dr. Rodaina Abdelsalam


JavaScript

JS
Outline
1. Conditional statements
2. JavaScript Errors
3. JavaScript Debugging
4. JavaScript Common Mistakes
5. JavaScript Form Validation
Outline
1. Conditional statements
2. JavaScript Errors
3. JavaScript Debugging
4. JavaScript Common Mistakes
5. JavaScript Form Validation
Conditional statements
The conditional statements in JS:
• Use if to specify a block of code to be executed, if a specified
condition is true
• Use else to specify a block of code to be executed, if the same
condition is false
• Use else if to specify a new condition to test, if the first
condition is false
• Use switch to specify many alternative blocks of code to be
executed
The if Statement
• The condition can be a value or an expression.
• Typically, the condition evaluates to a Boolean value, which is true or false.
• If the condition evaluates to true, the if statement executes the statement.
• Otherwise, the if statement passes the control to the next statement after it.

Syntax:
if (condition)
{
// statement; block of code to be executed if the condition is true
}

• Note:
• if is in lowercase letters.
• Uppercase letters (If or IF) will generate a JavaScript error.
The if Statement
Example:
• The following example uses the if statement to check if the age is equal
to or greater than 18 to sign up for our website:
let age = 18;
Output:
if (age >= 18) { console.log('You can sign up'); } You can sign up

• If the age is 16, this will cause the condition to evaluate to false.
Therefore, you won’t see any message in the output
let age = 16;
if (age >= 18) { console.log('You can sign up'); }
The nested if Statement
• It’s possible to use an if statement inside another if statement.
• Example:
let age = 16;
let Gender = ‘Male';
if (Gender == ‘Male')
{ if (age >= 16) Output:
{ console.log('You can join our team'); You can join our team

}
}
• However, in practice, you should avoid using nested if statements as much as possible.
• You can use the && operator to combine the conditions and use an if statements as follows:
let age = 16;
let Gender = ‘Male'; Output:
if (Gender == ‘Male‘ && age >= 16) You can join our team

{ console.log('You can join our team');


}
The else Statement
• Use the else statement to specify a block of code to
be executed if the condition is false .
• Syntax:
if (condition)
{
// statement; block of code to be executed if the condition is true
} else {
// statement; block of code to be executed if the condition is false
}
The else Statement
• Example:
if (age >= 18)
{ console.log('You can sign up'); }
else
{ console.log(‘ Sorry, you can’t sign up'); }
The else if Statement
• Use the else if statement to specify a new condition if the first condition is
false.
• Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
The else if Statement
• Example:
• If time is less than 10:00, create a "Good morning" greeting, if not, but time is less
than 20:00, create a "Good day" greeting, otherwise a "Good evening":
let time = 18
if (time < 10) {
greeting = "Good morning"; Output:
Good Day
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The switch Statement
The switch statement is used to perform different actions based on different conditions
• Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
• This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• If there is no match, the default code block is executed.
The switch Statement
Example
The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:

switch (new Date().getDay()) {


case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
The switch Statement
The break Keyword
• When JavaScript reaches a break keyword, it breaks out of the switch block.
• This will stop the execution inside the switch block.
• It is not necessary to break the last case in a switch block. The block breaks (ends) there
anyway.

• Note: If you omit the break statement, the next case will be executed even if the evaluation
does not match the case.
The switch Statement
The default Keyword
• The default keyword specifies the code to run if there is no case match:
• Example
• The getDay() method returns the weekday as a number between 0 and 6.
• If today is neither Friday (5) nor Saturday (6), write a default message:
switch (new Date().getDay()) {
case 5:
text = "Today is Friday";
break;
case 6:
text = "Today is Saturday";
break;
default:
text = "Looking forward to the Weekend";
}
If we run the code today, the result of text will be:
Looking forward to the Weekend
The switch Statement
Common Code Blocks
• Sometimes you will want different switch cases to use the same code.
• In this example case 3 and 4 share the same code block, and 5 and 6 share another code block:
Example
switch (new Date().getDay()) {
case 3:
case 4:
text = "Soon it is Weekend";
break;
case 5:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
The switch Statement
Switching Details
• If multiple cases matches a case value, the first case is selected.
• If no matching cases are found, the program continues to the default label.
• If no default label is found, the program continues to the statement(s) after
the switch.
Outline
1. Conditional statements
2. JavaScript Errors
3. JavaScript Debugging
4. JavaScript Common Mistakes
5. JavaScript Form Validation
JavaScript Errors
Throw, and Try...Catch...Finally
• The try statement defines a code block to run (to try).
• The catch statement defines a code block to handle any error.
• The throw statement defines a custom error.
• The finally statement defines a code block to run regardless of
the result.
JavaScript Errors
Errors Will Happen!
• When executing JavaScript code, different errors can occur.
• Errors can be coding errors made by the programmer, errors due to wrong input, and
other unforeseeable things.
JavaScript try and catch
• The try statement allows you to define a block of code to be tested for errors
while it is being executed.
• The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
• The JavaScript statements try and catch come in pairs:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
JavaScript Errors
Example
In this example we misspelled "alert" as "adddlert" to deliberately produce an error:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Error Handling</h2>
<p>How to use <b>catch</b> to display an error.</p>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
Note: JavaScript catches adddlert as an error, and executes the catch code to handle it.
JavaScript Errors
JavaScript Throws Errors
• When an error occurs, JavaScript will normally stop and generate an error message.
• The technical term for this is: JavaScript will throw an exception (throw an error).
• JavaScript will actually create an Error object with two properties: name and message.

The throw Statement


• The throw statement allows you to create a custom error.
• Technically you can throw an exception (throw an error).
• The exception can be a JavaScript String, a Number, a Boolean or an Object:
throw "Too big"; // throw a text
throw 500; // throw a number
• If you use throw together with try and catch, you can control program flow and generate
custom error messages.
JavaScript Errors
The finally Statement
• The finally statement lets you execute code, after try and catch, regardless of the result:
Syntax
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
JavaScript Errors
The finally Statement
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p> If left blank
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = ""; If “number”
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low"; If 15
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
} If 3
}
</script>
</body>
</html>
JavaScript Errors
The Error Object
• JavaScript has a built in error object that provides error information when an error occurs.
• The error object provides two useful properties: name and message.

Error Object Properties

Property Description
name Sets or returns an error name
message Sets or returns an error message (a string)
JavaScript Errors
Error Name Values
• Six different values can be returned by the error name property:
Error Name Description
EvalError An error has occurred in the eval() function
Note: Newer versions of JavaScript do not throw EvalError. Use SyntaxError instead.
RangeError A number "out of range" has occurred. A RangeError is thrown if you use a
number that is outside the range of legal values.
ReferenceError An illegal reference has occurred. A ReferenceError is thrown if you use
(reference) a variable that has not been declared
SyntaxError A syntax error has occurred. A SyntaxError is thrown if you try to evaluate code
with a syntax error.
TypeError A type error has occurred. A TypeError is thrown if you use a value that is
outside the range of expected types
URIError An error in encodeURI() has occurred. A URIError is thrown if you use illegal
characters in a URI function:
JavaScript Errors
Type Error Example
let num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Outline
1. Conditional statements
2. JavaScript Errors
3. JavaScript Debugging
4. JavaScript Common Mistakes
5. JavaScript Form Validation
JavaScript Debugging
Errors can (will) happen, every time you write some new computer code.
Code Debugging
• Programming code might contain syntax errors, or logical errors.
• Many of these errors are difficult to diagnose.
• Often, when programming code contains errors, nothing will happen. There are no error messages, and
you will get no indications where to search for errors.
• Searching for (and fixing) errors in programming code is called code debugging.

JavaScript Debuggers
• Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.
• Built-in debuggers can be turned on and off, forcing errors to be reported to the user.
• With a debugger, you can also set breakpoints (places where code execution can be stopped), and
examine variables while the code is executing.
• Normally you activate debugging in your browser with the F12 key, and select "Console" in the debugger
menu.
JavaScript Debugging
The console.log() Method
• If your browser supports debugging, you can use console.log() to display JavaScript
values in the debugger window

Setting Breakpoints
• In the debugger window, you can set breakpoints in the JavaScript code.
• At each breakpoint, JavaScript will stop executing, and let you examine JavaScript
values.
• After examining values, you can resume the execution of code (typically with a play
button).
JavaScript Debugging
The debugger Keyword
• The debugger keyword stops the execution of JavaScript, and calls (if available)
the debugging function.
• This has the same function as setting a breakpoint in the debugger.
• If no debugging is available, the debugger statement has no effect.
JavaScript Debugging
The debugger Keyword
• Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Debugger</h2>
<p id="demo"></p>
<p>With the debugger turned on, the code below should stop executing before it executes the third line.</p>
<script>
let x = 15 * 5;
debugger;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
• With the debugger turned on, this code will stop executing before it executes the third line.
JavaScript Debugging
• Major Browsers' Debugging Tools
• Normally, you activate debugging in your browser with F12, and select "Console" in the debugger menu.
• Otherwise follow these steps:
• Chrome
• Open the browser. • Opera
• From the menu, select "More tools". • Open the browser.
• From tools, choose "Developer tools". • From the menu, select "Developer".
• From "Developer", select "Developer tools".
• Finally, select “Console”.
• Finally, select "Console".
• Firefox • Safari
• Open the browser. • Go to Safari, Preferences, Advanced in the
• From the menu, select "Web Developer". main menu.
• Finally, select "Web Console". • Check "Enable Show Develop menu in menu
• Edge bar".
• Open the browser. • When the new option "Develop" appears in
• From the menu, select "Developer Tools". the menu:
• Choose "Show Error Console".
• Finally, select "Console".
Outline
1. Conditional statements
2. JavaScript Errors
3. JavaScript Debugging
4. JavaScript Common Mistakes
5. JavaScript Form Validation
JavaScript Common Mistakes
Accidentally Using the Assignment Operator
JavaScript programs may generate unexpected results if a programmer accidentally uses an
assignment operator (=), instead of a comparison operator (==) in an if statement.
This if statement returns false (as expected) because x is not equal to 10:
let x = 0;
if (x == 10)

This if statement returns true (maybe not as expected), because 10 is true:


let x = 0;
if (x = 10)

This if statement returns false (maybe not as expected), because 0 is false:


let x = 0;
if (x = 0)

An assignment always returns the value of the assignment.


JavaScript Common Mistakes
Expecting Loose Comparison

In regular comparison, data type does not matter. This if statement returns true:
let x = 10;
let y = "10";
if (x == y)

In strict comparison, data type does matter. This if statement returns false:
let x = 10;
let y = "10";
if (x === y)
JavaScript Common Mistakes
Expecting Loose Comparison
It is a common mistake to forget that switch statements use strict comparison:
This case switch will display an alert:
<script>
let x = 10;
switch(x) {
case 10: document.getElementById("demo").innerHTML = "Hello";
}
</script>

This case switch will not display an alert:


<script>
let x = 10;
switch(x) {
case “10”: document.getElementById("demo").innerHTML = "Hello";
}
</script>
JavaScript Common Mistakes
Confusing Addition & Concatenation
• Addition is about adding numbers.
• Concatenation is about adding strings.
• In JavaScript both operations use the same + operator.
• Because of this, adding a number as a number will produce a different result from adding a
number as a string:
let x = 10; let y = 10;
x = 10 + 5; // Now x is 15 y += "5"; // Now y is 105

When adding two variables, it can be difficult to anticipate the result:


let x = 10; let x = 10;
let y = 5; let y = "5";
let z = x + y; // Now z is 15 let z = x + y; // Now z is 105
JavaScript Common Mistakes
Misunderstanding Floats
• All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).
• All programming languages, including JavaScript, have difficulties with precise floating point values:
let x = 0.1;
let y = 0.2;
let z = x + y // the result in z will not be 0.3

• To solve the problem above, it helps to multiply and divide:

Example
let z = (x * 10 + y * 10) / 10; // z will be 0.3
JavaScript Common Mistakes
Misplacing Semicolon

• Because of a misplaced semicolon, this code block will execute regardless of the
value of x:
<script>
let x = 5;
if (x == 19);
{
document.getElementById("demo").innerHTML = "Hello";
}
</script>
JavaScript Common Mistakes
Breaking a Return Statement
• It is a default JavaScript behavior to close a statement automatically at the end of a line.
• Because of this, these two examples will return the same result: Explanation
Example 1 If a statement is incomplete like:
let
document.getElementById("demo").innerHTML = myFunction(55);
JavaScript will try to complete the
function myFunction(a) { statement by reading the next line:
let power = 10 power = 10;
return a * power But since this statement is complete:
return
}
JavaScript will automatically close it like
Example 2 this:
return;
document.getElementById("demo").innerHTML = myFunction(55);
This happens because closing (ending)
function myFunction(a) { statements with semicolon is optional in
let power = 10; JavaScript.
return a * power; JavaScript will close the return statement
at the end of the line, because it is a
}
complete statement.
Note: Never break a return statement.
JavaScript Common Mistakes
Breaking a Return Statement
• JavaScript will also allow you to break a statement into two lines.
• Because of this, example 3 will also return the same result:
Example 3
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
let
power = 10;
return a * power;
}
JavaScript Common Mistakes
Breaking a Return Statement
But, what will happen if you break the return statement in two lines like this:
Example 4
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
let
power = 10;
return
a * power;
}

The function will return undefined! Because JavaScript thought you meant:
Example 5
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
let
power = 10;
return;
a * power;
}
JavaScript Common Mistakes
Accessing Arrays with Named Indexes
• Many programming languages support arrays with named indexes.
• Arrays with named indexes are called associative arrays (or hashes).
• JavaScript does not support arrays with named indexes.
• In JavaScript, arrays use numbered indexes:
Example
<script>
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
document.getElementById("demo").innerHTML =
person[0] + " " + person.length; // person[0] will return "John", person.length will return 3
</script>
JavaScript Common Mistakes
Accessing Arrays with Named Indexes
• In JavaScript, objects use named indexes.
• If you use a named index, when accessing an array, JavaScript will redefine the array to a standard
object.
• After the automatic redefinition, array methods and properties will produce undefined or incorrect
results:
Example:
<script>
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
document.getElementById("demo").innerHTML =
person[0] + " " + person.length; // person[0] will return undefined, person.length will return 0
</script>
Outline
1. Conditional statements
2. JavaScript Errors
3. JavaScript Debugging
4. JavaScript Common Mistakes
5. JavaScript Form Validation
JavaScript Form Validation
• HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a message, and
returns false, to prevent the form from being submitted:
• JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
JavaScript Form Validation
The function can be called when the form is submitted:
HTML Form Example
JavaScript Form Validation
• JavaScript is often used to validate numeric input:
JavaScript Form Validation
Automatic HTML Form Validation
• HTML form validation can be performed automatically by the browser:
• If a form field (fname) is empty, the required attribute prevents this form from being submitted:
JavaScript Form Validation
• Data Validation
• Data validation is the process of ensuring that user input is clean, correct, and useful.
• Typical validation tasks are:
• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?
• Most often, the purpose of data validation is to ensure correct user input.
• Validation can be defined by many different methods, and deployed in many different ways.
• Server side validation is performed by a web server, after input has been sent to the
server.
• Client side validation is performed by a web browser, before input is sent to a web server

You might also like