0% found this document useful (0 votes)
6 views129 pages

Lec03 JavaScrip 002udated

This document provides an overview of JavaScript as a client-side programming language used in web development, detailing its capabilities such as dynamic HTML content generation, user event handling, and form validation. It explains the differences between JavaScript and Java, the structure of JavaScript code, and various ways to include JavaScript in HTML. Additionally, it covers fundamental concepts like variables, data types, functions, and the Document Object Model (DOM) for manipulating web page content.

Uploaded by

Luay Alzubaidy
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)
6 views129 pages

Lec03 JavaScrip 002udated

This document provides an overview of JavaScript as a client-side programming language used in web development, detailing its capabilities such as dynamic HTML content generation, user event handling, and form validation. It explains the differences between JavaScript and Java, the structure of JavaScript code, and various ways to include JavaScript in HTML. Additionally, it covers fundamental concepts like variables, data types, functions, and the Document Object Model (DOM) for manipulating web page content.

Uploaded by

Luay Alzubaidy
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

Web Development – Part A

JavaScript

CYB 452 – Mustafa Radaideh


Chapter 8
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
© 2023 Pearson [Link]
Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Part 01 Language
Fundamentals

Video lecture
Extra References .
Overview
Client-side programming, such as JavaScript, can be
integrated in a client's browser's page. When operating
a web application, this script will allow the client's
browser to relieve some of the load on your web
server. Client-side scripting enables the construction of
quicker and more responsive online applications by
executing source code on the client's browser rather
than the web server.

3
Overview
Client-side scripting refers to a type of online
programming that is run on the client side, rather than
on the server, by the user's web browser (on the web
server).A "scripting" language for HTML pages
Embed code in HTML pages so they are downloaded
directly to browser
The browser interprets and executes the script (it is not
compiled)
Do not declare data types for variables (loose typing)
Dynamic binding – object references checked at
runtime
4
Overview (cont.)

Scripts can manipulate "browser objects:"


• HTML form elements
• Images
• Frames
• etc.
For security – cannot write to disk (when run on a client)

5
Abilities
• Generating HTML content dynamically
• Monitoring and responding to user events
• Validate forms before submission
• Manipulate HTTP cookies
• Interact with the frames and windows of the browser
• Customize pages to suit users

6
It is not Java

Java :
compilation required (not a script)
can create “stand alone” application
object-oriented
Why is it called Javascript then?

7
Web Architecture for JavaScript
"CLIENT" "SERVER"
Desktop access Remote host
Web browser
Web
(HTTP)
HTML Page: HTML/HTTP HTML/HTTP
<SCRIPT> Internet Server
TCP/IP TCP/IP
…code..…
</SCRIPT>

built-in
JavaScript
interpreter HTML
pages w/
embedded
script
Where Does JavaScript Go ?
Inline JavaScript

Inline JavaScript refers to the practice of including JavaScript code directly


within certain HTML attributes

<a href="JavaScript:[Link]('[Link]
info</a>
<input value="Mustafa" type="button" onClick="alert('Are you Mustafa?');"
/>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Where Does JavaScript Go ?
Embedded JavaScript

Embedded JavaScript refers to the practice of placing JavaScript


code within a <script> element

<script type="text/javascript">
/* A JavaScript Comment */
alert("Hello World!");
</script>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Where Does JavaScript Go ?
External JavaScript

external JavaScript files typically contain function definitions,


data definitions, and entire frameworks.

<head>
<script type="text/javascript" src="[Link]"></script>
</head>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Variables and Data Types

Variables in JavaScript are dynamically typed


This simplifies variable declarations, since we do not
require the familiar data-type identifiers
Instead we simply use the var / let / const keyword

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Variables and Data Types
Example variable declarations and Assignments

variable

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Variables and Data Types
Data Types

two basic data types:


• reference types (usually referred to as objects) and
• primitive types
Primitive types represent simple forms of data.
• Boolean, Number, String, …

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
JavaScript Output

alert("Hello world");

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
JavaScript Output

var name = "Mustafa";


[Link]("<h1>Title</h1>");
// this uses the concatenate operator (+)
[Link]("Hello " + name + " and welcome");

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
JavaScript Output

• alert() Displays content within a pop-up box.


• [Link]() Displays content in the Browser’s
JavaScript console.
• [Link]
ole_log.asp
• [Link]() Outputs the content (as
markup) directly to the HTML document.
• [Link]
[Link]

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
JavaScript Output
To open the developer tools in Google Chrome:
[Link] the browser.
[Link] F12 on the keyboard. Optional: Press the Ctrl+Shift+I keys

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
JavaScript Output
Fun with [Link]()

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
[Link]
[Link]

aue9odUEo
Conditionals
If, else if, else

if (hourOfDay > 4 && hourOfDay < 12) {


greeting = "Good Morning";

}
else if (hourOfDay >= 12 && hourOfDay < 18) {
greeting = "Good Afternoon";

}
else {
greeting = "Good Evening";
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Conditionals
switch

switch (artType) {
case "PT":
output = "Painting";
break;
case "SC":
output = "Sculpture";
break;
default:
output = "Other";
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Conditionals
Conditional Assignment

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Conditionals
Truthy and Falsy

In JavaScript, a value is said to be truthy if it translates to true,


while a value is said to be falsy if it translates to false.
• Almost all values in JavaScript are truthy
• false, null, "", '', 0, NaN, and undefined are falsy

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Loops
While and do ...while Loops

var count = 0;

while (count < 10) {

// do something

// ...
count++;

count = 0;

do {

// do something

// ...
count++;

} while (count < 10);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Loops
For Loops

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
END OF PART 01
Part 02 Functions

Video lecture .
Functions
Function Declarations [Link] Expressions

Functions are the building block for modular code in JavaScript.

function subtotal(price,quantity) {
return price * quantity;
}
The above is formally called a function declaration, called or
invoked by using the () operator

var result = subtotal(10,2);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Function Declarations [Link] Expressions

// defines a function using a function expression


var sub = function subtotal(price,quantity) {
return price * quantity;

};
// invokes the function

var result = sub(10,2);


It is conventional to leave out the function name in function
expressions

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Anonymous Function Expressions

// defines a function using an anonymous function expression


var calculateSubtotal = function (price,quantity) {

return price * quantity;

};
// invokes the function
var result = calculateSubtotal(10,2);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Nested Functions

function calculateTotal(price,quantity)

{ var subtotal = price * quantity;


return subtotal + calculateTax(subtotal);
// this function is nested
function calculateTax(subtotal) {
var taxRate = 0.05;
var tax = subtotal * taxRate; return tax;
}
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Hoisting in JavaScript mechanism where variables and function declarations are
moved to the top of their scope before code execution

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Callback Functions

Randy Connolly and Ricardo Fundamentals of Web Development - 2 nd Ed.


Functions
Callback Functions

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Scope in JavaScript

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Scope in JavaScript

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Scope in JavaScript

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
11.2 Math Object
Math object methods enable you to conveniently perform many common
mathematical calculations.
An object’s methods are called by writing the name of the object followed by a
dot operator (.) and the name of the method
In parentheses following the method name is are arguments to the method
Gf ➔ [Link] ( Arguments) ;
JavaScript global functions
1. parseInt(), parseFloat() Not contained in any Object
2. isNaN(), isFinite()
3. eval()
eval – gets a string of JavaScript code, evaluates it and executes it
It allows dynamic code execution
let x = 10;
let y = 20;
let text = "x * y";
let result = eval(text);
Do NOT use eval()
Executing JavaScript from a string is an BIG security risk.
With eval(), malicious code can run inside your application
without permission.
With eval(), third-party code can see the scope of your
application, which can lead to possible attacks
Purpose of encodeURI() and decodeURI():
•Encoding: encodeURI() replaces special characters in a Uniform Resource
Identifier (URI) with their corresponding hexadecimal escape sequences (%xx),
ensuring compatibility with different systems and preventing misinterpretations.
However, it excludes the characters ":", "/", ";", and "?" and ? as they have
specific meanings in URIs.
•Decoding: decodeURI() reverses the process, converting back the encoded
characters (%xx) to their original forms, making the URI human-readable and
usable by web browsers.
Example:
JavaScript
var uri = "my [Link]?name=ståle&car=saab"; [Link](encodeURI(uri) +
"<br />");
Output:
my%[Link]?name=st%C3%A5le&car=saab
•Explanation:
•my%[Link] remains unchanged because spaces () are excluded from
encoding.
•ståle becomes st%C3%A5le due to encoding of the accented character å
(C3 and A5 are its hexadecimal codes).
•&car=saab remains untouched as it includes allowed characters.
Purpose of escape() and unescape():
Encoding: escape() replaces a broader range of characters, including spaces, punctuation, accented characters, and
non-ASCII characters, with their hexadecimal escape sequences (%xx). However, it's not recommended for URI
encoding because it doesn't handle special characters in URIs correctly (e.g., it encodes + as %2B, which is
interpreted as a space in URIs).
Decoding: unescape() is the counterpart of escape(), but it's deprecated due to security vulnerabilities and potential
inconsistencies.
Example:
JavaScript
[Link](escape("Need tips? Visit W3Schools!"));
Output:
Need%20tips%3F%20Visit%20W3Schools%21
Explanation:
All characters in the string, including spaces and special characters, are encoded with %xx sequences.

Key Points:
•Use encodeURI() and decodeURI() specifically for working with URIs. They ensure compatibility and
prevent misinterpretations.
•Avoid escape() and unescape() for URI encoding due to potential issues with special characters.
•Consider using alternative encoding functions like encodeURIComponent() or libraries like URL for
more robust and secure encoding/decoding in JavaScript.
By understanding these concepts and their appropriate usage, you can effectively encode
and decode URIs in web development while maintaining security and compatibility.
[Link]
[Link]()
generates a pseudo-random decimal between 0 (inclusive) and 1 (exclusive).

Examples:

• Coin Flip Simulation: [Link]() < 0.5 ? "Heads" : "Tails"


(Outputs "Heads" or "Tails" with equal probability)

• Random Number Generation (0-9): [Link]([Link]() * 10)


(Generates a random integer between 0 and 9)

let min = 5; // Adjust as needed (avoid 0)


let max = 15; // Adjust as needed
let randomNum = [Link]([Link]() * (max - min + 1)) +
min;
[Link](randomNum);
// Output: A random integer between min (inclusive) and max
(inclusive), excluding 0
Objects
Object Creation—Object LiteralNotation

var objName = {
name1: value1,

name2: value2,

// ...
nameN: valueN

};

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Objects
Object Creation—Object LiteralNotation

Access using either of:


• objName.name1
• objName["name1"]

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Objects
Object Creation—Constructed Form

// first create an empty object


var objName = new Object();
// then define properties for this object
objName.name1 = value1;
objName.name2 = value2;

[Link] ( Arguments)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Objects and Functions Together

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Functions
Function Constructors

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Wrappers and conversions

JavaScript has no “casts,” but conversions can be forced


var s = x + ""; // s is now a string
var n = x + 0; // n is now a number
var b = !!x; // b is now a boolean
Because JavaScript does automatic conversions as needed,
explicit conversions are hardly ever needed
END OF PART 02
Part 03 DOM

Video lecture
Extra References(optional) .
Objectives

You will learn:


• What is Document Object Model (DOM)
• How to use the DOM to dynamically manipulate the contents of
a web page
• How to respond to JavaScript events
• How to use the DOM and event handling to validate user input in
a form
Outline
The Document
1 2
Modifying the
Object Model DOM
(DOM)

3 Events
4 Event Types

5 Forms
6 Summary
The Document Object Model (DOM)
Overview

DOM is a Platform- and language-neutral interface that will allow programs and scripts
to dynamically access and update the content, structure and style of documents
Document Tree Structure

document #document <html>


<body>
HTML <h1>Heading 1</h1>
<p>Paragraph.</p>
HEAD
document. <h2>Heading 2</h2>
documentElement <p>Paragraph.</p>
BODY </body>
[Link] </html>
H1
#text

P
#text

H2
#text

P
#text

61
The Document Object Model (DOM)
Nodes and NodeLists
Document Model
Arrays of various kinds of objects.
The Document Object Model (DOM)
Document Object

The DOM document object is the root JavaScript object


representing the entire HTML document

// retrieve the URL of the current page


var a = [Link];
// retrieve the page encoding, for example ISO-8859-1
var b = [Link];
The Document Object Model (DOM)
Selection Methods

Classic
• getElementById()
• getElementsByTagName()
• getElementsByClassName()
Newer
• querySelector() and
• querySelectorAll()
Apart from that, the Console also has a
set of convenience functions that make
it easier to interact with a page. For
example:
Rather than typing
[Link]() to select an
element, you can type $(). This syntax is
inspired by jQuery, but it's not actually
jQuery. It's just an alias for
[Link]().
debug(function) effectively sets a
breakpoint on the first line of that
function.
keys(object) returns an array containing
the keys of the specified object.
JS: Document Object Model (DOM)
DOM Methods and Properties
[Link](ID) returns the element with the
specified ID attribute.
[Link](tag) returns an array of the
elements with the specified tag name. You can use the asterisk
(*) as a wildcard to return an array containing all of the nodes in
the document.
[Link](tag) creates a new element with the
specified tag name.
[Link](text) creates a new text node
containing the specified text.
[Link] is an object that represents the
document itself, and can be used to find information about the
document.
Finding HTML Objects
The Document Object Model (DOM)
Selection Methods

[Link](“latest").[Link] = "red";

Any id should be unique, but:

If two or more elements with the same id exist, getElementById()


returns the first.
The Document Object Model (DOM)
Query Selector
The Document Object Model (DOM)
Element Node Object

Element Node object represents an HTML element in the hierarchy,


contained between the opening <> and closing </> tags for this
element. Every node has
• classList: A read-only list of CSS classes assigned to this element.
This list has a variety of helper methods for manipulating this list.
• className: current value for the class attribute of this HTML
element.
• id: current value for the id of this element
• innerHTML: represents all the content (text and tags) of the eleme.
• Style: style attribute of an element
• tagName: tag name for the element.
Using innerHTML
Prior to HTML5
innerHTML was universally supported, but not W3C standard
Some browsers did not parse and add nested tags to the DOM
HTML 5
Part of the HTML 5 standard and is reasonably fast
Supporting browsers parse and add nested tags to the DOM
The following now works, assuming: <body id="data"> </body>
<script type="text/javascript">
var data = [Link]("data")
[Link] = '<h2 id="header">header</h2>
var header = [Link]("header");
[Link] = "new header";
</script>
Modifying an Elements Class

To set a CSS classes for an element:


[Link]("Element").className = "C1";
To set more than one CSS class into an element:
[Link]("Element").className = "C1 C2";
To add an additional class to an element:
[Link]("Element").className += " C3";
To remove a class from an element:
var tag = [Link]("Element").className;
[Link](/\bMyClass\b/, "");
The Document Object Model (DOM)
More common (not universal) properties

• href
• name
• src
• value
<!doctype html>
<html> <head> <title>Console Demo</title>
</head> <body>
<h1>Hello, World!</h1>
<script>
[Link]('Loading!');
const h1 = [Link]('h1');
[Link]([Link]);
[Link]([Link]('h2'), 'h2 not found!');
const artists = [
{
first: 'René',
last: 'Magritte'
},
{
first: 'Chaim',
last: 'Soutine'
},
{
first: 'Henri',
last: 'Matisse'
}
];
[Link](artists);
setTimeout(() => {
[Link] = 'Hello, Console!';
[Link]([Link]);
}, 3000);
</script> </body>
</html>
View and change the page's JavaScript or DOM
When building or debugging a page, it's often useful to run statements in
the Console in order to change how the page looks or runs.
[Link] the text in the button below.
[Link] [Link]('hello').textContent = 'Hello, Console!' in
the Console and then press Enter to evaluate the expression. Notice how the
text inside the button changes.

Figure 3. How the Console looks after evaluating the expression above.
Below the code that you evaluated you see "Hello, Console!". Recall the 4
steps of REPL: read, evaluate, print, loop. After evaluating your code, a REPL
prints the result of the expression. So "Hello, Console!" must be the result of
evaluating [Link]('hello').textContent = 'Hello, Console!'.
setTimeout setInterval

Imagine you have a kitchen timer. You set it Think of a metronome, a device that clicks at
for 3 minutes (3000 milliseconds) to remind regular intervals to help musicians keep time.
you to take out your cookies from the oven.
What it does: setInterval repeatedly calls a
What it does: setTimeout schedules a function at a specified interval (time in
function to run once after a specified delay milliseconds) until you stop it.
(time in milliseconds). Example:
Example: JavaScript
JavaScript function displayTime() {
function sayHiAfterThreeSeconds() { const date = new Date();
[Link]("Hello! Your cookies are [Link]("The time is:",
done!"); [Link]());
} }

setTimeout(sayHiAfterThreeSeconds, 3000); const intervalId = setInterval(displayTime,


// Call the function after 3 1000); // Call the function every second

// To stop the interval (like stopping the


metronome):
clearInterval(intervalId);
Outline
The Document
1 2
Modifying the
Object Model DOM
(DOM)

3 Events
4 Event Types

5 Forms
6 Summary
Modifying the DOM
Changing an Element’s Style
Modifying the DOM
Changing an Element’s Content

[Link]("here").innerHTML =
"foo<em>bar</em>";
Modifying the DOM
Creating DOM elements
Modifying the DOM
Creating DOM elements
JS: DOM – Adding or modifying HTML
element properties
Methods
getAttribute(“attribute_name”)
Same method:
getAttributeNode(“attribute_name”)
Retrieve the node representation of the named
attribute from the current node.
setAttribute(“attribute_name”, “attribute_value”)
Adds a new attribute or changes the value of an
existing attribute on the specified element.
hasAttribute((“attribute_name”)
Return boolean
removeAttribute(“attribute_name”)
JS: DOM – Adding or modifying HTML element properties
Activity 10:5

• Create the element


• var linkElement = [Link]("a");
• Set the element content
• [Link] = "Click me to go to google!";
• Set element property
• [Link]("href",
"[Link]

To change attribute value:


Get the element
Use setAttribute with a new value
Modifying the DOM
Creating DOM elements

• appendChild
• createAttribute
• createElement
• createTextNode
• InsertBefore
• removeChild
• replaceChild
Outline
The Document
1 2
Modifying the
Object Model DOM
(DOM)

3 Events
4 Event Types

5 Forms
6 Summary
Part 03 Event

Video lecture /examples


Extra References(optional) .
Events
 Two models for registering event handlers
Inline model treats events as attributes of HTML elements
Traditional model assigns the name of the function to the event property of a DOM node
 The inline model places calls to JavaScript functions directly in
HTML code.
 The following code indicates that JavaScript function start
should be called when the body element loads:
<body onload = "start()">
 The traditional model uses a property of an object to specify an
event handler.
 The following JavaScript code indicates that function start should
be called when document loads:
[Link] = "start()";
Events
Event-Handling Approaches – Inline Hook
Events
Event-Handling Approaches – Event Property Approach

var myButton = [Link]('example');


[Link] = alert('some message');
Events
Event-Handling Approaches – Event Listener Approach

var myButton = [Link]('example');


[Link]('click', alert('some message'));
[Link]('mouseout', funcName);
Events
Event-Handling Approaches – Event Listener Approach (anon function)

[Link]('click', function() {

var d = new Date();


alert("You clicked this on "+ [Link]());
});
Events
Event Object

When an event is triggered, the browser will construct an event


object that contains information about the event.

[Link]('click', function( ) { e
// find out where the user clicked
var x = [Link];
//This line retrieves information from the event object (e).

Essentially, the code listens for a click on the div and then uses the clientX
property of the event object to find out where (horizontally) on the screen the
user clicked.
Events
Event Object
• bubbles Indicates whether the event bubbles up
through the DOM
• cancelable Indicates whether the event can be
cancelled. An event is cancelable if it is possible to
prevent its default action.
• target The object that generated (or dispatched) the
event. To return the element where the event
occurred.
Imagine you have a button on a box. Clicking the button (event) triggers a
sound (default behavior).
•bubbles: If bubbles is true, the sound travels up to any surrounding boxes
(parent elements).
•cancelable: If cancelable is true, you can write code to mute the sound
(prevent default behavior).
•target: This is the button you clicked on, where the sound originated (the
element that generated the event).
Outline
The Document
1 2
Modifying the
Object Model DOM
(DOM)

3 Events
4 Event Types

5 Forms
6 Summary
Event Types
Mouse Events

• click The mouse was clicked on an element


• dblclick The mouse was double clicked on an
element
• mousedown The mouse was pressed down over an
element
• mouseup The mouse was released over an element
• mouseover The mouse was moved (not clicked) over
an element
• mouseout The mouse was moved off of an element
• mousemove The mouse was moved while over an
element
onerror Event
Execute a JavaScript if an error occurs when loading an image:
<img src="[Link]" onerror="myFunction()">
Syntax
<element onerror="myScript">
[Link] = function(){myScript};
[Link]("error", myScript);
Event Types
Keyboard Events
Event Types
Form Events

• Blur: Triggered when a form element has lost focus, perhaps due to a
click or Tab key press.
• Change: Some <input>, <textarea> or <select> field had their value
change. This could mean the user typed something or selected a new
choice.
• Focus: Complementing the blur event, this is triggered when an
element gets focus.
• Reset: HTML forms have the ability to be reset. This event is triggered
when that happens.
• Select: When the users select some text. This is often used to try and
prevent copy/paste.
• Submit: When the form is submitted this event is triggered. We can do
some prevalidation of the form in JavaScript before sending the data on
to the server.
Part 04 ARRAY

Video lecture
Extra References(optional) .
Arrays

Arrays are one of the most commonly used data structures in


programming.
JavaScript provides two main ways to define an array.
• object literal notation
• use the Array() constructor

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Arrays
object literal notation

The literal notation approach is generally preferred since it involves less typing, is
more readable, and executes a little bit quicker

var years = [1855, 1648, 1420];


var countries = ["Canada", "France","Germany", "Nigeria",, "",];
var mess = [53, "Canada", true, 1420];
var A = new Array(5);
var B = new Array();
var C = new Array (1 ,2 , 3, 4 ,5);
var D = [1 , 2 ,3 ,7, 9, ] ; //initializer list
var E = [1,2,,,5];
var F = [Link]; //5

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Arrays
Arrays Illustrated

Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
Arrays
Some common features

• arrays in JavaScript are zero indexed


• [] notation for access
• .length gives the length of the array
• .push() adds new items to the end of an array
• .pop() removes the last element of an array
• concat()
• .slice() method returns selected elements in an array, as
a new array; .slice(start, end)
• .join() returns an array as a string
• .reverse() method reverses the order of the elements in
an array
• .shift() removes the first item of an array (by shifting)
• .sort() method sorts the array
• Indexof , lastIndexOf
Randy Connolly and Ricardo Hoar Fundamentals of Web Development - 2nd Ed.
10.7 Passing Arrays to Functions
(Cont.)

join method of an Array


Returns a string that contains all of the elements of an array, separated by
the string supplied in the function’s argument
If an argument is not specified, the empty string is used as the separator
GF: - [Link](“separator”);
var C = new Array (1 ,2 , 3, 4 ,5);
[Link]([Link]("*"));
//1*2*3*4*5

var C = new Array (1 ,2 , , 4 ,5);


10.9 Searching Arrays with Array
Method indexOf (Cont.)

 Every input element has a value property that can be used to get or set the element’s value.

Optional Second Argument to indexOf and lastIndexOf


 You can pass an optional second argument to methods indexOf and lastIndexOf that
represents the index from which to start the search.
 By default, this argument’s value is 0 and the methods search the entire array.
 If the argument is greater than or equal to the array’s length, the methods simply return -1.
 If the argument’s value is negative, it’s used as an offset from the end of the array.
Index and lastIndexOf
const fruits = ["apple", "banana", "orange", "apple", "mango"];

// Find the first "apple"


let firstAppleIndex = [Link]("apple");
[Link]("First apple at index:", firstAppleIndex); // Output:
First apple at index: 0

// Find the last "apple" (searching backward)


let lastAppleIndex = [Link]("apple");
[Link]("Last apple at index:", lastAppleIndex); // Output:
Last apple at index: 3

// If a fruit is not found


let kiwiIndex = [Link]("kiwi");
[Link]("Index of kiwi:", kiwiIndex); // Output: Index of
kiwi: -1
Remember, JavaScript's built-in sort() method is generally preferred for
most sorting needs as it's optimized for performance. This example is for
educational purposes.

const colors = ["red", "green", "blue", "yellow", "purple"];

// Sort the colors alphabetically (ascending order)


[Link]();

[Link]("Sorted colors:", colors);


// Output: Sorted colors: ["blue", "green", "purple", "red", "yellow"]

const colors = [5, 3, 10, 1, 8]; // Numbers representing color intensity

// Sort the colors (numbers) in ascending order


[Link]((a, b) => a - b);

[Link]("Sorted colors by intensity:", colors);


// Output: Sorted colors by intensity: [1, 3, 5, 8, 10]
Download the CODE
Part 04 String

Extra References(optional) .
11.3 String Object
Characters are the building blocks of JavaScript
programs
A string is a series of characters treated as a single
unit
A string may include letters, digits and various
special characters, such as +, -, *, /, and $
JavaScript supports Unicode, which represents a
large portion of the world’s languages
String literals or string constants are written as a
sequence of characters in double or single
quotation marks
Combining strings is called concatenation (+)
Gf➔ [Link](argument)
String Method
trim(): Removes leading and trailing whitespace from a string.
Example:
let username = " john123 "; username = [Link]();
[Link](username); // Output: "john123“

Security Benefit: Prevents manipulation attempts that exploit extra spaces

replace(): Replaces occurrences of a substring with another string.


Example:
let userInput = "<script>alert('XSS Attack!')</script>";
userInput = [Link](/<script>/g, "&lt;script&gt;");
[Link](userInput); // Output: "&lt;script&gt;alert('XSS Attack!')&lt;/script&gt;“

Security Benefit: Escapes potentially malicious characters like script tags, preventing code
injection.
The g flag at the end of the regular expression indicates a global search, meaning it replaces all
occurrences of the pattern, not just the first one.
1. charAt(index):

Explanation: Picks the character at a specific position (index) within a string.


Example: "hello“.charAt(0); // Output: "h"` (Gets the first character)
2. charCodeAt(index)

Explanation: Grabs the numeric code representing a character's position in the Unicode
character set.
Example: "hello".charCodeAt(0) // Output: 104` (Code for "h")

3. fromCharCode(code):

Explanation: Converts a numeric Unicode code point back into its corresponding character.
Example: [Link](104) // Output: "h" (Converts code 104 back to "h")
11.3.5 Splitting Strings and
Obtaining Substrings
Breaking a string into tokens is called tokenization
Tokens are separated from one another by delimiters, typically
white-space characters such as blank, tab, newline and carriage
return
Other characters may also be used as delimiters to separate tokens
String method split
Breaks a string into its component tokens
Argument is the delimiter string
Returns an array of strings containing the tokens

var str ="cis mis Nis "


var tokens = [Link](" ");
[Link]( “<br>")
FORMS
Forms
Validating a Submitted Form

• Empty Field Validation


• Number Validation
• Other (non JavaScript) Form validation reminder
Forms
Empty Field Validation

The events triggered by forms allow us to do some


timely processing in response to user input. In the
below figure, we listen for that event on a form with id
loginForm. If the password field (with id pw) is blank,
we prevent submitting to the server using
preventDefault() and alert the user. Otherwise, we do
nothing, which allows the default event to happen
(submitting the form).
Forms
Empty Field Validation

A common application of a client-side validation is to


make sure the user entered something into a field (or
selected a value). There's certainly no point sending a
request to log in if the username was left blank, so why
not prevent the request from working? The way to
check for an empty field in JavaScript is to compare a
value to both null and the empty string (“”), as shown in
below figure.
Forms
Responding to Form Movement Events
Forms
Responding to Form Changes Events
Forms
Number Validation

Number validation can take many forms. You might be asking users
for their age for example, and then allow them to type it rather
than select it. Unfortunately, no simple functions exist for number
validation like one might expect from a full-fledged library. Using
parseInt(), isNAN(), and isFinite(), you can write your own number
validation function.
Questions?
SAMPLE CODE
Final example (Roll dice )

You might also like