Which functions are usually used in JavaScript

JavaScript: functions

Here is a JavaScript documentation by molily. At the moment it is still patchy, but it is gradually growing. Comments and feedback are welcome by email.

To the table of contents


You can use functions to write down flexible partial programs that you can call up repeatedly. Functions are a simple means of structuring a JavaScript program.

In JavaScript functions are more important than in other programming languages ​​and have some special features. JavaScript has aspects of a functional programming language. In JavaScript, functions are not fixed, once defined program units, but rather values ​​themselves that you can work with in the program. You can create new functions at runtime. Functions that are no longer required are deleted.

You can own functions define in different ways. You can create functions as local variables in another function. You can also attach functions to objects. That means storing it as a property of an object. The technical term for this in object-oriented programming is method. And finally, you can also create anonymous (nameless) functions, e.g. to pass them as parameters to another function.

Function declarations

The simplest and most important way to define a function is the so-called (in English function declaration). Their syntax is structured as follows:

function () {}

The Function name must meet the usual requirements for JavaScript identifiers: You can use letters, decimal digits (0-9), the dollar sign ($) and the underscore (_). Numbers must not come first.

The Parameter list between the two round brackets is a comma-separated list of names. The named naming conventions apply to these. You can access the transferred parameters within the function by using the names assigned here.

The is noted between the two curly brackets: This contains the instructions that are to be executed when the function is called.

The following example should clarify the scheme:

function statusMmessage (meldungsTyp, meldungsText) {var ausgabeElement = document.getElementById ('meldungsausgabe'); AusgabeElement.className = message type; outputElement.innerHTML = message text; } statusMessage ('error', 'An error occurred while sending your message.');

The example defines a function with the name. The function expects two parameters with the names and. It searches for an element in the document with the ID. Then it sets its class to the value of the parameter and fills the element with the value of the parameter.

A function is called according to the scheme. The parameter list when called is a comma-separated list of expressions (names or values). Two parameters are transferred to the function in the example, which are noted as string literals.

This results in the function getting the value and the value.

Return value (result)

A function can not only receive values, but also return a value. This value is called or also. The value can be used at the point where the function call is. The function call results the value.

Think of a simple math function:. For x = 5 the function is 25, for x = 6 the function is 36, etc.

In JavaScript, the function could look like this:

function square (x) { return x * x; } window.alert (square (5));

You can use the statement to terminate the function and return a value. Any expression follows the keyword. The statement ends with a semicolon.

In the example, the function is called with parameter 5. The expression returns 25, so the value 25 is returned.

The result 25 is inserted at the point where the function call was. So it will be out.

The function execution can only be executed once, because it terminates the execution immediately and ensures that the execution continues from where the function was called.

However, that does not mean that you cannot use multiple statements in a function. can occur several times, but must be in different logical branches. For example:

function greeting (person) {if (person.nickname) { return 'Welcome' + person.nickname; } else { return 'Hello' + person.first name; }} var person1 = {first name: 'Erika'}; var person2 = {first name: 'Max', nickname: 'cinnamon bun'}; window.alert (greeting (person1)); window.alert (greeting (person2));

The example defines a function that expects an object as a parameter. There is a conditional statement in it. It checks whether the transferred object has a property. If so, it returns a greeting that uses. If not, it returns a greeting using the property.

The function is called twice. Once with the object that has a nickname. Once with the object that does not have a nickname. The case distinction in the function now determines the return value: In the first case, returns are made, in the second case.

The statement terminates the execution of the function as I said. That is, we can also define the function as follows:

function greeting (person) {if (person.nickname) { return 'Welcome' + person.nickname; } return 'Hello' + person.first name; }

You can save yourself the branch. If the condition of the statement is met, the JavaScript interpreter jumps out of the function immediately. This pattern is often used to prematurely end a function. Another example:

function hypotenuse (a, b) {if (a <= 0 || b <= 0) {return 0; } var c = Math.sqrt (a * a + b * b); return c; }

The example calculates the length of the hypotenuse in a right triangle using the Pythagorean theorem. The formula for this is.

If the lengths of the legs and are less than or equal to 0, then a calculation is not possible or would result in an incorrect value. If necessary, the function is terminated prematurely and it returns 0. Only after this check does the actual calculation of the hypotenuse take place.

Function variables

Within functions, you can declare variables whose scope is restricted to the function. The example function above has defined a variable, namely:

function hypotenuse (a, b) {if (a <= 0 || b <= 0) {return 0; } var c = Math.sqrt (a * a + b * b); return c; }

The variable is only available within the function, but its value should be given outside. This is possible with the previously discussed statement.

A detailed explanation of function variables can be found in the chapter on variables.

Function expressions

The function declaration presented combines two tasks: It creates a function and at the same time saves it under a name in the current scope.

The following function declaration saves a function under the name.

function square (x) {return x * x; }

However, it is not always desirable to give a function a name and make it available in the current scope. Sometimes you want to create a function without making it available under a name.

There is therefore another notation for creating functions: Den (English function expression).

Syntactically, a function declaration is one Instruction. A function expression, on the other hand, is a Expression, As the name indicates. Both have different application possibilities. You can write function expressions in more places than a function declaration.

The scheme of a function expression looks like this:

function () {}

A function expression only creates a function, but does not automatically save it under a name. One therefore also speaks of.

The result of the expression is a function object. Like any other value in JavaScript, you can continue to use it as you wish. For example, you can save the created function object in a variable:

var = function () {};

This variable assignment with function expression has the same effect as the classic function declaration. Except for a few special cases, the two spellings are interchangeable.

What are they now advantages of a function expression?

A function that you create with a function expression can be attached directly to an object as a method. In this way you can bring order to your scripts and group related values ​​and functions under one object. An example:

var picture gallery = {play: function () { /* … */ } }; picture gallery.playback ();

In the example above, an object is created using the object literal and stored in the variable. A method named Empty Object is added to the object.

The corresponding function is noted as a function expression. The resulting function object is saved in the property. Finally, the function is called as a method.

The above example could also be solved with a function declaration:

play function () { /* … */ } var picture gallery = {play: play}; picture gallery.playback ();

First a function is created here. It is then saved in the object's property of the same name.

Why does it make more sense to use a function expression here?

First of all, the notation with function expression is more compact. But it is more important that only one name, namely, is used. The notation with function declaration occupies another name,. This is unnecessary and can lead to conflicts if other scripts use the same name.

Function expressions are often used when passing a function to another function. This happens, for example, with advanced event processing.

The variant with a function declaration would look like this:

function init () {window.alert ('Document has finished loading!'); } window.addEventListener ('load', init);

In the example, a function named is created and registered as an event handler for the event on the object. The function is transferred to the addEventListener method as a parameter.

This notation is useful if you need the function again later. Usually this is not the case: you only need the function once to register it as a handler. There is no need to save them under a name.

A function expression can simplify the code. Make a note of the handler function with an expression and pass the generated function directly to:

window.addEventListener ('load', function () {window.alert ('Document has finished loading!'); });

There are other cases where naming and caching a function is unnecessary. There are thus further possible uses for function expressions. We will come back to this in the section on closures.

Variable number of parameters: The arguments array

Functional programming: functions as values

Functions are normal objects with properties and methods

Event handlers and callback functions

Functional programming

Context of a function: the keyword this

See meaning of this

How it is called determines the this context

object.method () vs. var m = object.method (); m ();

Function binding, Function.prototype.bind

Context with and influence