Function Declaration and Function Expression

Lecture




  1. Function Declaration
    1. Creation time Function Declaration
  2. Function Expression declaration
  3. Function with a call "on site"
    1. Why braces around the function?
  4. Total

In this section, we will introduce important features of functions in JavaScript, as well as three ways to declare a function.

Function Declaration

The declaration of the function, which we talked about all the time before, is called the specification of the language Function Declaration .

There is no settled Russian translation, such syntax is also called “standard” or “normal” function declaration. A bit further we will look at other options for creating functions.

Let me once again highlight the main meaning of the declaration of the Function Declaration :

When a function is declared, a variable is created with a value function.

In other words, the declaration of function func(параметры) { код } tells the interpreter: “create the variable func , and put a function with the specified parameters and code”.

In this case, func is not really a “function name”. It is absolutely not tied to the function!

This is the name of the variable into which the function will be placed, and from which it can then be deleted, copied to another variable, and as a result, it will not be possible to call it as func :

1 function func() { alert(1); } func() { alert(1); }
2
3 var g = func; // скопировали
4
5 func = null ; // поменяли значение
6
7 g(); // работает, теперь функция в g, а в func ничего нет
8 func(); // вызываем null()? ошибка!

In particular, it is impossible to have a function and a variable with the same name:

1 // Нонсенс!
2 function f() { } // объявить переменную f и записать в нее функцию
3 var f = 5; // объявить переменную f (а она уже объявлена) и присвоить 5
4
5 alert(f); // результат: 5

In the example above, the variable f in the first line gets the value - the function, and in the second - the number 5 . As a result, we get a variable with the value f=5 .

Creation time Function Declaration

Functions declared as Function Declaration are created by the interpreter before executing the code.

Before you execute the first line, the interpreter scans the code, looks for the Function Declaration in it, and processes them.

Therefore, they can be called before the announcement, for example:

1 sayHi( "Вася" );
2
3 function sayHi(name) {
4    alert( "Привет, " + name);
5 }

This code will work because The declaration of declaration function sayHi processed and the function is created before the first line of code is executed.

You cannot conditionally declare a function through Function Declaration

Let's try, depending on the condition, declare the function in different ways:

1 var age = 20;
2
3 if (age >= 18) {
4    function sayHi() { alert( 'Прошу вас!' ); } ); }
5 } else {
6    function sayHi() { alert( 'До 18 нельзя' ); } ); }
7 }
8
9 sayHi();

Which call will work?

To understand this, remember how functions work.

  1. Function Declaration processed before the first line of code.

    The browser scans the code and creates functions from such declarations. In this second ad will overwrite the first.

  2. Further, at runtime, ads are ignored (they have already been processed), as if the code were:
    01 function sayHi() { alert( 'Прошу вас!' ); } ); }
    02 function sayHi() { alert( 'До 18 нельзя' ); } ); }
    03
    04 var age = 20;
    05
    06 if (age >= 18) {
    07    
    08 } else {
    09   
    10 }
    11
    12 sayHi();

As you can see, the if construct does not affect anything here. It was not possible to declare a function differently, depending on the condition.

PS This is the correct specification. At the time of this writing, it is followed by all browsers except Firefox.

Function Expression declaration

There is an alternative syntax for creating functions that solves problems with a “conditional” declaration.

You can create a function and assign it to a variable as the most common value.

This declaration is called Function Expression and looks like this:

1 var f = function (параметры) {
2     // тело функции
3 };

For example:

1 var sayHi = function (person) {
2      alert( "Привет, " + person);
3 };
4
5 sayHi( 'Вася' );

Such a function can be declared in any expression where a normal value is allowed.

For example, the following array declaration is quite possible:

1 var arr = [1, 2, function (a) { alert(a) }, 3, 4];
2
3 var fun = arr[2];
4 fun(1); // 1

Unlike Function Declaration declarations, which are created in advance, before code execution, Function Expression declarations create a function when execution reaches them.

Therefore, they can be used only after the announcement.

1 sayHi(); // <-- работать не будет, функции еще нет
2
3 var sayHi = function () { alert(1) };

... And so it will be:

1 var sayHi = function () { alert(1) };
2
3 sayHi(); // 1

Thanks to this property, Function Expression can (and even should) be used for conditional function declaration:

01 var age = prompt( 'Сколько вам лет?' );
02 var sayHi;
03
04 if (age >= 18) {
05    sayHi = function () { alert( 'Вход разрешен' ); } ); }
06 } else {
07    sayHi = function () { alert( 'Извините, вы слишком молоды' ); } ); }
08 }
09
10 sayHi(); // запустит ту функцию, которая присвоена в if

Function with a call "on site"

Imagine for a moment that we have created a script that does something deliciously stunning with a page. To do this, he, of course, declares his temporary variables and functions.

Our script is so wonderful that we want to give it to other people.

In this case, we would like anyone to insert the script on the page, and the temporary variables and functions of the script do not conflict with those used on it. For example, our script sets the variables a, b , and if they are already used on the page, there will be a conflict.

To avoid it, our script needs its own separate scope in which it will work.

To do this, use the function with a call "on the spot." Such a function is declared - and immediately called, like this:

1 ( function () {
2
3    var a = 1 , b = 2; // переменные для нашего скрипта
4
5    // код скрипта
6
7 })();

Now the internal variables of the script have become local. Even if the variable a is declared elsewhere on the page, there will be no problems. Our script now has its own, isolated scope.

This practice is widely used in JavaScript libraries so that temporary variables and functions that are used during initialization do not conflict with external code.

A function that is declared this way, and immediately called, has no name. It is not saved anywhere, and therefore cannot be called a second time. But in this case it is not necessary, because the task of such a wrapper function is to create a separate scope for the script, which it did.

Why braces around the function?

In the examples above, there are brackets around function() {...} . If you write without them - this code will cause an error:

1 function () {
2   // syntax error
3 }();

This error will occur because the browser, seeing the function keyword in the main code flow, will try to read the Function Declaration , and there is not even a name here.

However, even if you put the name, it will not work either:

1 function work() {
2    // ...
3 }(); // syntax error

The fact is that "on the spot" it is allowed to call only Function Expression .

The general rule is:

  • If the browser sees function in the main flow of code, it considers that it is a Function Declaration .
  • If function goes as part of a more complex expression, then it assumes that it is a Function Expression .

For this, we need brackets - to show that we have Function Expression , which, according to JavaScript rules, can be called "on the spot".

You can show it in another way, for example, by putting an operator before a function:

1 + function () {
2    alert( 'Вызов на месте' );
3 }();
4
5 ! function () {
6    alert( 'Так тоже будет работать' );
7 }();

The main thing is for the interpreter to understand that this is Function Expression , then it will allow to call the function "in place".

The brackets are not needed if this is Function Expression , for example in such a call:

1 // функция объявлена и тут же вызвана
2 var res = function (a,b) { return a+b }(2,2);
3 alert(res); // 4

The function here is created as part of an assignment expression, therefore it is a Function Expression and can be called "in place". At the same time, since the function itself is not saved anywhere, it will disappear when it is executed, only its result will remain.

When calling "on the spot" it is better to put brackets for Expression

Technically, if a function is already defined as Function Expression , then it can be called "in place" without brackets:

var result = function (a,b) {
   return a*b;
}(2,3);

But for reasons of style and readability of the brackets around function it is recommended to put :

var result = ( function (a,b) {
   return a*b;
})(2,3);

Then it is immediately obvious that the function itself is not recorded in result ( result = function... ), but the “on-site call” is in progress. When reading this code, fewer errors.

Total

Functions in JavaScript are values. They can be assigned, transmitted, created anywhere in the code.

  • If the function is declared in the main code flow , then it is a Function Declaration .
  • If the function is created as part of an expression, then it is a Function Expression .

There are the following differences between these two main ways of creating functions:

Function Declaration Function Expression
Time of creation Before executing the first line of code. When control reaches the line with the function.
You can call before the announcement Да (because it is created in advance) Нет
You can declare in if Нет (because it is created in advance) Да
You can call "on the spot" Нет (limiting javascript syntax) Да

As a general tip, prefer the Function Declaration .

Compare readability:

1 // Function Expression
2 var f = function () { ... }
3
4 // Function Declaration
5 function f() { ... }

Function Declaration shorter and better read. Extra bonus - such functions can be called before they are declared.

Use Function Expression only where you need it. For example, to declare a function depending on conditions.

created: 2014-10-07
updated: 2021-03-13
132500



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone