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

Functions

Uploaded by

venkat Mohan
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)
17 views

Functions

Uploaded by

venkat Mohan
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/ 10

Functions

• The JavaScript engine can execute JavaScript code in two different modes:
o Immediate mode - As soon as the webpage loads on the browser,
JavaScript code embedded inside it, executes without any delay.
o Deferred mode - Execution of JavaScript code is deferred or delayed
until any user action like data input, button click, drop-down selection,
etc. takes place.
• The JavaScript code understood so far was running in immediate mode. As
soon as the page is loaded in the browser, the script gets executed line by line
without any delay.
• But in real-world application development, it is not possible to wait for
sequential execution of the code written for the huge applications. JavaScript
provides a solution to this problem in the form of JavaScript functions.
• Functions are one of the integral components of JavaScript. A JavaScript
function is a set of statements that performs a specific task. They become a
reusable unit of code.
• In JavaScript, functions are first-class objects. i.e., functions can be passed as
an argument to other functions, it can be a return value of another function or
can be assigned as a value to a variable. JavaScript leverages this behavior to
extend its capabilities.
• JavaScript has two types of functions.
o User-defined functions - JavaScript allows to write own functions called
as user-defined functions. The user-defined functions can also be
created using a much simpler syntax called arrow functions.
o Built-in functions - JavaScript provides several predefined functions
that perform tasks such as displaying dialog boxes, parsing a string
argument, timing-related operations, and so on.
• Function Declaration and Function Invocation
• To use a function, it must be defined or declared and then it can be invoked
anywhere in the program.
• A function declaration also called a function definition, consists of the function
keyword, followed by: Function name
• A list of parameters to the function separated by commas and enclosed in
parentheses, if any.
• A set of JavaScript statements that define the function, also called a function
body, enclosed in curly brackets {…}.
• Syntax for Function Declaration:
function function_name(parameter 1, parameter 2 , …, parameter n) {
//statements to be executed
}
The code written inside the function body will be executed only when it is
invoked or called.
• Syntax for Function Invocation:
function_name(argument 1, argument 2, ..., argument n);
Example
function multiply(num1, num2) {
return num1 * num2;
}
document.write(multiply(5,6))
Function Parameters
• Function parameters are the variables that are defined in the function
definition and the values passed to the function when it is invoked are
called arguments.
• In JavaScript, function definition does not have any data type specified for the
parameters, and type checking is not performed on the arguments passed to the
function.
• JavaScript does not throw any error if the number of arguments passed during
a function invocation doesn’t match with the number of parameters listed
during the function definition. If the number of parameters is more than the
number of arguments, then the parameters that have no corresponding
arguments are set to undefined.
function multiply(num1, num2) {
if (num2 == undefined) {
num2 = 1;
}
return num1 * num2;
}
console.log(multiply(5, 6)); // 30
console.log(multiply(5)); // 5
Default Parameters
JavaScript introduces an option to assign default values in functions.
function multiply(num1, num2 = 1) {
return num1 * num2;
}
console.log(multiply(5, 5)); //25
console.log(multiply(10)); //10
console.log(multiply(10, undefined)); //10
• In the above example, when the function is invoked with two parameters, the
default value of num2 will be overridden and considered when the value is
omitted while calling.

• Rest parameter syntax allows to hold an indefinite number of arguments in the


form of an array.
Syntax:
function(a, …args) {
//…
}
• The rest of the parameters can be included in the function definition by using
three dots ( … ) followed by the name of the array that will hold them.
Example:
function showNumbers(x, y, …z) {
return z;
}
console.log(showNumbers(1, 2, 3, 4, 5)); // [3,4,5]
console.log(showNumbers(3, 4, 5, 6, 7, 8, 9, 10)); // [5,6,7,8,9,10]
• The rest parameter should always be the last parameter in the function
definition.

Destructuring Assignment
• Destructuring gives a syntax which makes it easy to unpack values from arrays,
or properties from objects, into different variables.
Array destructuring in functions
Example:
let myArray = ["Andrew", "James", "Chris"];
function showDetails([arg1, arg2]) {
console.log(arg1); // Andrew
console.log(arg2); // James
}
showDetails(myArray);
In the above example, the first two array elements ‘Andrew’ and 'James’ have been
destructured into individual function parameters arg1 and arg2.
Object destructuring in functions
Example:
let myObject = { name: "Mark", age: 25, country: "India" };
function showDetails({ name, country }) {
console.log(name, country); // Mark India
}
showDetails(myObject);
• The properties name and country of the object have been destructured and
captured as a function parameter.

Nested Functions
• In JavaScript, it is perfectly normal to have functions inside functions. The
function within another function body is called a nested function.
• The nested function is private to the container function and cannot be invoked
from outside the container function.
Example:
function giveMessage(message) {
let userMsg = message;
function toUser(userName) {
let name = userName;
let greet = userMsg + " " + name;
return greet;
}
userMsg = toUser("Bob");
return userMsg;
}
console.log(giveMessage("The world says hello dear: "));
// The world says hello dear: Bob
Arrow Functions (the fat arrow)
• In JavaScript, functions are first-class objects. This means, that you can assign
a function as a value to a variable. For example,
let sayHello = function () {
console.log("Welcome to JavaScript");
};
sayHello();
• Here, a function without a name is called an anonymous function which is
assigned to a variable sayHello.
• JavaScript has introduced a new and concise way of writing functions using
arrow notation. The arrow function is one of the easiest ways to declare an
anonymous function.
Example:
let sayHello = () => {
console.log("Welcome to JavaScript");
};
sayHello();
• There are two parts for the Arrow function syntax:
1. let sayHello = ()
• This declares a variable sayHello and assigns a function to it using () to
just say that the variable is a function.
2. => { }
• This declares the body of the function with an arrow and the curly braces.
• Below are a few scenarios of arrow functions.

Syntax 1: Multi-parameter, multi-line code:


If code is in multiple lines, use {}.
calculateCost = (ticketPrice, noOfPerson)=>{
noOfPerson= ticketPrice * noOfPerson;
return noOfPerson;
}
console.log(calculateCost(500, 2));
// 1000

Syntax 2: No parameter, single line code:


If the code is single line, {} is not required. The expression is evaluated and
automatically returned.
trip = () => "Let's go to trip."
console.log(trip());
// Let's go to trip.

Syntax 3: One parameter, single line code:


If only one parameter, then () is not required.
trip = place => "Trip to " + place;
console.log(trip("Paris"));
// Trip to Paris
Syntax 4: One parameter, single line code:
if only one parameter, use '_' and do not use a variable name also.
trip = _ => "Trip to " + _;
console.log(trip("Paris"));
// Trip to Paris

'this' keyword in Arrow function

• JavaScript comes with certain built-in functions. To use them, they need to be
invoked.
• Below is the table with some of these built-in functions to understand their
significance and usage.
Built-in
Description Example
functions
It throws an alert box and is often
used when user interaction is
alert() alert("Let us proceed");
required to decide whether
execution should proceed or not.
It throws a confirm box where user
can click "OK" or "Cancel". If "OK" let decision = confirm("Shall we
confirm()
is clicked, the function returns proceed?");
"true", else returns "false".
It produces a box where user can
enter an input. The user input may
be used for some processing later. let userInput = prompt("Please enter
prompt()
This function takes parameter of your name:");
type string which represents the
label of the box.
This function checks if the data-
type of given parameter is number isNaN(30); //false
isNaN()
or not. If number, it returns isNaN('hello'); //true
"false", else it returns "true".
It determines if the number given
as parameter is a finite number. If
the parameter value is isFinite(30); //true
isFinite()
NaN,positive infinity, or negative isFinite('hello'); //false
infinity, this method will return
false, else will return true.
This function parses string and
returns an integer number.
It takes two parameters. The first
parameter is the string to be
parseInt("10"); //10
parsed. The second parameter
parseInt("10 20 30"); //10, only the
represents radix which is an
integer part is returned
parseInt() integer between 2 and 36 that
parseInt("10 years"); //10
represents the numerical system to
parseInt("years 10"); //NaN, the
be used and is optional.
first character stops the parsing
The method stops parsing when it
encounters a non-numerical
character and returns the gathered
number.
It returns NaN when the first non-
whitespace character cannot be
converted to number.
This function parses string and
returns a float number.
The method stops parsing when it
parseFloat("10.34"); //10.34
encounters a non-numerical
parseFloat("10 20 30"); //10
parseFloat() character and further characters
parseFloat("10.50 years"); //10.50
are ignored.
It returns NaN when the first non-
whitespace character cannot be
converted to number.
It takes an argument of type string
eval("let num1=2; let
which can be an expression,
eval() num2=3;let result= num1 *
statement or sequence of
num2;console.log(result)");
statements and evaluates them.

• JavaScript provides two-timer built-in functions. Let us explore these timer


functions.
Built-in
Description Example
functions
It executes a given function
after waiting for the specified
function executeMe(){
number of milliseconds.
console.log("Function says hello!")
It takes 2 parameters. First is
}
setTimeout() the function to be executed
setTimeout(executeMe, 3000);
and the second is the number
//It executes executeMe() after 3
of milliseconds after which
seconds.
the given function should be
executed.
It cancels a timeout
previously established by
calling setTimeout(). function executeMe(){
It takes the parameter console.log("Function says hello!")
"timeoutID" which is the }
clearTimeout()
identifier of the timeout that let timerId= setTimeout(executeMe,
can be used to cancel the 3000);
execution of setTimeout(). clearTimeout(timerId);
The ID is returned by the
setTimeout().
It executes the given function
repetitively.
function executeMe(){
It takes 2 parameters, first is
console.log("Function says hello!");
the function to be executed
}
setInterval() and second is the number of
setInterval(executeMe,3000);
milliseconds. The function
//It executes executeMe() every 3
executes continuously after
seconds
every given number of
milliseconds.
function executeMe(){
It cancels the timed, repeating console.log("Function says hello!");
execution which was }
previously established by a let timerId=setInterval(executeMe,
call to setInterval(). 2000);
It takes the parameter function stopInterval(){
clearInterval() “intervalID” which is the clearInterval(timerId);
identifier of the timeout that console.log("Function says bye to
can be used to cancel the setInterval()!")
execution of setInterval(). The setTimeout(stopInterval,5000)
ID is returned by the //It executes executeMe() every 2
setInterval(). seconds and after 5 seconds, further
calls to executeMe() is stopped.

Scopes
• Variable declaration in the JavaScript program can be done within the function
or outside the function. But the accessibility of the variable to other parts of the
same program is decided based on the place of its declaration. This accessibility
of a variable is referred to as scope.
• JavaScript scopes can be of three types:
• Global scope
• Local scope
• Block scope

• Variables defined outside function have Global Scope and they are accessible
anywhere in the program.
Example:

//Global variable
var greet = "Hello JavaScript";
function message() {

//Global variable accessed inside the function


console.log("Message from inside the function: " + greet);
}
message();
//Global variable accessed outside the function
console.log("Message from outside the function: " + greet);
//Message from inside the function: Hello JavaScript
//Message from outside the function: Hello JavaScript
• Variables declared inside the function would have local scope. These variables
cannot be accessed outside the declared function block.
Example:
function message() {
//Local variable
var greet = "Hello JavaScript";
//Local variables are accessible inside the function
console.log("Message from inside the function: " + greet);
}
message();
//Local variable cannot be accessed outside the function
console.log("Message from outside the function: " + greet);
//Message from inside the function: Hello JavaScript
//Uncaught ReferenceError: greet is not defined
• If a local variable is declared without the use of keyword 'var', it takes a global
scope.
Example:
//Global variable
var firstName = "Mark";
function fullName() {
//Variable declared without var has global scope
lastName = "Zuckerberg";
console.log("Full Name from inside the function: " + firstName + " " +
lastName);
}
fullName();
console.log("Full Name from outside the function: " + firstName + " " +
lastName);
//Full Name from inside the function: Mark Zuckerberg
//Full Name from outside the function: Mark Zuckerberg
• In 2015, JavaScript introduced two new keywords to declare variables: let and
const.
• Variables declared with 'var' keyword are function-scoped whereas variables
declared with 'let' and 'const' are block-scoped and they exist only in the block
in which they are defined.
• Consider the below example:
function testVar() {
if (10 == 10) {
var flag = "true";
}
console.log(flag); //true
}
testVar();
• In the above example, the variable flag declared inside 'if' block is accessible
outside the block since it has function scope
• Modifying the code to use 'let' variable will result in an error:
function testVar() {
if (10 == 10) {
let flag = "true";
}
console.log(flag); //Uncaught ReferenceError: flag is not defined
}
testVar();
• The usage of 'let' in the above code snippet has restricted the variable scope
only to 'if' block.
• 'const' has the same scope as that of 'let' i.e., block scope.
Practice
Problem Statement:
Write a JavaScript code to do online booking of theatre tickets and calculate the total
price based on the below conditions:
1. If seats to be booked are not more than 2, the cost per ticket remains $9.
2. If seats are 6 or more, booking is not allowed.
3. If seats to be booked are more than 2 but less than 5, based on the number of
seats booked, do the following:
o Calculate total cost by applying a discount of 5, 7, 9, 11 percent, and so
on for customer 1,2,3 till 5.
o Try the code with different values for the number of seats.
Write the following custom functions to implement given requirements:
1. calculateCost(seats): Calculate and display the total cost to be paid by the
customer for the tickets they have bought.
2. calculateDiscount(seats): Calculate discount on the tickets bought by the
customer. Implement using arrow functions.
Expected Output:

Starter code:
<!DOCTYPE html>
<html>
<head>
<title>Booking Summary</title>
<style>
div#maincontent {
height: 250px;
width: 500px;
border: 1px solid #CEE2FA;
text-align: left;
color: #08438E;
font-family: calibri;
font-size: 20;
padding: 5px;
}
div#heading {
text-decoration: bold;
text-align: center;
margin-top: 80px;
width: 500px;
border: 1px solid #CEE2FA;
text-align: center;
color: #08438E;
background-color: #CEE2FA;
font-family: calibri;
font-size: 20;
padding: 5px;
}
h2 {
padding: 0;
margin: 0;
}
</style>
</head>

<body>
<center>
<div id="heading">
<h2>Booking Summary</h2>
</div>
<div id="maincontent">
<script>
//Write the code to display the booking summary
</script>
</div>
</center>
</body>

</html>

You might also like