JavaScript Functions

Like every programming language, JavaScript also supports the use of functions. JavaScript functions are the main blocks of code designed to perform a particular task. Functions allow the code to be called many times without repetition.

Function Declaration

We can create functions in JavaScript using a function declaration that looks like this:

w3docs logo Simple function in javascript
function show() { console.log('Welcome to W3Docs!'); } show();

As you see in the example the function keyword goes first, followed by the name of the function, then we put a list of parameters between the parentheses and finally we place the code of the function between curly braces .

Beautified JavaScript:

function name(parameters) {
  //body...
}

We can call our new function by its name: show() which executes the code of the function. As a result, we see the message two times:

w3docs logo Javascript function
function show() { console.log('Welcome to W3Docs!'); } show(); show();

This example shows one of the main purposes of functions: to avoid code duplication. If we want to change the message, we just need to modify the code in the function which outputs it.

Local variables

A variable declared inside a JavaScript function is only visible inside that function. It can only be accessed from within the function.

Example of the local variable:

w3docs logo The local variable in javascript function
function show() { let localVar = "Welcome to W3Docs!"; //it’s a local variable console.log(localVar); } show(); // Welcome to W3Docs! console.log(localVar); // <-- Error! The variable is local to the function

Outer variables

A function can also evaluate an outer variable.

Example of the outer variable:

w3docs logo The outer variable for javascript function
let siteName = 'W3Docs'; function show() { let variable = 'Welcome to ' + siteName; console.log(variable); } show(); // Welcome to W3Docs

We use an outer variable only if there is no local one. If some same-named variable is declared inside the function then outer one is ignored.

Example of the function that uses the local variable:

w3docs logo The local and outer variables for javascript function
let siteName = 'newSite'; // it’s a outer variable function show() { let siteName = "W3Docs"; // it’s a local variable let message = 'Welcome to ' + siteName; console.log(message); //Welcome to W3Docs } // the function created and used its own siteName show(); console.log(siteName); //newSite,the function didn’t access the outer variable
We declare global variables outside of any function, they are visible from any function. Modern code has few or no globals, that is why it is better to minimize the use of global variables.
Modern code has few or no globals, that is why it is better to minimize the use of global variables.

Parameters

We can proceed with random data to functions using parameters. In this example, the function has two parameters: arg1 and arg2:

w3docs logo Javascript function arguments
function show(arg1, arg2) { // arguments: arg1, ag2 console.log(arg1 + ' to ' + arg2); } show('Welcome', 'W3Docs!'); // Welcome to W3Docs! (*)

The function uses (*) when the given values are copied to local variables arg1 and arg2.

In this example we have a variable arg1 and proceed it to the function. Note that the function changes arg1, and the change is not seen outside, as a function always gets a copy of the value:

w3docs logo Javascript function arguments
function sum(arg1, arg2) { arg1 = arg1++; // change "arg1" let sum = arg1 + arg2; console.log(sum); } let arg1 = 2; sum(arg1, 3); // result: 5 console.log(arg1); // 2

The value of "arg1" is the same, the function modified a local copy.

Default values

Parameters of functions default to undefined if a parameter is not defined. But sometimes it might be useful to set a different default value.

w3docs logo Javascript function arguments
function show(arg1, arg2) { // arguments: arg1, ag2 console.log(arg1 + ' to ' + arg2); } show("Welcome", "W3Docs");

For example we can call the aforementioned function show(arg1, arg2) with a single argument:

show("W3Docs"); // undefined to W3Docs

That is not an error. This kind of a call would output "undefined to W3Docs", but as there is no text it is supposed that text === undefined.

If we want to use a “default” in this case, we can specify it after =:

w3docs logo Javascript function default argument
function show(arg1, arg2 = "W3Docs!!") { console.log(arg1 + " to " + arg2); } show("Welcome"); // Welcome to W3Docs!!

So if the text parameter is not passed, it will get the value "W3Docs!!", which is a string in this case, but it can be a more complex expression. That expression is only evaluated and assigned if the parameter is missing and this is also possible:

function show(arg1, arg2 = anyFunction()) {
  //if no text given a anyFunction() only executed
  // its result becomes the value of text

}

A default parameter can be evaluated every time the function is called without the corresponding parameter.

In the presented above example, anyFunction() is called every time show() is called.

Default parameters old-style

Old editions of JavaScript did not assist default parameters, that is why there are alternative ways that you can meet mostly in the old scripts.

For example, a clear check for being undefined:

w3docs logo Javascript function arguments
function show(arg1, arg2) { if (arg2 === undefined) { arg2 = 'text not specified'; } console.log(arg1 + " to " + arg2); } show("Welcome", undefined);

Or the || (OR) operator:

function show(arg1, arg2) {
  arg2 = arg2 || 'text not specified';
  //if the arg2 is false, then the text gets the default value
  ...
}

Returning a value

A function can return a value to the calling code as the result. In this simple example a function multiplies two values:

w3docs logo Javascript function return value
function multiply(a, b) { return a * b; } let result = multiply(2, 3); console.log(result); // 6

We can place the directive return in any place of the function. The function stops when the execution reaches it, and the value is returned to the calling code.

There may be many incidents of return in a single function:

w3docs logo Javascript function return value
function checkNumber(number) { if (number == 10) { return true; } else { return false; } } let number = prompt('Guess the number?', ''); if (checkNumber(number)) { console.log('it’s true'); } else { console.log('it’s false'); }

We can use return directive without a value, what causes the function to exit immediately.

Example of the return without a value:

function showNumber(number) {
  if (!checkNumber(number)) {
    return;
  }
  console.log("Showing the number");
  //...
}

In the presented above code, if checkNumber(number) returns false, showNumber() will not move to the alert.

A function with an empty return directive or without it returns undefined.

When a function does not return a value, it is the same as when it returns undefined and an empty return.

w3docs logo Javascript function value show in console
function doNothing() { /* empty */ } console.log(doNothing() === undefined); // true
Never add a newline between return directive and the value attribute.

For a long expression in return, it might be attractive to put it on a separate line:

return
 (long + expression + or + whatever * f(x) + f(y))

But that does not work, because JavaScript accepts a semicolon after return and that will work the same as:

return;
 (long + expression + or + whatever * f(x))

As you see it effectively becomes an empty return.

When we want the returned expression to wrap across multiple lines, we need to start it at the same line as a return or put the opening parentheses there like this:

return (
  long + expression +
  or +
  whatever * f(x)
)

And it will work like we expect it to.

Naming a function

Functions are actions and their name is generally a verb. The name should be brief, accurate, describing what the function does.

It is a worldwide practice to start a function with a verbal prefix which more or less describes the action.

For example, functions that start with "show" used to show something.

Function starting with…

  • "get…" – return a value,
  • "create…" – create something
  • ,
  • "calc…" – calculate something and so on.

Examples of such names:

showMessage(..)     // shows a message
getNumber(..)          // returns the age (gets it somehow)
calcMultiply(..)         // calculates a multiply and returns the result
createForm(..)      // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false

With the function name, we can understand what kind of work it does and what kind of value it returns.

One function should do exactly what is suggested by its name, no more.

Two independent actions usually do two functions, even if they are usually called together.

Ultrashort function names

Very often used functions sometimes have ultrashort names.

For instance, the jQuery framework defines a function with $. The Lodash library has its core function named _.

But generally functions names should be brief and descriptive.

Functions == Comments

As we mentioned above, functions should be short and do exactly one thing. But when that thing is big, maybe it is worth it to break the function into a few smaller functions.

The reason is that the separate function is not only easier to test and debug but also it is very existence is a great comment.

Let’s compare the two functions showEven(num) where each one outputs even numbers up to n.

The first example uses a label:

w3docs logo Javascript function show value in console
function printEven(num) { for (let i = 1; i < num; i++) { if (i % 2 === 0) { console.log(i); } } } printEven(10);

The second example uses an additional function isEven(n) to test for primality:

w3docs logo Javascript function return value
function showEven(n) { for (let i = 2; i < n; i++) { if (!isEven(i)) continue; console.log(i); // a odd } } function isEven(num) { if (num % 2 === 0) { return true; } else { return false; } } showEven(10);

As you see it is easier to understand the second variant. We see the name of the action (isEven) instead of the code piece.


Do you find this helpful?