You get a bonus - 1 coin for daily activity. Now you have 1 coin

Javascript functions

Lecture




  1. Announcement
  2. Local variables
  3. External variables
  4. Options
  5. Default Arguments
  6. Feature Declaration Style
  7. Return value
  8. Name selection
  9. Total

Often we need to repeat the same action in many parts of the program.

For example, it is necessary to display a message when greeting a visitor, when a visitor leaves the site, somewhere else.

In order not to repeat the same code in many places, functions are invented. Functions are the basic building blocks of the program.

Examples of built-in functions you have already seen are alert(message) , prompt(message, default) and confirm(question) . But you can create your own.

Announcement

Example function declaration:

function showMessage() {
   alert( 'Привет всем присутствующим!' );
}

First comes the function keyword, after it is the name of the function , then the list of parameters in brackets (in the example above it is empty) and the function body — the code that is executed when it is called.

The declared function is available by name, for example:

1 function showMessage() {
2    alert( 'Привет всем присутствующим!' );
3 }
4
5 showMessage();
6 showMessage();

This code will display the message twice. The main purpose of creating functions is already visible here : getting rid of code duplication .

If you need to change the message or the method of its output, it is enough to change it in one place: in the function that outputs it.

Local variables

The function may contain local variables declared via var . Such variables are visible only inside the function:

1 function showMessage() {
2    var message = 'Привет, я - Вася!' ; // локальная переменная
3
4    alert(message);
5 }
6
7 showMessage(); // 'Привет, я - Вася!'
8
9 alert(message); // <-- будет ошибка, т.к. переменная видна только внутри

if/else , switch , for , while , do..while blocks do not affect the scope of variables.

When a variable is declared in such blocks, it will still be visible in the entire function.

For example:

1 function count() {
2    for ( var i=0; i<3; i++) {
3      var j = i * 2;
4    }
5
6    alert(i); // i=3, на этом значении цикл остановился
7    alert(j); // j=4, последнее значение, на котором цикл сработал, было i=2
8 }

It doesn't matter where exactly in the function and how many times the variable is declared. Any announcement is triggered once and applies to the entire function.

Variable declarations in the example above can be moved up, this will not affect anything:

1 function count() {
2    var i, j; // передвинули объявления var в начало
3    for (i=0; i<3; i++) {
4      j = i * 2;
5    }
6
7    alert(i); // i=3
8    alert(j); // j=4
9 }

External variables

The function may refer to an external variable, for example:

1 var userName = 'Вася' ;
2
3 function showMessage() {
4    var message = 'Привет, я ' + userName ;
5    alert(message);
6 }
7
8 showMessage(); // Привет, я Вася

Access is possible not only for reading, but also for writing. In this case, since the variable is external, the changes will be visible outside the function:

01 var userName = 'Вася' ;
02
03 function showMessage() {
04    userName = 'Петя' ; // (1) присвоение во внешнюю переменную
05    var message = 'Привет, я ' + userName ;
06    alert(message);
07 }
08
09 showMessage();
10
11 alert(userName); // Петя, значение внешней переменной изменено функцией

Of course, if inside a function, in line (1) , its own local variable var userName were declared, then all calls would use it, and the external variable would remain unchanged.

Variables declared at the level of the entire script are called “global variables” .

Make global only those variables that really have a common meaning for your project.

Let each function work “in its own sandbox”.

Warning: implicit declaration of global variables!

In the old JavaScript standard, there was the possibility of implicitly declaring variables by assigning a value.

For example:

1 function showMessage() {
2    message = 'Привет' ; // без var!
3 }
4
5 showMessage();
6
7 alert(message); // Привет

In the code above, the message variable is not declared anywhere, but is immediately assigned. Most likely, the programmer simply forgot to install var .

In the modern JavaScript standard, such an assignment is prohibited, and in the old one, which works in browsers by default, the variable will be created automatically, and in the example above it is created not in the function, but at the level of the entire script.

Avoid this.

Here, the danger is not even in the automatic creation of a variable, but in the fact that global variables should be used when “common script” parameters are really needed.

Lost var in one place, then another - as a result, two functions unexpectedly changed the same global variable for each other.

In the future, when we get better acquainted with the basics of JavaScript, in the chapter Closures, functions from the inside, we will take a closer look at the internal mechanisms of variables and functions.

Options

When you call a function, you can transfer data to it that it uses at its discretion.

For example, this code displays two messages:

1 function showMessage( from, text ) { // параметры from, text
2   
3    from = "** " + from + " **" ; // здесь может быть сложный код оформления
4    alert(from + '\n\n' + text);
5 }
6
7 showMessage( 'Маша' , 'Привет!' );
8 showMessage( 'Маша' , 'Как дела?' );

Parameters are copied to local function variables .

In the example below, the change from in the string (1) will not affect the value of the external variable from (2) , since The copy of the value was changed:

1 function showMessage(from, text) {
2    from = '**' + from + '**' ; // (1), красиво оформили from
3    alert(from + '\n\n' + text);
4 }
5
6 var from = 'Маша' , msg = 'Привет!' ; // (2)
7
8 showMessage(from, msg); // значения будут скопированы в параметры
9 alert(from); // перезапись в строке (1) не повлияет на внешнюю переменную

Default Arguments

The function can be called with any number of arguments.

For example, the showMessage(from, text) message display function showMessage(from, text) can be called with one argument:

showMessage( "Маша" );

If the parameter is not passed during the call, it is considered to be equal to undefined .

Such a situation can be caught and assigned the value “by default”:

01 function showMessage(from, text) {
02    if (text === undefined ) {
03      text = 'текст не передан' ;
04    }
05
06    alert(from + ": " + text);
07 }
08
09 showMessage( "Маша" , "Привет!" ); // Маша: Привет!
10 showMessage( "Маша" ); // Маша: текст не передан

When declaring a function, optional arguments are usually placed at the end of the list.

To specify the value of "default", that is, one that is used if the argument is not specified, two methods are used:

  1. You can check whether the argument is undefined , and if so, write the default value in it. This method is demonstrated in the example above.
  2. Use operator || :

    1 function showMessage(from, text) {
    2    text = text || 'текст не передан' ;
    3
    4    ...
    5 }

    The second method assumes that the argument is absent if an empty string is passed, 0 , or in general any value that is false in the boolean form.

If there are more arguments than you need, for example showMessage("Маша", "привет", 1, 2, 3) , then there will be no error. But since no parameters are provided for “extra” arguments, they can only be accessed through the special arguments object, which we will look at in the Pseudo-array of arguments chapter.

Feature Declaration Style

In the function declaration there are rules for the arrangement of spaces. They are marked with arrows:

  Javascript functions

Of course, you can put spaces in a different way, but these rules are used in most JavaScript frameworks.

Return value

A function can return a result that will be passed to the code that called it.

For example, create the calcD function, which will return the discriminant of a quadratic equation using the formula b 2 - 4ac :

1 function calcD(a, b, c) {
2     return b*b - 4*a*c;
3 }
4
5 var test = calcD(-4, 2, 1);
6 alert(test); // 20

To return a value, use the return directive.

It can be anywhere in the function. As soon as control reaches it, the function ends and the value is transferred back.

There can be several return calls, for example:

01 function checkAge(age) {
02    if (age > 18) {
03      return true ;
04    } else {
05      return confirm( 'Родители разрешили?' );
06    }
07 }
08
09 var age = prompt( 'Ваш возраст?' );
10
11 if (checkAge(age)) {
12    alert( 'Доступ разрешен' );
13 } else {
14    alert( 'В доступе отказано' );
15 }

Importance: 4

The following function returns true if the age parameter is greater than 18 .
Otherwise, it asks a question by calling confirm and returns its result.

1 function checkAge(age) {
2    if (age > 18) {
3      return true ;
4    } else {
5      // ...
6      return confirm( 'Родители разрешили?' );
7    }
8 }

Will this function work otherwise if you remove the else ?

1 function checkAge(age) {
2    if (age > 18) {
3      return true ;
4    }
5    // ...
6    return confirm( 'Родители разрешили?' );
7 }

Is there at least one difference in the behavior of this option?

Decision

Both options function the same, there is no difference.

[Open task in new window]

Importance: 4

The following function returns true if the age parameter is greater than 18 .
Otherwise, it asks the question to confirm and returns its result.

1 function checkAge(age) {
2    if (age > 18) {
3      return true ;
4    } else {
5      return confirm( 'Родители разрешили?' );
6    }
7 }

Rewrite the function to do the same, but without if , in one line.
Make two choices for the checkAge function:

  1. Using the operator '?'
  2. Using the operator ||
Decision

Using the operator '?' :

function checkAge(age) {
   return (age > 18) ? true : confirm( 'Родители разрешили?' );
}

Using the operator || (shortest option):

function checkAge(age) {
   return (age > 18) || confirm( (age > 18) || confirm( 'Родители разрешили?' );
}

[Open task in new window]

The return directive can also be used without a value to terminate and exit a function.

For example:

1 function showMovie(age) {
2    if (!checkAge(age)) {
3      return ;
4    }
5   
6    alert( "Фильм не для всех" ); // (*)
7    // ...
8 }

In the code above, if the if worked, then the string (*) and all the code under it will never be executed, since return completes the execution of the function.

Function value without return and with empty return

In the case when the function did not return a value or the return was without arguments, it is considered that it returned undefined :

1 function doNothing() { /* пусто */ }
2
3 alert( doNothing() ); // undefined

Please note there is no error. Just returning undefined .

Another example, this time with return with no argument:

1 function doNothing() {
2    return ;
3 }
4
5 alert( doNothing() === undefined ); // true

Name selection

The function name follows the same rules as the variable name. The main difference is that it should be a verb, since function is action.

As a rule, verb prefixes are used to indicate the general nature of the action, followed by clarification.

Functions that start with "show" - show something:

showMessage(..) // префикс show, "показать" сообщение

Functions beginning with "get" - receive, etc.:

1 getAge(..) // get, "получает" возраст
2 calcD(..) // calc, "вычисляет" дискриминант
3 createForm(..) // create, "создает" форму
4 checkPermission(..) // check, "проверяет" разрешение, возвращает true/false

This is very convenient, because looking at a function, we’re about what it does, even if the function was written by a completely different person, and in some cases, and what kind of value it returns.

One function - one action.

A function must do only what is explicitly implied by its name. And it should be one action.

If it is complex and implies sub-actions - maybe it makes sense to isolate them into separate functions? Often it makes sense to better structure the code.

... But the most important thing is that there should be nothing in the function except the action itself and the sub-actions that are inseparably connected with it.

For example, the data validation function (say, "validate" ) should not show an error message. Her action is to check.

Ultrashort function names

Names of functions that are used very often sometimes make it ultrashort.

For example, in the jQuery framework there is a $ function, in the Prototype framework the $$ function, and in the Underscore library the function with the name of a single underscore symbol _ very actively used.

Total

Function declaration:

function имя(параметры, через, запятую) {
   код функции
}

  • The values ​​passed are copied to the function parameters and become local variables.
  • Function parameters are its local variables.
  • You can declare new local variables with var .
  • The value is returned by the operator return ...
  • Calling return immediately terminates the function.
  • If return; called without a value, or the function terminated without return , then its result is equal to undefined .

When accessing an undeclared variable, the function will search for an external variable with this name.

If possible, it is recommended to use local variables and parameters:

  • This makes the overall execution flow obvious - what is passed to the function and what is the result.
  • This prevents possible access conflicts when two functions, possibly written at different times or by different people, unexpectedly use the same external variable.

Function Naming:

  • The name of the function should be clear and clearly reflect what it does. After seeing her call in the code, you should immediately understand what she is doing.
  • A function is an action, so verbs are usually used for function names.

Functions are the basic building blocks of scripts. We will repeatedly return to them and study more and more deeply.

Importance: 1

“Hello World” task for functions

Write the function min(a,b) , which returns the smaller of the numbers a,b .

Sample Calls:

min(2, 5) == 2
min(3, -1) == -1
min(1, 1) == 1

Decision
[Open task in new window]

Importance: 4

Write the function pow(x,n) , which returns x to the power n . In other words, multiplies x by itself n times and returns the result.

pow(3, 2) = 3*3 = 9
pow(3, 3) = 3*3*3 = 27
pow(1, 100) = 1*1*...*1 = 1

Create a page that requests x and n , and then displays the result of pow(x,n) .

Demo: tutorial / intro / pow.html

PS In this task, the function must support only natural values ​​of n , i.e. integers from 1 and up.

Decision

Solution: tutorial / intro / pow.html

created: 2014-10-07
updated: 2024-11-14
398



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