Lec12 JS
Lec12 JS
Semester 4
Web Technology
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
• 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.
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)
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>
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