0% found this document useful (0 votes)
2 views

CIM 322 Topic 3 Javascript Functions

The document provides an overview of JavaScript functions, including their definitions, advantages, and types such as named, anonymous, library, and user-defined functions. It explains how to create, invoke, and manage functions, including concepts like hoisting, parameter passing, and scope. Additionally, it discusses best practices for coding in JavaScript, emphasizing the use of local variables and strict mode.

Uploaded by

theeeclipse17
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 views

CIM 322 Topic 3 Javascript Functions

The document provides an overview of JavaScript functions, including their definitions, advantages, and types such as named, anonymous, library, and user-defined functions. It explains how to create, invoke, and manage functions, including concepts like hoisting, parameter passing, and scope. Additionally, it discusses best practices for coding in JavaScript, emphasizing the use of local variables and strict mode.

Uploaded by

theeeclipse17
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/ 64

Week 2

Topic 3: JavaScript
Functions
Lecture Overview

Saka D. CIM 322 2


Functions
• Function - a set of related code designed to
carryout a specific task.
• A JavaScript function is executed only when
"something" invokes (calls) it.

Saka D. CIM 322 3


Advantages of Functions
1. Enables code reuse – define the code once,
and use it many times.
2. Enables code short.
3. Easy to understand
4. Easy to maintain - modify the once, affect all
the instances where it has been used.
5. Breaks a task into manageable modules.
6. Allows team work.
Saka D. CIM 322 4
Library Vs User Defined Functions
• Library function: a function inbuilt in
JavaScript engine and ready for use.
• They are used to carry out common and
complex programming tasks.
• Examples: isset, isnumeric etc.
• Use defined function: a function defined by
the programmer to meet unique
programming requirements.

Saka D. CIM 322 5


Named Vs Anonymous Functions
• Named Function – a set of related code
assigned a name.
• A named function must be called in order to
execute it.
• Use named function when you want to reuse
code.
• All library functions are named functions.

Saka D. CIM 322 6


• Anonymous function – a set of related code
with no name assigned.
• Anonymous function only works where they
are located.
• Use anonymous function for code that runs
only once.
• Some user defined functions are anonymous
functions.

Saka D. CIM 322 7


Creating a Function
• There are 2 options for creating/defining a
function in JavaScript:
i. creating a function by declaration
ii. creating a variable/expression function

Saka D. CIM 322 8


Declaring a Function
• Syntax:
function functionName(parameter-list)
{
statement(s)
}

Saka D. CIM 322 9


Anatomy of a Function Declaration
• It consists of:
i). Function Header
• Made up of 2 components
a) Function name – identifies the function.
b) Parameter list – provides means of passing
data into out of the function.

Saka D. CIM 322 10


• Parameter list is optional.
• If not there, the brackets should remain
empty.
ii). Function body
• A set of statements that define the function’s
behavior.
iii). A pair of curly “{}” brackets to mark
beginning and end of the function.
Saka D. CIM 322 11
• Example:
function sayHello()
{
alert("Hello Africa!");
}

Saka D. CIM 322 12


Function Declaration Placement
• A function can be defined/placed in:
i. The body section of an HTML document
ii. The head section of an HTML document
iii. In an external file (.js file)

Saka D. CIM 322 13


Defining a Function in the Body Section
• Example:
<body>
<script type="text/javascript">
function greetings()
{
document.write ("Hello there!");
}
</script>
</body>

Saka D. CIM 322 14


Function Invocation
• There are 3 ways in which a function invoked
(called) into execution:
i. Automatically calling itself (self invoked) e.g.
anonymous function.
ii. When it is invoked (called) as a stand alone
JavaScript code
iii. When it is invoked (called) on the RHS of an
assignment statement
iv. When an event occurs (e.g. when a user clicks a
button)

Saka D. CIM 322 15


Invoking (calling) a Function From JavaScript
within Code

Saka D. CIM 322 16


<!DOCTYPE html>
<html>
<head>
<title>Function Call Demo</title>
</head>
<body>
<h2 align="center">Function Declaration</h2>
<script>
greetings();
function greetings() {
alert ("Hello Africa!");
}
</script>
</body>

Saka D. CIM 322 17


Event Driven Function Invocation
• A function can be invoked when an event fires
(happen) by attaching the function to the
respective event listener of an HTML object.
• Examples:
Object Event Event Listener
Button Click onclick
paragraph mouseover onmouseover

Saka D. CIM 322 18


• Example:
<input type="button" value="Click me"
onclick="greetings()" />

Event listener event handler


• Event listener: an object that monitors the
occurrence of an event in the browser
• Event handler: is a function that's executed when
an event occurs i.e. it "handles“ the event.

Saka D. CIM 322 19


• Example App:

Saka D. CIM 322 20


<!DOCTYPE html>
<html>
<head><title>Function Call Demo</title></head>
<body>
<h2 align="center">Function Invocation By an Event</h2>
<p>Click the button below to see your greetings</p>
<form>
<input type="button" value="Click me" onclick="greetings()" />
</form>
<script>
function greetings() {
alert ("Hello Africa!");
}
</script>
</body>
</html>

Saka D. CIM 322 21


Function Hoisting
• Hoisting: is JavaScript's default behavior
of moving declarations to the top of the
current scope.
• Hoisting applies to variable declarations
and to function declarations.
• Because of this, declared functions can
be called before they are declared.

Saka D. CIM 322 22


How Values are Passed to Functions
(Parameter Passing)

Saka D. CIM 322 23


• Values are passed to/from function by means
of parameters.
• Parameters: variables that provide means of
passing data into or out of a function.
• Formal parameters – parameters in the
function header.
• The server as channels for passing data into a
function.
• They are optional.
Saka D. CIM 322 24
• Actual parameters (Arguments) – parameters
in the calling statement.
• They specify the values to be passed to a
functions.
• They are also optional.
• N/B: the number of formal parameter list
must match that in the actual parameter list.

Saka D. CIM 322 25


<!DOCTYPE html>
<head><title>Parameter Passing</title></head>
<body>
<h2>Exams</h2>
<script>
var english = parseInt(prompt("Enter English mark:"));
var mathematics = parseInt(prompt("Enter Math mark:"));
calculator(english, mathematics);
function calculator(eng, math){
total = eng + math;
document.write("English :", eng, "<br />");
document.write("Mathematics:", math, "<br />");
document.write("Total :", total, "<br />");
}
</script>
</body>
</html>

Saka D. CIM 322 26


Value Formal Parameters Vs Reference Formal
Parameters
• When you pass a number, string, or Boolean
value (primitive type) to a function, it is
passed by value.
• This means that a copy of the value is sent to
the function, not the value itself.
• As a result, the function can't change the
original value.
Saka D. CIM 322 27
• In contrast, when you pass an object (e.g.
form) to a function, it is passed by reference.
• This means that a reference (actual storage) to
the object is sent to the function instead of a
copy of the object.
• Then, the function changes the object that the
reference identifies.
• As a result, those changes will persist after the
function has finished.
Saka D. CIM 322 28
The Return Statement
• It is required if a function is to communicate a
value back to the caller module.
• It should be the last statement.
• The return statement stops the execution of a
function and returns a value to the caller
module.
• Example:

Saka D. CIM 322 29


• Example Average Age App:

Saka D. CIM 322 30


<html>
<head><title>Return Statement</title></head>
<body>
<h2 align="center">Average Age App</h2>
<p>Enter ages of 2 pupils and find average</p>
<script>
var fNum, sNum, average
fNum = parseInt(prompt("Enter 1st Number:"));
sNum = parseInt(prompt("Enter 2nd number:"));
average = avg(fNum, sNum);
document.write("First child's age:" , fNum, "<br />");
document.write("Second child's age:" , sNum, "<br />");
document.write("Average age:" , average);
function avg(num1,num2){
var result;
result=(num1 + num2)/2;
return result;
}
</script>
</body>
</html>

Saka D. CIM 322 31


Function Expressions/Variable
Functions
• A JavaScript function can also be defined using
an expression.
• A function expression can be stored in a
variable.
• Hence, they are also called variable functions.
• They need not be given a name because the
they can be called by the variable name
(anonymous function).

Saka D. CIM 322 32


• Syntax:
var variableName = function(parameters) {
statement(s);
};
• Example:
var calculateTax =function( subtotal, taxRate) {
var tax= subtotal* taxRate;
return tax;
};

Saka D. CIM 322 33


How to call the function
var subtotal= 85.00;
var taxRate = 0.05;
var salesTax = calculateTax( subtotal, taxRate );
// calls the function
alert{salesTax); // displays 4.25

Saka D. CIM 322 34


• Example 2: A function expression with one
parameter that returns a DOM element
var mail= function(id) {
return document.getElementByid{id);
};
How to call the function
var emailAddress1 =
mail(“email_address1”).value;
Saka D. CIM 322 35
• N/B: Functions created by way of function
expression are not hoisted by the JavaScript
interpreter.

Saka D. CIM 322 36


• Example App:

Saka D. CIM 322 37


<!DOCTYPE html>
<html>
<head><title>Function Expression</title></head>
<body>
<h2>Function Expression</h2>
<script>
const taxRate = 0.05;
var calculateTax = function( sal, rate) {
var tax= sal * rate; tax= tax.toFixed(2);
return tax;
};
//How to call the function
var salary = parseFloat(prompt("Enter salary"));
var salaryTax = calculateTax( salary, taxRate ); // calls the function
document.write("Salary:", salary, "<br />"); // displays 4.25
document.write("TaxRate:", taxRate, "<br />");
document.write("Tax:", salaryTax, "<br />");
</script>
</body>
</html>

Saka D. CIM 322 38


Self-Invoking Functions
• Function expressions can be made "self-
invoking".
• A self-invoking expression is invoked (started)
automatically, without being called.
• Function expressions will execute
automatically if the expression is followed by
() operator.

Saka D. CIM 322 39


• You have to add parentheses around the
function to indicate that it is a function
expression.
• N/B: You cannot self-invoke a function
declaration.

Saka D. CIM 322 40


• Example App:
<!DOCTYPE html>
<html>
<head><title>Self Invoke Function</title></head>
<body>
<p>Functions can be invoked automatically without being
called:</p>
<script>
(function () {
alert("Hello Africa");
})();
</script>
</body>
</html>

Saka D. CIM 322 41


Function Nesting
• Refers to placing a function inside another
function.
• Example:

Saka D. CIM 322 42


• Example App:
<!DOCTYPE html>
<head><title>Parameter Passing</title></head>
<body>
<h2 align="center">Exams</h2>
<script>
var english = parseInt(prompt("Enter English mark:"));
var mathematics = parseInt(prompt("Enter Math mark:"));
var average = calculator(english, mathematics);
document.write("English :", english, "<br />");
document.write("Mathematics:", mathematics, "<br />");
document.write("Average :", average, "<br />");

function calculator(eng, math){


var x = eng; var y = math;
sum = summation(x, y);
avg = sum/2;

function summation (a, b){


var total = a + b;
return total;
}
return avg;
}
</script>
</body>
</html>

Saka D. CIM 322 43


Variable/Function Scope
• Scope – refers to the visibility and accessibility
of a variable or function.
• JavaScript uses lexical scope, as opposed to
dynamic scope.
• Lexical (static) scope : it doesn’t change when
the program runs.
• This means that you can determine the scope
of a variable or function by looking at where it
is in the code.
Saka D. CIM 322 44
• JavaScript has 3 scopes: global scope, local
scope, and block scope.
i). Block Scope/ Block Variable
• Variable declared within a block
• They are declared using the let or const
keywords
• Variables declared inside a { } block cannot be
accessed from outside the block.
Saka D. CIM 322 45
• Example:
If i>5 {
const x=2;
let y=0;
document.write(i);
}

Saka D. CIM 322 46


ii) Local Variable/Scope
• Variables declared within a JavaScript function.
• Local variables have Function Scope.
• They can only be accessed from within the
function (locally).
• Example:
function myFunction() {
const carName = "Volvo"; // Function Scope
}
Saka D. CIM 322 47
iii) Global Variable/Scope
• A variable declared outside any function.
• Global variables can be accessed from anywhere
in a JavaScript program.
• Example:
let carName = "Volvo";
function myFunction() {
// code here can also use carName
}
Saka D. CIM 322 48
JS5 Strict Mode
• The strict mode was introduced in ECMAScript
5.
• With strict mode, you can not use undeclared
variables and constants or duplicate
parameters.
• Strict mode is declared by “use strict”
directive.
• This can be declared at the beginning of a
script or a function.
Saka D. CIM 322 49
• When declared at the beginning of a script, it
has global scope (all code in the script will
execute in strict mode).
• Declared inside a function, it has local scope
(only the code inside the function is in strict
mode).

Saka D. CIM 322 50


• Example:
<!DOCTYPE html>
<html>
<body>
<p>"use strict" in a function will only cause errors in that function.</p>
<p>Activate debugging in your browser (F12) to see the error
report.</p>
<script>
x = 3.14; // This will not cause an error.
myFunction();
function myFunction() {
"use strict";
y = 3.14; // This will cause an error (y is not defined).
}
</script>
</body>
</html>

Saka D. CIM 322 51


Coding Best Practices
1. Use local variables whenever possible.
2. Use the var keyword to declare all variables.
3. Use strict mode.
4. Declare the variables that are used in a
function at the start of the function.

Saka D. CIM 322 52


Creating a JavaScript Source File
(.js File)
• The file contains only JavaScript statements,
and it does not contain the script element.
• Instead, the script element is located within
the HTML document that calls the source file.
• N/B: the file is saved with the “.js” file
extension.
• Example: hello.js

Saka D. CIM 322 53


Linking a Source File with HTML Document
• Use the src attribute of the <script> tag.
• You assign to the src attribute the URL of a
JavaScript source file.
• Example: <script src="scripts.js"></script>
• You can place an external script reference in
<head> or <body> sections as you like.
• The script will behave as if it was located exactly
where the <script> tag is located.

Saka D. CIM 322 54


• Example File: ExtJS.js
function sayHello()
{
alert ("Hello there!");
}

Saka D. CIM 322 55


• Example 2: ExtJS.html
<html>
<head>
<title>JS Link Demo2</title>
<script src=“extjs.js"></script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say
Hello">
</form>
</body>
</html>
Saka D. CIM 322 56
Advantages/Disadvantages of JS Files
Advantages
1. It helps in the reusability of the code in more
than one HTML file.
2. It allows easy code readability.
3. It is time-efficient, as web browsers cache the
external js files, which further reduces the page
loading time.

Saka D. CIM 322 57


4. It enables both, web designers and coders, to
work with HTML and js files parallelly and
separately, i.e., without facing any code
conflictions.
5. The length of the code reduces as we only
need to specify the location of the js file.

Saka D. CIM 322 58


Disadvantages
1. If two js files are dependent on one another,
then a failure in one file may affect the
execution of the other dependent file.
2. The web browser needs to make an additional
HTTP request to get the js code.

Saka D. CIM 322 59


3. A tiny to a large change in the js code may
cause unexpected results in all its dependent
files.
4. We need to check each file that depends on
the commonly created external JavaScript file.

Saka D. CIM 322 60


JavaScript Libraries
• A JavaScript library is an external file that
contains related functions, objects, or both.
• JavaScript libraries range from simple
collections of functions that you write yourself
to extensive third-party tools like jQuery.
• Organizing your code in libraries encourages
separation of concerns, which makes it easier
to maintain and reuse code.

Saka D. CIM 322 61


• You include JavaScript libraries in your
applications by using script tags.
• If a library depends on another library, you
must make sure that the script tag for the
needed library precedes the one for the
library that uses it.

Saka D. CIM 322 62


Benefits of JavaScript libraries
1. Allows you to group similar functionality in a
single file.
2. Makes code easier to read and understand
code.
3. Easy to maintain code.
4. Encourages code reuse.

Saka D. CIM 322 63


Some Popular JavaScript Libraries
Library Purpose
jQuery General-purpose, cross-browser functionality
for DOM scripting.
jQuery UI User interface functionality like tabs and
accordions. It requires the jQuery library.
AngularJS Framework for Single-Page Applications
(SPAs).
Underscore Utility functions for common programming
tasks.
Backbone Framework for SPAs based on the Model
View Presenter design pattern.
shim.js, sham.js ECMAScript 5 compatibility for older
browsers.

Saka D. CIM 322 64

You might also like