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

Chapter 4 - JavaScript

Computer science

Uploaded by

Leta Yezachow
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 views38 pages

Chapter 4 - JavaScript

Computer science

Uploaded by

Leta Yezachow
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

Chapter Four: JavaScript

4.1. What is JavaScript?


 JavaScript is the world's most popular programming language.
 JavaScript is the programming language of the Web.
 JavaScript is easy to learn.

JavaScript is an object-based scripting language which is lightweight and cross-platform.


JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web browser.
JavaScript (js) is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages. It is an interpreted, full-fledged programming language that
enables dynamic interactivity on websites when applied to an HTML document. It was introduced
in the year 1995 for adding programs to the webpages in the Netscape Navigator browser. Since
then, it has been adopted by all other graphical web browsers. With JavaScript, users can build
modern web applications to interact directly without reloading the page every time. The traditional
website uses js to provide several forms of interactivity and simplicity.
Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In addition
to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their scripting and
query language.

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:


1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

4.2. Application of JavaScript


JavaScript is used to create interactive websites. It is mainly used for:

 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
 Displaying clocks etc.

JavaScript Example
JavaScript example is easy to code. Let’s create the first JavaScript example.
<script type="text/javascript">
[Link]("Hello World");
</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the
data.
The [Link]() function is used to display dynamic content through JavaScript. We
will learn about document object in detail later.

4.3. Where to Add JavaScript in HTML


The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
3 Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)

1. JavaScript Example: code between the body tag


Let’s see the simple example of JavaScript that displays alert dialog box.
<html>
<head>
<body>

<script type="text/javascript">
alert(" Welcome to JavaScript ");
</script>

</body>
</html>
2. JavaScript Example: code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside
the head tag. In this example, we are creating a function msg(). To create function in JavaScript,
you need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call msg()
function.
<html>
<head>
<script type="text/javascript">
function msg() {
alert("You clicked a button");
}
</script>
</head>
<body>
<p> Welcome to JavaScript </p>
<form>
<input type="button" value="Click Here" onclick="msg()"/>
</form>
</body>
</html>

3. External JavaScript file

We can create external JavaScript file and embed it in many html pages. It provides code re-
usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.
Let's create an external JavaScript file that prints Hello World in an alert dialog box.
[Link]
function msg() {
alert("Hello World ");
}
Let's include the JavaScript file into html page. It calls the JavaScript function on button click.
[Link]
<html>
<head>
<script type="text/javascript" src="[Link]">
</script>
</head>
<body>
<p> Welcome to JavaScript </p>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</body>
</html>

4.4. JavaScript Output


JavaScript Display Possibilities
JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using [Link]().
 Writing into an alert box, using [Link]().
 Writing into the browser console, using [Link]().

Using innerHTML
To access an HTML element, JavaScript can use the [Link](id)
method. The id attribute defines the HTML element. The innerHTML property defines the
HTML content.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML=5+6;
</script>
<p>My Second Paragraph</p>
</body>
</html>

Using [Link]()
<!DOCTYPE html> Output:
<html>
<body>
<h1> My First Web Page </h1>
<p> My first paragraph. </p>

<script>
[Link](5 + 6);
</script>

</body>
</html>

Using [Link]()
You can use an alert box to display data.
Example
<!DOCTYPE html>
<html>
<body>
<h1> My First Web Page</h1>
<p> My first paragraph.</p>

<script>
[Link](5 + 6);
</script>

</body>
</html>
You can skip the window keyword.
In JavaScript, the window object is the global scope object, that means that variables, properties,
and methods by default belong to the window object. This also means that specifying the
window keyword is optional:

Using [Link]()

For debugging purposes, you can call the [Link]() method in the browser to display
data.
Example
<!DOCTYPE html>
<html>
<body>

<script>
[Link](5 + 6);
</script>
</body>
</html>

4.5. JavaScript Statements


A computer program is a list of "instructions" to be "executed" by a computer. In a
programming language, these programming instructions are called statements. A JavaScript
program is a list of programming statements. In HTML, JavaScript programs are executed by
the web browser.
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
[Link]("demo").innerHTML = "Hello Dolly.";
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
JavaScript programs (and JavaScript statements) are often called JavaScript code.
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript functions:
function myFunction() {
[Link]("demo1").innerHTML = "Hello Dolly!";
[Link]("demo2").innerHTML = "How are you?";
}

4.6. JavaScript Syntax


JavaScript syntax is the set of rules, how JavaScript programs are constructed.
// How to create variables:
var x;
let y;
// How to use variables:
x = 5;
y = 6;
let z = x + y;
JavaScript Values

The JavaScript syntax defines two types of values:


 Fixed values
 Variable values
Fixed values are called Literals.
Variable values are called Variables.

JavaScript Literals

The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals: 10.50 1001
2. Strings are text, written within double or single quotes: "John Doe" 'John Doe'

JavaScript Variables

In a programming language, variables are used to store data values.


JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
let x;
x = 6;
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values: (5 + 6) * 10
JavaScript uses an assignment operator ( = ) to assign values to variables:
let x, y;
x = 5;
y = 6;
JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value.


The computation is called an evaluation.
For example, 5 * 10 evaluates to 50: 5 * 10
Expressions can also contain variable values: x * 10

The values can be of various types, such as numbers and strings.


For example, "John" + " " + "Doe", evaluates to "John Doe": "John" + " " + "Doe"

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
JavaScript keywords are used to identify actions to be performed.
The let keyword tells the browser to create variables:
let x, y;
x = 5 + 6;
y = x * 10;
The var keyword also tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
In these examples, using var or let will produce the same result.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements

JavaScript Comments

JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
let x = 5; // I will be executed
// x = 6; I will NOT be executed
JavaScript Identifiers / Names

Identifiers are JavaScript names.


Identifiers are used to name variables and keywords, and functions.
The rules for legal names are the same in most programming languages.
A JavaScript name must begin with:
 A letter (A-Z or a-z)
 A dollar sign ($)
 Or an underscore (_)
Subsequent characters may be letters, digits, underscores, or dollar signs.
Note:
Numbers are not allowed as the first character in names.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive.


The variables lastName and lastname, are two different variables:
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
JavaScript does not interpret LET or Let as the keyword let.

JavaScript and Camel Case

Historically, programmers have used different ways of joining multiple words into one variable
name.
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.

Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.

JavaScript Character Set


JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.

4.7. JavaScript Variables


4 Ways to Declare a JavaScript Variable:
 Using var
 Using let
 Using const
 Using nothing

What are Variables?

Variables are containers for storing data (storing data values).


In this example, x, y, and z, are variables, declared with the var keyword:
Example:
var x = 5;
var y = 6;
var z = x + y;
In this example, x, y, and z, are variables, declared with the let keyword:
Example:
let x = 5;
let y = 6;
let z = x + y;
In this example, x, y, and z, are undeclared variables:
x = 5;
y = 6;
z = x + y;
From all the examples above, you can guess:
 x stores the value 5
 y stores the value 6
 z stores the value 11
When to Use JavaScript var?

Always declare JavaScript variables with var, let, or const.


The var keyword is used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
If you want your code to run in older browsers, you must use var.
When to Use JavaScript const?
If you want a general rule: always declare variables with const.
If you think the value of the variable can change, use let.
In this example, price1, price2, and total, are variables.
Example:
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
The two variables price1 and price2 are declared with the const keyword. These are constant
values and cannot be changed.

The variable total is declared with the let keyword. This is a value that can be changed.

Just Like Algebra


Just like in algebra, variables hold values:
let x = 5;
let y = 6;
Just like in algebra, variables are used in expressions:
let z = x + y;

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

Declaring a JavaScript Variable


Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var or the let keyword:
var carName; or: let carName;
After the declaration, the variable has no value (technically it is undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
let carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example:
<p id="demo"></p>
<script>
let carName = "Volvo";
[Link]("demo").innerHTML = carName;
</script>
Note: It's a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.


Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
let person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined

In computer programs, variables are often declared without a value. The value can be something
that has to be calculated, or something that will be provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:
let carName;

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
Example:
var carName = "Volvo";
var carName;
Note: You cannot re-declare a variable declared with let or const.
This will not work:
let carName = "Volvo";
let carName;

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
Using the dollar sign is not very common in JavaScript, but professional programmers often use
it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML
elements. In jQuery $("p"); means "select all p elements".

4.8. Data Type conversion


JavaScript variables can be converted to a new variable and another data type:
 By the use of a JavaScript function
 Automatically by JavaScript itself
Converting Strings to Numbers

The global method Number() converts a variable (or a value) into a number. A numeric string
(like "3.14") converts to a number (like 3.14). An empty string (like "") converts to 0. A non
numeric string (like "John") converts to NaN (Not a Number).
Example
These will convert:
Number("3.14") // returns 3.14
Number([Link]) // returns 3.141592653589793
Number(" ") // returns 0
Number("") // returns 0
These will not convert:
Number("99 88") // returns NaN
Number("John") // returns NaN

Number Methods
Method Description
Number() Returns a number, converted from its argument
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer

Converting Numbers to Strings

The global method String() can convert numbers to strings.


It can be used on any type of numbers, literals, variables, or expressions.
String(x) // returns a string from a number variable x
String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression
The Number method toString() does the same.
Example
[Link]()
(123).toString()
(100 + 23).toString()
Converting Dates to Numbers

The global method Number() can be used to convert dates to numbers.


d = new Date();
Number(d) // returns 1404568027739

The date method getTime() does the same.

d = new Date();
[Link]() // returns 1404568027739
Converting Dates to Strings

The global method String() can convert dates to strings.

String(Date()) /* returns "Thu Jul 17 2014 [Link] GMT+0200 (W.


Europe Daylight Time)" */
The Date method toString() does the same.

Example

Date().toString() /* returns "Thu Jul 17 2014 [Link] GMT+0200 (W.


Europe Daylight Time)" */
Date Methods:
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)

Converting Booleans to Numbers


The global method Number() can also convert booleans to numbers.
Number(false) // returns 0
Number(true) // returns 1
Converting Booleans to Strings

The global method String() can convert booleans to strings.


String(false) // returns "false"
String(true) // returns "true"
The Boolean method toString() does the same.
[Link]() // returns "false"
[Link]() // returns "true"
Automatic Type Conversion

When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a
"right" type. The result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2

4.9. JavaScript Operators


There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Conditional Operators
 Type Operators
JavaScript Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator Description Operator Description


+ Addition / Division
- Subtraction % Modulus (Remainder)
* Multiplication ++ Increment
** Exponentiation -- Decrement
Operators and Operands

The numbers (in an arithmetic operation) are called operands.


The operation (to be performed between the two operands) is defined by an operator.

Operand Operator Operand

100 + 50

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.


The Addition Assignment Operator (+=) adds a value to a variable.
let x = 10;
x += 5;

Operator Example Same As

x=y x=y
=

x += y x=x+y
+=

x -= y x=x-y
-=

x *= y x=x*y
*=

x /= y x=x/y
/=

x %= y x=x%y
%=

x **= y x = x ** y
**=

JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type


> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

JavaScript Logical Operators


Operator Description

&& logical and

|| logical or

! logical not

4.10. Control Structure


Control structure actually controls the flow of execution of a program. Following are the several
control structure supported by JavaScript.

 if … else
 switch case
 do while loop
 while loop
 for loop

If … else

The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
var age = 20;
if (age > 18) {
[Link]("<b>Qualifies for driving</b>");
}
</script>

If…else if…else
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
</script>

Switch case

The basic syntax of the switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case
against the value of the expression until a match is found. If nothing matches, a default condition
will be used.
Syntax:
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Example

<script type="text/javascript">
var grade='A';
[Link]("Entering switch block<br/>");
switch (grade) {
case 'A': [Link]("Good job<br/>");
break;
case 'B': [Link]("Pretty good<br/>");
break;
case 'C': [Link]("Passed<br/>");
break;
case 'D': [Link]("Not so good<br/>");
break;
case 'F': [Link]("Failed<br/>");
break;
default: [Link]("Unknown grade<br/>")
}
[Link]("Exiting switch block");
</script>

Do while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax:

do {
Statement(s) to be executed;
} while (expression);
Example

<script type="text/javascript">
var count = 0;
[Link]("Starting Loop" + "<br/>");
do{
[Link]("Current Count : " + count + "<br/>");
count++;
}while (count < 0);
[Link]("Loop stopped!");
</script>

While Loop

The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.
Syntax:

while (expression){
Statement(s) to be executed if expression is true
}

Example

<script type="text/javascript">
var count = 0;
[Link]("Starting Loop" + "<br/>");
while (count < 10){
[Link]("Current Count : " + count + "<br/>");
count++;
}
[Link]("Loop stopped!");
</script>
For Loop
The for loop is the most compact form of looping and includes the following three important
parts:

 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
 The test statement which will test if the given condition is true or not. If condition is true
then code given inside the loop will be executed otherwise loop will come out.
 The iteration statement where you can increase or decrease your counter.
Syntax

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}

Example

<script type="text/javascript">
var count;
[Link]("Starting Loop" + "<br/>");
for(count = 0; count < 10; count++){
[Link]("Current Count : " + count );
[Link]("<br/>");
}
[Link]("Loop stopped!");
</script>

4.11. Array in JavaScript


An array is a special variable, which can hold more than one value.
const cars = ["Saab", "Volvo", "BMW"];

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.


Syntax:
const array_name = [item1, item2, ...];
It is a common practice to declare arrays with the const keyword.
Example:
const cars = ["Saab", "Volvo", "BMW"];
You can also create an array, and then provide the elements.
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it.
const cars = new Array("Saab", "Volvo", "BMW");

Accessing Array Elements

You access an array element by referring to the index number.


const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];

Changing an Array Element

This statement changes the value of the first element in cars:


cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name.
Example
const cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML = cars;

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John.
Array:
const person = ["John", "Doe", 46];

Objects use names to access its "members". In this example, [Link] returns John.
Object:
const person = {firstName:"John", lastName:"Doe", age:46};

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.


Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in
an Array.
myArray[0] = [Link];
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:
[Link] // Returns the number of elements
[Link]() // Sorts the array

The length Property

The length property of an array returns the length of an array (the number of array elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = [Link];
The length property is always one more than the highest array index.

Accessing the First Array Element

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];
Accessing the Last Array Element

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[[Link] - 1];
Looping Array Elements
One way to loop through an array, is using a for loop:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = [Link];
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

Adding Array Elements

The easiest way to add a new element to an array is using the push() method.
Example
const fruits = ["Banana", "Orange", "Apple"];
[Link]("Lemon"); // Adds a new element (Lemon) to fruits

4.12. JavaScript Functions


A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
Example:
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ( ).
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: { }
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Functions </h2>
<p> This example calls a function which performs a calculation and
returns the result: </p>
<p id="demo"> </p>
<script>
var x = myFunction(4, 3);
[Link]("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same code
many times with different arguments, to produce different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
[Link]("demo").innerHTML = toCelsius(77);

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from Fahrenheit to
Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
[Link]("demo").innerHTML = toCelsius(77);
</script>
</body>
</html>

The () Operator Invokes the Function

Using the example above, toCelsius refers to the function object, and toCelsius() refers to
the function result.
Accessing a function without () will return the function object instead of the function result.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
[Link]("demo").innerHTML = toCelsius;

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.


Local variables can only be accessed from within the function.
Example:
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
Since local variables are only recognized inside their functions, variables with the same name
can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.

JavaScript Date() Function


Following is the sample program that shows time, when we click in button.
Example:

<html>
<body>
<button onclick="[Link]=Date()">The time is?</button>
<p>Click to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
[Link]("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</script>
</body>
</html>

Output

Displaying Dates

JavaScript will (by default) output dates in full text string format.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>new Date() without arguments, creates a date object with the
current date and time:</p>
<p id="demo"></p>
<script>
const d = new Date();
[Link]("demo").innerHTML = d;
</script>
</body>
</html>

The toDateString() method converts a date to a more readable format:


const d = new Date();
[Link]();
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The toDateString() Method</h2>
<p>Convert a date to a date string:</p>
<p id="demo"></p>
<script>
const d = new Date();
[Link]("demo").innerHTML = [Link]();
</script>
</body>
</html>
4.13. JavaScript HTML DOM (Document Object Model)
With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects.
The HTML DOM Tree of Objects:

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It
defines:

 The HTML elements as objects


 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
Generally, The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

JavaScript - HTML DOM Methods

HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.

The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).
Example
The following example changes the content (the innerHTML) of the <p> element with
id="demo":
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

In the example above, getElementById is a method, while innerHTML is a property.

The getElementById Method

The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The innerHTML property can be used to get or change any HTML element, including <html>
and <body>.

DOM Form Processing

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 = [Link]["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:


HTML Form Example
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

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:
HTML Form Example
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
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.

JavaScript provides a way to validate form's data on the client's computer before sending it to the
web server. Form validation generally performs two functions.
 Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check for
data.
 Data Format Validation − Secondly, the data that is entered must be checked for correct
form and value. Your code must include appropriate logic to test correctness of data.
JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

JavaScript Form Validation Example

In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.

<script>
function validateform(){
var name=[Link];
var password=[Link];

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]"
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

JavaScript Retype Password Validation

<script type="text/javascript">
function matchpass(){
var firstpassword=[Link];
var secondpassword=[Link];

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="[Link]" onsubmit="return matchpass()">


Password: <input type="password" name="password" /><br/>
Re-enter Password: <input type="password" name="password2"/><br/>
<input type="submit">
</form>
JavaScript Number Validation

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value
only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num">
<span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

JavaScript email validation

We can validate the email by the help of JavaScript.


There are many criteria that need to be follow to validate the email id such as:
 email id must contain the @ and . character
 There must be at least one character before and after the @.
 There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.
<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=
[Link]){
alert("Please enter a valid e-mail address \n
atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>

You might also like