Functions
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.
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.
• 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.
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() {
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>