JavaScript Functions
A function is a group of statements that perform specific tasks
and can be kept and maintained separately from main program. Functions provide
a way to create reusable code packages that are more portable and easier to
debug.
Advantage of JavaScript
function
There are mainly three advantages of JavaScript functions.
- Code reusability: We can call a function several
times so it saves coding.
- Less coding: It makes our program compact. We
don’t need to write many lines of code each time to perform a common task.
- Eliminate errors: When the program is subdivided into functions if any error occurs you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.
We’ve already seen examples of built-in
functions, like alert(message)
, prompt(message,
default)
and confirm(question)
. But JavaScript allows us to create user-defined
functions also.
The following section will show you how to define and call
functions in your scripts.
Defining and Calling a
Function
The declaration
of a function start with the function
keyword,
followed by the name of the function you want to create, followed by
parentheses i.e. ()
and
finally, place your function's code between curly brackets {}
. Here's the basic syntax for declaring a function:
function functionName() {
//
Code to be executed
}
Here is a simple example of a function, that will show a hello message:
Example
// Defining function
functionsayHello()
{
alert("Hello, welcome to this website!");
}
// Calling function
sayHello();// 0utputs: Hello, welcome to this website!
Once a function
is defined it can be called (invoked) from anywhere in the document, by typing
its name followed by a set of parentheses, like sayHello()
in the example above.
Note: A function name must
start with a letter or underscore character, not with a number, optionally
followed by more letters, numbers, or underscore characters. Function names
are case sensitive, just like variable names.
Adding Parameters to
Functions
You can specify
parameters when you define your function to accept input values at run time.
The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the function
at the time of invocation.
Parameters are
set on the first line of the function inside the set of parentheses, like this:
function functionName(parameter1, parameter2, parameter3)
{
//
Code to be executed
}
The displaySum()
function in the following example takes two numbers as
arguments, simply add them together and then display the result in the browser.
Example
// Defining function
functiondisplaySum(
num1
,num2
){
var
total
=num1
+num2
;
alert(
total
);
}
// Calling function
displaySum(6,20);
// 0utputs: 26
displaySum(-5,17);
// 0utputs: 12
You can define
as many parameters as you like. However, for each parameter, you specify, the corresponding argument needs to be passed to the function when it is called,
otherwise, its value becomes undefined
. Let's consider the following example:
Example
// Defining function
functionshowFullname(
firstName
,lastName
){
alert(
firstName
+" "
+
lastName
);
}
// Calling function
showFullname("Clark","Kent");
// 0utputs: Clark Kent
showFullname("John");// 0utputs: John undefined
Default Values
for Function Parameters ES6
With ES6, now
you can specify default values to the function parameters. This means that if
no arguments are provided to the function when it is called these default
parameter values will be used. This is one of the most awaited features in
JavaScript. If a parameter is not provided, then its value becomes undefined
.
For instance, the aforementioned function showMessage(from, text)
can be called with a single argument:
That’s not an error. Such a call would output "*Ann*: undefined"
. There’s no text
, so it’s assumed that text === undefined
.
If we want to use a “default” text
in this case, then we can specify it after =
:
"no text given"
is a string, but it can be a more complex expression, which is only evaluated and assigned if the parameter is missing. Here's another example:Example
functionsayHello(
name
='Guest')
{
alert('Hello, '
+
name
);
}
sayHello();
// 0utputs: Hello, Guest
sayHello('John');// 0utputs: Hello, John
While prior to
ES6, to achieve the same we had to write something like this:
Example
functionsayHello(
name
){
var
name
=name
||'Guest';
alert('Hello, '
+
name
);
}
sayHello();// 0utputs: Hello, Guest
sayHello('John');
// 0utputs: Hello, John
Returning Values from a
Function
A function can
return a value back to the script that called the function as a result using
the return
statement. The value may be of any type, including arrays
and objects.
The return
statement usually placed as the last line of the function
before the closing curly bracket and ends it with a semicolon, as shown in the
following example.
Example
// Defining function
functiongetSum(
num1
,num2
){
var
total
=num1
+num2
;
return
total
;
}
// Displaying returned value
alert(getSum(6,20));
// 0utputs: 26
alert(getSum(-5,17));
// 0utputs: 12
A function can not return multiple
values. However, you can obtain similar results by returning an array of
values, as demonstrated in the following example.
Example
// Defining function
functiondivideNumbers(
dividend
,divisor
){
var
quotient
=dividend
/divisor
;
var
arr
=[
dividend
,divisor
,quotient
];
return
arr
;
}
// Store returned value in a variable
varall
=divideNumbers(10,
2);
// Displaying individual values
alert(all
[0]);// 0utputs: 10
alert(all
[1]);// 0utputs: 2
alert(all
[2]);// 0utputs: 5
Local variables
A variable declared inside a function is only visible inside
that function.
Example:
Outer variables
A function can access an outer variable as well, for example:
The function has full access to the outer variable. It can
modify it as well.
For instance:
The outer variable is only used if there’s no
local one. If a same-named variable is declared inside the function then it shadows the outer one.
For instance, in the code below the function uses the local userName
.
The outer one is ignored:
let userName = 'John';
Global variables
Variables declared outside of any function,
such as the outer userName
in the code above, are
called global. Global variables are visible from any
function (unless shadowed by locals).
It’s a good practice to minimize the use of global variables. Modern code has few or no globals. Most variables reside in their functions. Sometimes though, they can be useful to store project-level data.
The arguments object
Inside the body of a function, you can access an object called arguments
that
represents the named arguments of the function.
The arguments
object behaves like an array though it is not an instance of the Array type.
For example, you can use the square bracket []
to
access the arguments: arguments[0]
returns
the first argument, arguments[1]
returns the second one, and
so on.
Furthermore, you can use the length
property
of the arguments
object to determine the number
of arguments.
The following example implements a generic add()
function
that calculates the sum of any number of arguments.
function add() {let sum = 0;for (let i = 0; i < arguments.length; i++) {sum += arguments[i];}return sum;}
Hence, you can pass any number of arguments to the add()
function,
like this:
console.log(add(1, 2)); // 3console.log(add(1, 2, 3, 4, 5)); // 15
Nested Functions
In JavaScript, a function can have one or more inner functions. These nested functions are in the scope of outer function. Inner function can access variables and parameters of outer function. However, outer function cannot access variables defined inside inner functions.
Example
Function hoisting
In JavaScript, it is possible to use a function before it is declared. See the following example:
showMe(); // a hoisting examplefunction showMe() {console.log('an hoisting example');}
This feature is called hoisting.
The function hoisting is a mechanism that the JavaScript engine physically moves function declarations to the top of the code before executing them.
The following shows the version of the code before the JavaScript engine executes it:
function showMe() {console.log('a hoisting example');}showMe(); // a hoisting exampleImportant Function Concepts
Function comes under reference data type. Variables declared inside functions are local variables. Thus they can be used only within the same function, not outside a function. typeof operator can check the datatype of the function.
JavaScript functions are first-class citizen. This means they are very powerful in JavaScript as compared to other programming languages. They are even more powerful than objects.
Why JavaScript Functions are first-class citizen?
- Functions can be assigned to variables.
- Functions can have properties and methods.
- Functions can return functions.
- Functions can have callbacks.
Working with Function Expressions
The syntax that we've used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression.
Example
// Function Declaration
functiongetSum(
num1
,num2
){
var
total
=num1
+num2
;
return
total
;
}
// Function Expression
vargetSum
=
function(
num1
,num2
){
var
total
=num1
+num2
;
return
total
;
};Once function the expression has been stored in a variable, the variable can be used as a function:
Example
vargetSum
=
function(
num1
,num2
){
var
total
=num1
+num2
;
return
total
;
};
alert(getSum(5,10));
// 0utputs: 15
varsum
=getSum(7,
25);
alert(sum
);// 0utputs: 32
Note: There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon.
Tip: In JavaScript, functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time.
The syntax of the function declaration and function expression looks very similar, but they differ in the way they are evaluated, check out the following example:
Example
declaration();// Outputs: Hi, I'm a function declaration!
functiondeclaration()
{
alert("Hi, I'm a function declaration!");
}
expression();// Uncaught TypeError: undefined is not a function
varexpression
=
function()
{
alert("Hi, I'm a function expression!");
};As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully.
JavaScript parse declaration function before the program executes. Therefore, it doesn't matter if the program invokes the function before it is defined because JavaScript has hoisted the function to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked.
ES6 has introduced even shorter syntax for writing function expression which is called arrow function, please check out the JavaScript ES6 features chapter to learn more about it.
Call a function on Button click
To call a function on button click, use the example below. In first example, a function is created on button click. In Second example, an already build function ( myFunction) is invoked on button click. As function is used inside another function (addEventListener), no need to use parentheses.
Example
<script>function sayHi(){alert("Hi");}<script><button onclick="sayHi()">Say Hi</button>Expression functions are first created and then invoked. If we call an expression function before, an error will occur. Also semicolon is required after function expression.
Arrow Functions
Arrow functions are actually a short form of expression functions. To call arrow functions, we have to declare function first and then call. Arrow functions were introduced in ES6. It's recommended using function declaration or expression for IE browsers.
var myFunc1 = (x, y) => {}; // 2 parametersvar myFunc2 = (x) => {}; // 1 parametervar myFunc3 = (x) => {}; // 1 parameterOne main difference between arrow function and expression is use of
this
keyword.
this
Keywordthis keyword in Javascript refers to the current object. In a function, this keyword value depends upon how the function is called. For any function, this keyword is window object, but in strict mode, this keyword is
undefined
. See the example belowdocument.body.onclick = function () {console.log(this);};// click on body to call function
Output:
<body></body>
'use strict';function sayHi() {console.log(this);}sayHi();Output:
undefined
In expression function,
this
keyword refers to the current object. But in arrow function, it is a window object. For such cases, avoid using arrow functions for events.
document.body.onclick = () => {console.log(this);};// click on body to call functionOutput:
Window {parent: Window, opener: null, top: Window, length: 6, frames: Window, …}
Anonymous Function
Immediate Invoke Function or self-invoking function are anonymous function who call themself. They are not assigned and named. That's why they are anonymous. But they call themself on pageload or event.
Syntax
(function () {// statement Statement})();Example
(function (x) {console.log('Hello', x);})('user');
Function Properties
Functions are first class objects in javascript, means they have both properties and methods. These properties are same for function declaration and expression functions.
function.name: Return name of function. The name of function is always string.
Example
function area1() {}var area2 = function () {};var area3 = function area4() {};area1.name; // returns "area1"area2.name; // returns "area2"area3.name; // returns "area4"
function.length: Return total no of parameters used in function.
Example
function area1(x, y) {}function area2(x, y, z) {}area1.length; // return 2area2.length; // return 3
custom property: Apart from length and name, functions can have custom properties and methods.
function user() {}user.brandname = 'Tech Altum';user.location = 'Noida';user.year = 2012;user.getAge = function () {return 2019 - user.year;};user.name; // return "user"user.brandname; // return "Tech Altum"user.location; // return "Noida"user.year; // return 2012user.getAge(); // return 7Its better to use JavaScript Objects to declare properties and methods instead of functions. See example
var user = {
name: 'user',year: 2012,location: 'Noida',};