- JavaScript Anonymous Functions
- Anonymous Functions Syntax
- Example 1: Anonymous Functions in JavaScript
- Example 2: Anonymous Functions with arguments in JavaScript
- Example 3: Using anonymous functions as arguments of other functions
- Example 4: Immediate execution of a function
- Example 5: Arrow functions
- JavaScript Anonymous Functions
- Introduction to JavaScript anonymous functions
- Using anonymous functions as arguments
- Immediately invoked function execution
- Arrow functions
- Summary
- Анонимные функции в JavaScript
- Самовызывающаяся функция
- Анонимные функции в качестве параметров
- Итого
JavaScript Anonymous Functions
An anonymous function is a type of function that has no name. In simple terms, we can call it a function without a name.
Anonymous functions are not accessible after the initial creation it can only be accessed by a variable stored as a function value.
An anonymous function can contain multiple arguments, but it can have only one expression.
Anonymous Functions Syntax
Like any other standard function, an anonymous function can accept input parameters and return output.
Example 1: Anonymous Functions in JavaScript
The following example is the demonstration of a simple anonymous function in JS.
The function does not have any name associated with it, and since we need to call this anonymous function later, we need to assign this to a variable to call it later.
We can call the anonymous function by invoking the variable text() as shown below.
let text = function () < console.log('Hello World'); >; text();
Example 2: Anonymous Functions with arguments in JavaScript
In this example, let’s take a look at how to pass arguments to the anonymous function.
let printName = function (name) < console.log('Hello ',name); >; printName('Chandler Bing');
Example 3: Using anonymous functions as arguments of other functions
We can pass an anonymous function to another function as its argument as JavaScript supports higher-order functions. Let us take a look at a simple use case where we achieve this functionality.
setTimeout(function () < console.log('Welcome to JavaScript world') >, 1000);
Welcome to JavaScript world
We pass an anonymous function as an argument to the setTimeout() method in the above code.
The setTimeout() method will execute the anonymous function after a timeout of 1 second.
Example 4: Immediate execution of a function
If you want to invoke and execute a function immediately after its declaration, creating an anonymous function is the best way. Let’s take a look at the example of how we can achieve this functionality.
Welcome to JavaScript world
Suppose you want to execute the anonymous function immediately, you need to wrap the entire function using parenthesis. Also, add the trailing parenthesis at the end to call the function as shown in the above code.
Sometimes, you need to pass the argument to the function and execute it immediately. Below is an example of passing an argument and executing the anonymous function immediately.
(function () < console.log('Hello ' + fname + lname) >)(fname = "Chandler ", lname = "Bing");
Example 5: Arrow functions
ES6 has introduced an arrow function that provides a shorthand expression to declare an anonymous function.
If you look at the below example, we have eliminated the function keyword and used an arrow to shorthand the entire function.
let text = () => console.log('Hello World');
JavaScript Anonymous Functions
Summary: in this tutorial, you will learn about JavaScript anonymous functions.
Introduction to JavaScript anonymous functions
An anonymous function is a function without a name. The following shows how to define an anonymous function:
(function ( ) < //. >);
Code language: JavaScript (javascript)
Note that if you don’t place the anonymous function inside the () , you’ll get a syntax error. The () makes the anonymous function an expression that returns a function object.
An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable.
For example, the following shows an anonymous function that displays a message:
let show = function( ) < console.log('Anonymous function'); >; show();
Code language: JavaScript (javascript)
In this example, the anonymous function has no name between the function keyword and parentheses () .
Because we need to call the anonymous function later, we assign the anonymous function to the show variable.
Since the whole assignment of the anonymous function to the show variable makes a valid expression, you don’t need to wrap the anonymous function inside the parentheses () .
Using anonymous functions as arguments
In practice, you often pass anonymous functions as arguments to other functions. For example:
setTimeout(function( ) < console.log('Execute later after 1 second') >, 1000);
Code language: JavaScript (javascript)
In this example, we pass an anonymous function into the setTimeout() function. The setTimeout() function executes this anonymous function one second later.
Note that functions are first-class citizens in JavaScript. Therefore, you can pass a function to another function as an argument.
Immediately invoked function execution
If you want to create a function and execute it immediately after the declaration, you can declare an anonymous function like this:
(function( ) < console.log('IIFE'); >)();
Code language: JavaScript (javascript)
First, define a function expression:
(function ( ) < console.log('Immediately invoked function execution'); >)
Code language: JavaScript (javascript)
This expression returns a function.
Second, call the function by adding the trailing parentheses () :
(function ( ) < console.log('Immediately invoked function execution'); >)();
Code language: JavaScript (javascript)
and sometimes, you may want to pass arguments into it, like this:
let person = < firstName: 'John', lastName: 'Doe' >; (function ( ) < console.log(person.firstName> + ' ' + person.lastName); >)(person);
Code language: JavaScript (javascript)
Arrow functions
ES6 introduced arrow function expressions that provide a shorthand for declaring anonymous functions:
For example, this function:
let show = function ( ) < console.log('Anonymous function'); >;
Code language: JavaScript (javascript)
… can be shortened using the following arrow function:
let show = () => console.log('Anonymous function');
Code language: JavaScript (javascript)
Similarly, the following anonymous function:
let add = function (a, b) < return a + b; >;
Code language: JavaScript (javascript)
… is functionally equivalent to the following arrow function:
let add = (a, b) => a + b;
Code language: JavaScript (javascript)
Summary
- Anonymous functions are functions without names.
- Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.
Анонимные функции в JavaScript
Анонимной в JavaScript называют функцию с которой не связано никакое имя или другими словами у такой функции нет имени. Также можно сказать, что если после ключевого слова function или перед знаком стрелочной функции => не стоит имя — функция анонимная. Однако если такую функцию положить в переменную она уже считается именованной.
Анонимная функция недоступна после первоначального создания, поэтому чаще всего она записывается в переменную и дальше с ней происходит работа. Но есть случаи, когда функция так и остается без уникального идентификатора.
Самовызывающаяся функция
Такая анонимная функция выполнится сразу же, как интерпретатор до неё дойдет. В такой записи, функция заключается в круглые скобки () , а после нее добавляется вызов () .
Также запись может быть сделана в стиле стрелочных функций.
Анонимные функции в качестве параметров
Зачем присваивать функции имя, если ее вызов происходит здесь, сейчас и больше нигде.
В данном примере анонимная функция выступает в качестве аргумента функции setTimeout() , и выведет сообщение через пять секунд после загрузки страницы.
Еще один пример, но уже не с кастомной функцией.
function importantQuestion(question, yes, no) < if (confirm(question)) yes() else no(); >importantQuestion( "Вы хотите изучать JavaScript?", function() < alert("Не опускайте руки и у вас все получиться!"); >, function() < alert("Отличная новость! Чем меньше у меня конкурентов, тем выше моя зарплата."); >);
Итого
1. Анонимные функции становятся доступны, только после того, как интерпретатор дойдет до них, таким образом их вызов возможен только после записи функции в коде.
2. Анонимные функции короче и отлично подходят в тех случаях, когда на них не нужно ссылаться в коде.
3. Анонимные функции могут вызывать сами себя.
4. Анонимные функции могут выступать в качестве параметров в других функциях.
Skypro — научим с нуля