Skip to main content




Very often we need to perform a similar action in many places in the script. For example, we must show an attractive message when a visitor starts session, log out and maybe somewhere else.

Functions are the main "building blocks" of the program. They allow the code to be called many times without repetition.

We have already seen examples of built-in functions, such as alert (message), prompt (message, default) and confirm (question). But we can also create our own functions.

Declaration of functions

To create a function we can use a function declaration.

Does it look like this:

function showMessage () {alert ('Hello everyone!'); }

The key word function comes first, then the name of the function, then a list of parameters between the parentheses (empty in the example above) and finally the code of the function, also called "the body of the function", enclosed in braces.

Our new function can be called by name: showMessage ().

For example:

function showMessage {alert ('Hello everyone!'); } showMessage (); showMessage ();

The call showMessage () executes the function code. Here we will see the message twice.

This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.

If we ever need to change the message or the way it is displayed, simply modify the code in one place: the function that generates it.

Local variables

A variable declared within a function is only visible within that function.

For example:

function showMessage () {let message = "Hi, I'm JavaScript!"; // local variable alert (message); } showMessage (); // Hello, I am JavaScript! alert (message); // <- Error! The variable is local within the function

External variables

A function can also access an external variable, for example:

let username = 'Maria'; function showMessage () {let message = 'Hello,' + username; alert (message); } showMessage (); // Hello, Maria

The function has full access to the outer variable. You can modify it too.

For example:

let username = 'Maria'; function showMessage () {username = "Bob"; // (1) changed the outer variable let message = 'Hello,' + username; alert (message); } alert (username); // Maria before the function call showMessage (); alert (username); // Bob, the value was modified by the function

The external variable is only used if there is no local one. So an occasional modification can happen if we forget let.

If a variable with the same name is declared inside the function, it shades the outer one. For example, in the code below, the function uses the local username. The exterior is ignored:

let username = 'Maria'; function showMessage () {let username = "Bob"; // declare a local variable let message = 'Hello,' + username; // Bob alert (message); } // the function will create and use its own variable username displayMessage (); alert (username); // Maria, no changes, the function did not access the external variable

Global variables

Variables declared outside of any function, such as external Username in the code above, they are called globals.

Global variables are visible from any function (unless shaded by locals).

Usually a function declares all the variables specific to its task. Global variables only store data at the project level, so when it is important that these variables are accessible from anywhere. Modern code has few or no global globes. Most of the variables reside in their functions.

Parameters

We can pass arbitrary data to functions using parameters (also called function arguments).

In the following example, the function has two parameters: since and text.

function showMessage (from, text) {// arguments: from, text alert (from + ':' + text); } showMessage ('Ann', 'Hello!'); // Ann: Hi! (*) showMessage ('Ann', "What's wrong?"); // Ann: What's up? (**)

When the function is called on lines (*) and (**), the given values are copied to the local variables since and text. Then the function uses them.

Here's one more example: we have a variable since and we pass it on to the function. Please note: function changes since, but the change is not seen outside, because a function always gets a copy of the value:

function showMessage (from, text) {from = '*' + from + '*'; // make "from" look better alert (from + ':' + text); } let from = "Ann"; showMessage (from, "Hello"); // * Ann *: Hello // the value of "from" is the same, the function modified a local copy alert (from); // Ann

Predetermined values

If no parameter is provided, then its value becomes undefined.

For example, the above-mentioned function showMessage (from, text) can be called with a single argument:

showMessage ("Ann");

That is not a mistake. Such a call would go out "Ann: undefined". There is no text so it's supposed to text === undefined.

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

function showMessage (from, text = "no text") {alert (from + ":" + text); } showMessage ("Ann"); // Ann: no text Now if the text parameter is not passed, you will get the value "no text"

There is a string "no text" here, but it can be a more complex expression, which is only evaluated and assigned if the parameter is missing. Therefore, this is also possible:

function showMessage (from, text = otherFunction ()) {// otherFunction () is only executed if no text has been given // its result becomes the value of the text}

Old style default parameters

Older editions of JavaScript did not support default parameters. So there are alternative ways to support them, which you can find mostly in old scripts.

For example, an explicit check to be undefined:

function showMessage (from, text) {if (text === undefined) {text = 'no text'; } alert (from + ":" + text); } ... or

The operator ||:

function showMessage (from, text) {// if the text is false, then the text gets the "default" value text = text || 'no text'; ...}

Returning a value

A function can return a value to the calling code as a result.

The simplest example would be a function that adds two values:

function sum (a, b) {return a + b; } let result = sum (1, 2); alert (result); // 3

Directive return it can be anywhere in the function. When execution reaches it, the function stops and the value is returned to the calling code (assigned to result above).

There may be many appearances in a single function. For example:

function checkAge (age) {if (age> 18) {return true; } else {return confirm ('Do you have parental permission?'); }} let age = prompt ('How old are you?', 18); if (checkAge (age)) {alert ('Access allowed'); } else {alert ('Access denied'); }

It is possible to use return without a value. That causes the function to exit immediately.

For example:

function viewMovie (age) {if (! viewMovie (age)) {return; } alert ("Showing you the movie"); // (*) // ...}

In the above code, if verify Age (age) It is returned false, watch movie will not proceed to alert.

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

If a function does not return a value, it is the same as if it returns undefined:

function doNothing () {/ * empty * /}
alert (doNothing () === undefined); // true

return empty is also the same as return undefined:

function doNothing () {return; } alert (doNothing () === undefined); // true

Never add a new line between return and the value
For a long return expression, it might be tempting to put it on a separate line, like this:

return (some + long + expression + or + whatever + is * f (a) + f (b))

That doesn't work, because JavaScript assumes a semicolon after return. That will work the same as:

return; (some + long + expression + or + whatever + is * f (a) + f (b))

Therefore, it effectively becomes an empty return. We should put the value on the same line instead.

R Marketing Digital