Functions
Functions
Quite often we need to perform a similar action in many places of the script.
For example, we need to show a message when a visitor logs in, logs out and maybe somewhere else.
Functions are the main “building blocks” of the program. We’ve already seen examples of built-in
functions, like alert(message), prompt(message, default) and
confirm(question). But we can create functions of our own as well.
>function is a named block; it consists group of statements
>function is used to perform specific task/operation
adv:
> Reusable means they allow the code to be called many times without
repetition.
> reduce length of code
> Easy maintenance code (readability, easy debugging, modification of
code, ...)
Function Declaration
To create a function, we can use a function declaration.
The function keyword goes first, then goes the name of the function, then a list of parameters between the
parentheses (comma-separated, empty in the example above) and finally the code of the function, also named “the
function body”, between curly braces.
function name(parameters) {
...body...
}
calling Syn:
fun-name()
fun-name(arg1, arg2,...)
function showMessage() {
alert( 'Hello everyone!' );
}
showMessage();
showMessage();
The call showMessage() executes the code of the function. Here we will see the message two times.
This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.
Local variables
A variable declared inside a function is only visible inside that function.
For example:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
function showMessage()
{
userName = "Kumar"; //changed the outer variable
showMessage();
function showMessage() {
let userName = "Kumar"; // declare a local variable
Parameters
We can pass arbitrary data to functions using parameters (also called function arguments).
Note: while declaring parameters don’t use let, const and var keywords.
Syn:
for Example:
Here’s one more example: we have a variable from and pass it to the function. Please note: the function
changes from, but the change is not seen outside, because a function always gets a copy of the value:
showMessage(from, "Hello");
Default values
function fun-name(param=value, param=value, param=value) { }
function fun-name(param, param=value, param=value) { }
function fun-name(param, param, param=value) { }
function fun-name(param=value, param, param) { } X
function fun-name(param=value, param=value, param) { } X
function fun-name(param, param=value, param) { } X
For instance, the aforementioned function showMessage(from, text) can be called with a single
argument:
showMessage("Siva");
That’s not an error. Such a call would output "Siva: 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 =:
In the example above, anotherFunction() is called every time showMessage() is called without
the text parameter.
function sum(a, b) {
return a + b;
}
function checkAge(age) {
if (age >= 18) {
return true;
} else {
return confirm('Do you have permission from your parents?');
}
}
if ( checkAge(age) ) {
alert( 'Access granted' );
} else {
alert( 'Access denied' );
}
It is possible to use return without a value. That causes the function to exit immediately.
For example:
function showMovie(age) {
if ( !checkAge(age) ) {
return;
}
return
(some + long + expression + or + whatever * f(a) + f(b))
That doesn’t work, because JavaScript assumes a semicolon after return. That’ll work the same as:
return;
(some + long + expression + or + whatever * f(a) + f(b))
So, it effectively becomes an empty return.
If we want the returned expression to wrap across multiple lines, we should start it at the same line as return. Or at
least put the opening parentheses there as follows:
return (
some + long + expression
+ or +
whatever * f(a) + f(b)
)
And it will work just as we expect it to.
Naming a function
Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what
the function does, so that someone reading the code gets an indication of what the function does.
It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There must be an
agreement within the team on the meaning of the prefixes.
For instance, functions that start with "show" usually show something.
Function starting with…
getAge – would be bad if it shows an alert with the age (should only get).
createForm – would be bad if it modifies the document, adding a form to it (should only create it and return).
checkPermission – would be bad if it displays the access granted/denied message (should
only perform the check and return the result).
These examples assume common meanings of prefixes. You and your team are free to agree on other meanings, but
usually they’re not much different. In any case, you should have a firm understanding of what a prefix means, what a
prefixed function can and cannot do. All same-prefixed functions should obey the rules. And the team should share the
knowledge.
For example, the jQuery framework defines a function with $. The Lodash library has its core function named _.
These are exceptions. Generally functions names should be concise and descriptive.
Functions Comments
Functions should be short and do exactly one thing. If that thing is big, maybe it’s worth it to split the function into a few
smaller functions. Sometimes following this rule may not be that easy, but it’s definitely a good thing.
A separate function is not only easier to test and debug – its very existence is a great comment!
For instance, compare the two functions showPrimes(n) below. Each one outputs prime numbers up to n.
The first variant uses a label:
function showPrimes(n) {
nextPrime: for (let i = 2; i < n; i++) {
alert( i ); // a prime
}
}
The second variant uses an additional function isPrime(n) to test for primarily:
function showPrimes(n) {
alert(i); // a prime
}
}
function isPrime(n) {
for (let i = 2; i < n; i++) {
if ( n % i == 0) return false;
}
return true;
}
The second variant is easier to understand, isn’t it? Instead of the code piece we see a name of the action
(isPrime). Sometimes people refer to such code as self-describing.
So, functions can be created even if we don’t intend to reuse them. They structure the code and make it readable.
Summary
A function declaration looks like this: