There are many ways to do the same thing in JavaScript. There is both good and bad in this. For a beginner, this is definitely bad, since he will not only have to study more information, but there will also be more places for potential mistakes to be made. This can happen when defining functions.

There are many different ways to declare a function:

Function A() (); // function declaration var B = function () (); //function expression var C = (function () ()); // function expression with grouping operator var D = function foo () (); // named function expression var E = (function () ())(); // self-invoking function expression var F = new Function(); // function constructor var G = new function() (); // degenerate case: object constructor
It’s hard not to get confused in such abundance, isn’t it? As a rule, in everyday life we use no more than three different types of function declarations, and it works great. However, if you dig deeper, it may turn out that most of us do not even suspect how many mysteries and pitfalls the operation of declaring a function contains.

According to the ECMA documentation, the syntax for defining a function is as follows:
Function Declaration: function Identifier (Parameters) (Function Body) Function Expression: function Identifier (optional) (Parameters) (Function Body)
Although these definitions look quite similar, there is a big difference between a function declaration and a functional expression. Function declaration ( Function Declaration) is created before any code is executed, while a function expression ( Function Expression) will be created only when the interpreter reaches this line of code.

A function expression is a declaration of a function in the context of an expression.

Let's look at some examples of function expressions:

Assignment operator
var a = function()();
This is a classic example of specifying a functional expression through assignment. The assignment operator expects an expression on the right, which is why the function becomes part of the expression.
With a little imagination, you can come up with the following examples:

Var a = function() ( return 1; )() + 12; // 13 var b = function() ( return 1; ) + ""; // function ()(return 1) var c = function() ( return 1; ) + "" - 1; //NaN

Grouping operator
By declaring a function, we cannot execute it immediately, however, by wrapping the function declaration in parentheses- it becomes possible. The grouping operator is expressed in parentheses, and in this case it turns a function declaration into a function expression.

Function foo() ( return 1; ) // undefined function foo() ( return 1; )(); // Uncaught SyntaxError: Expected () to start arrow function, but got ")" instead of "=>" (function foo() ( return 1; )()) // 1 (function foo() ( return 1; ) )() // 1
There is no fundamental difference between the third and fourth options, since in the first case we execute an expression that defines and immediately executes a function, and in the second case we execute an expression that defines a function that will then be executed.

Comma operator
The comma operator evaluates the value of each of its operands (from left to right) and returns the value of the last operand.

0, function() ( return 1; )(); // 1

Operators (+, -, !, ~, void)
+function() ( return false; )(); // 0 -function() ( return false; )(); // -0 !function() ( return false; )(); // true ~function() ( return false; )(); // -1 void function() ( return false; )(); //undefined
Combined operators:
!-function () ( return false; )(); // true var c = 5 * (2 - function () (return 1)()) // 5 var c = 5 * 2 - -~function () (return 1)() // 8

The difference between named function expressions and unnamed ones:

Often, the name assigned to a function expression is redundant in the context of the rest of the code, unless the function must be accessed from within the function itself. The scope of a function expression name is limited solely to the function itself.

Var f = function getFactorial (n) ( return n ? n * getFactorial(n - 1) : 1; ); f(5); // 120

Important:
Remember, you're writing code for people, so try to avoid writing ninja-style code. The knowledge provided in the article is useful in order to understand internal structure language and not get confused if you suddenly come across such expressions in one of your projects or at an interview.

Expressions in JavaScript are combinations operands And operators.

Operations in expressions are executed sequentially in accordance with the priority value (the higher the priority value, the higher it is). The returned result is not always of the same type as the type of data being processed. For example, comparison operations involve operands of different types, but the return result will always be a boolean type.

Rice. 1. Expression structure in JavaScript

Operands is the data processed by the JavaScript script. The operands can be either simple or complex data types, as well as other expressions.

Operators are language symbols that perform various operations with data. Operators can be written using punctuation characters or keywords.

Depending on the number of operands, the following types of operators are distinguished:
unary— one operand is involved in the operation;
binary— the operation involves two operands;
ternary— combines three operands.

The simplest form of expression is literal— something that evaluates to itself, for example, the number 100, the string "Hello world" . A variable can also be an expression, since it evaluates to the value assigned to it.

Expressions and Operators in JavaScript

1. Arithmetic operators

Arithmetic operators designed to perform mathematical operations, they operate on numeric operands (or variables that store numeric values), returning a numeric value as a result.

If one of the operands is a string, the JavaScript interpreter will try to convert it to a numeric type and then perform the appropriate operation. If type conversion is not possible, the result will be NaN (not a number).

Table 1. Arithmetic operators
Operator/Operation Description Priority
+ Addition Adds numeric operands. If one of the operands is a string, then the result of the expression is a string. 12
- Subtraction Subtracts the second operand from the first. 12
- Unary minus Converts a positive number to a negative number and vice versa. 14
* Multiplication Multiplies two operands. 13
/ Division Divides the first operand by the second. The result of division can be either an integer or a floating point number. 13
% Modulo division (division remainder) Calculates the remainder resulting from an integer division of the first operand by the second. Applies to both integers and floating point numbers. 13
var x = 5, y = 8, z; z = x + y; // return 13 z = x - y; // return -3 z = - y; // return -8 z = x * y; // return 40 z = x / y; // return 0.625 z = y % x; // return 3

2. Assignment operators

Assignment Operators are used to assign values ​​to variables. Combined operators allow you to store the original and subsequent values ​​in a single variable.

var a = 5; // assign the numeric value 5 to variable a var b = "hello"; // store the string hellow in variable b var m = n = z = 10; // assign the variables m, n, z the numerical value 10 x += 10; // equivalent to x = x + 10; x -= 10; // equivalent to x = x - 10; x *= 10; // equivalent to x = x * 10; x /= 10; // equivalent to x = x / 10; x %= 10; // equivalent to x = x % 10;

3. Increment and decrement operators

Operations increment and decrement are unary and increment and decrement the value of the operand by one. The operand can be a variable, an array element, or an object property. Most often, such operations are used to increment a counter in a loop.

var x = y = m = n = 5, z, s, k, l; z = ++x * 2; /* as a result of calculations will return the value z = 12, x = 6, i.e. the value of x is first increased by 1, and then the multiplication operation is performed */ s = y++ * 2; /* as a result of calculations will return the value s = 10, y = 6, i.e. First, the multiplication operation is performed, and then the value increased by 1 is stored in the variable y */ k = --m * 2; // return the value k = 8, m = 4 l = n-- * 2; // return the value l = 10, n = 4

4. Comparison operators

Comparison Operators are used to match operands, the result of the expression can be one of two values ​​- true or false . Operands can be not only numbers, but also strings, logical values ​​and objects. However, comparisons can only be performed on numbers and strings, so operands that are not numbers or strings are converted.

If both operands cannot be successfully converted to numbers or strings, the operators always return false .

If both operands are strings/numbers or can be converted to strings/numbers, they will be compared as strings/numbers.

If one operand is a string/converts to a string and the other is a number/converts to a number, then the operator will attempt to convert the string to a number and perform a number comparison. If the string is not a number, it is converted to NaN and the result of the comparison is false .

Most often, comparison operations are used when organizing branches in programs.

Table 4. Comparison operators
Operator/Operation Description Priority
== Equality Tests two values ​​for the same value, allowing type conversion. Returns true if the operands are the same, and false if they are different. 9
!= Inequality Returns true if the operands are not equal 9
=== Identity Tests two operands for "identity" using a strict definition of a match. Returns true if the operands are equal without type conversion. 9
!== Non-identity Performs identity verification. Returns true if the operands are not equal without type conversion. 9
> More Returns true if the first operand is greater than the second, otherwise returns false. 10
>= Greater than or equal to Returns true if the first operand is not less than the second, otherwise returns false. 10
Returns true if the first operand is less than the second, otherwise returns false. 10
Returns true if the first operand is not greater than the second, otherwise returns false. 10
5 == "5"; // return true 5 != -5.0; // return true 5 === "5"; // return false false === false; // return true 1 !== true; // return true 1 != true; // will return false since true is converted to 1 3 > -3; // return true 3 >= "4"; // return false

5. Logical operators

Logical operators allow you to combine conditions that return boolean values. Most often used in an if conditional statement.

(2 < 3) && (3===3); // вернет true, так как выражения в обеих скобках дают true (x < 10 && x >0); // will return true if x is in the range from 0 to 10 !false; // return true

6. Bitwise operators

Bitwise operators operate on the operands as a 32-bit sequence of ones and zeros and return a numeric value indicating the result of the operation, written in decimal system Reckoning. Integer numbers are considered as operands; the fractional part of the operand is discarded. Bitwise operations can be used, for example, when encrypting data, working with flags, and delineating access rights.

Table 6. Bitwise operators
Operator/Operation Description Priority
& Bitwise AND If both bits are 1, then the resulting bit will be 1. Otherwise the result is 0. 8
| Bitwise OR If one of the operands contains a 1 at position, the result will also contain a 1 at that position, otherwise the result at that position will be 0. 6
^ Exclusive OR If one and only one value contains a 1 at any position, then the result will contain a 1 at that position, otherwise the result at that position will be 0. 7
~ Denial A bitwise negation operation is performed on the binary representation of the value of an expression. Any position containing a 1 in the original expression is replaced with a 0. Any position containing 0 in the original expression becomes 0 . Positive numbers start at 0, negative numbers start at -1, so ~ n == -(n+1) . 14
The operator shifts the bits of the first operand to the left by the number of bit positions set by the second operand. Zeros are used to fill positions on the right. Return a result of the same type as the left operand. 11
>> Bitwise shift right The operator shifts the bits of the first operand to the right by the number of bit positions set by the second operand. Digits shifted outside the range are removed. The most significant bit (32nd) is left unchanged to preserve the sign of the result. If the first operand is positive, the most significant bits of the result are filled with zeros; if the first operand is negative, the most significant bits of the result are filled with ones. Shifting a value to the right by one position is equivalent to dividing by 2 (discarding the remainder), and shifting to the right by two positions is equivalent to dividing by 4, etc. 11
>>> Bitwise right shift without sign The operator shifts the bits of the first operand to the right by the number of bit positions set by the second operand. Zeros are added to the left, regardless of the sign of the first operand. Digits shifted outside the range are removed. 11
var x = 9, y = 5, z = 2, s = -5, result; // 9 is equivalent to 1001, 5 is equivalent to 0101 result = x & y; // will return 1 (equivalent to 0001) result = x | y; // will return 13 (equivalent to 1101) result = x ^ y; // returns 12 (equivalent to 1100) result = ~ y; // will return -6 (equivalent to 1100) result = x<< y; // вернет 288 (эквивалентно 100100000) result = x >> z; // return 2 (equivalent to 10) result = s >>> z; // will return 1073741822 (equivalent to 1111111111111111111111111111110)

7. String operators

There are several operators that work with strings in special ways.

"1" + "10"; // return "110" "1" + 10; // returns "110" 2 + 5 + "colored pencils"; // returns "7 colored pencils" "Colored pencils" + 2 + 5; // returns "25 colored pencils" "1" > "10"; // return false "10"<= 10; // вернет true "СССР" == "ссср"; // вернет false x = "micro"; x+= "soft"; // вернет "microsoft"

8. Special operators

Table 8. Special operators
Operator/Operation Description Priority
. Accessing a property Accesses a property of an object. 15
,Multiple calculation Evaluates multiple independent expressions written on one line. 1
Array indexing Accesses array elements or object properties. 15
() Function call, grouping Groups operations or calls a function. 15
typeof Data type definition Unary operator, returns the data type of the operand. 14
instanceof Checking the type of an object The operator checks whether an object is an instance of a particular class. The left operand must be an object, the right operand must contain the name of the object class. The result will be true if the object on the left is an instance of the class on the right, false otherwise. 10
in Checking for the presence of a property The left operand must be a string and the right operand must be an array or object. If the left value is a property of an object, the result will be true . 10
new Creating an object The operator creates a new object with undefined properties, then calls the constructor function to initialize it (passing parameters). Can also be used to create an array. 1
delete Delete The operator allows you to remove a property from an object or an element from an array. Returns true if the deletion was successful, false otherwise. When an array element is deleted, its length does not change. 14
void Defining an expression without a return value Unary operator, discards the value of the operand and returns underfined . 14
?: Conditional expression operator The ternary operator allows you to organize simple branching. The expression involves three operands, the first must be a Boolean value or convert to one, and the second and third must be any values. If the first operand is true , then the conditional expression will take the value of the second operand; if false - then the third one. 3
document.write("hello world"); // displays the string hello world i = 0, j = 1; // stores values ​​in variables function1(10, 5); // function call function1 with parameters 10 and 5 var year = ; // creates an array with elements typeof (a:1); // return "object" var d = new Date(); // create a new object using the Date() constructor d instanceof Date; // return true var mycar = (make: "Honda", model: "Accord", year: 2005); "make" in mycar; // return true var obj = new Object(); // creates an empty object var food = ["milk", "bread", "meat", "olive oil", "cheese"]; delete food; // removes the fourth element from the array food x > 10 ? x * 2: x / 2; // returns x * 2 if x > 10, otherwise x / 2

9. Comments in JavaScript

Single-line comment: you must precede the comment text with the symbols // .

An article in which we will consider another way to create a function - through a definition expression. In addition, let’s look at the difference between this method of declaring a function and the traditional one.

Creating a Function Using a Definition Expression

In JavaScript, you can create a function not only using the traditional method (Traditional Declarations), but also using Definition Expressions. This method of defining a function in some sources is called a function literal.

The basic idea of ​​Definition Expressions is that the function definition is used as the value of some variable or expression.

For example, the sum variable will contain a description of a function that will output to the console the sum of 2 numbers specified as a parameter.

Var sum = function(num1,num2) ( return console.log(num1+num2); );

A function created based on a definition expression is called by the name of the variable.

//for example, call the function contained in the sum variable and pass 2 arguments to it. sum(7,4);

Note: The function name is not specified in the definition expression. A function that is described without a name is called anonymous.

Note that JavaScript allows you to use a name in the syntax of a function that is created as a definition expression. But this only makes sense when it needs to be addressed inside her own body. For example, when writing recursive functions. This feature does not provide any other application, since it is impossible to refer to a function defined in this way outside its boundaries by name.

For example, let's create a function to calculate the factorial specified as a number parameter:

Var factorial = function fact(num) ( if (num

This code defines a function and stores a reference to it in the factorial variable. To call a function inside this function we use the name fact . Please note that you cannot access a function outside its body by the name fact; for this you must use the factorial variable.

But even in this case, you can do without a name, because JavaScript allows you to call a function inside its body using the callee property of the arguments object.

Var factorial = function(num) ( if (num

JavaScript - Self-Calling Function

A function defined by a definition expression can be called immediately. To do this, after the function body you need to put parentheses and specify arguments in them, if necessary.

For example, let's call the sum function immediately with parameter values ​​7 and 4.

Var sum = function(num1,num2) ( return console.log(num1+num2); )(7,4);

The process of calling a function immediately is sometimes called initialization or function instantiation.

A function definition expression is very often used if it needs to be executed once and immediately. To do this, you can even not use a variable, but immediately write a calculated expression, i.e. wrap the anonymous function definition in parentheses.

(function(num1,num2) ( return console.log(num1+num2); )(7,4));

Differences between Function Declaration and Function Expression

The main differences between the Function Declaration and Function Expression functions are presented in the following table:

Function Declaration Function Expression
The browser (JavaScript interpreter) considers a function to be a Function Declaration if it is located in the main code flow (not part of any expression). The browser finds a function as a Function Expression if it is placed within an expression.
When declaring a function in this way, the variable by which it is accessed is created automatically. function square(a) ( return a*a; ) // calling the function console.log(square(5)); To access a function, you need to create a variable and store a link to this function in it. var square = function(a) ( return a*a; ) // calling the function console.log(square(5));
Initialized before code execution (in the corresponding scope). This action also called raising or hoisting. Such functions can be called before declaration. // call the function before it is declared console.log(square(7)); function square(a) ( return a*a; ) Function Expressions cannot be used before they are declared. Only the variable itself is raised. // error when calling the function console.log(square(7)); var square = function(a) ( return a*a; )

In this case the following happens:

Var square; console.log(square(7)); // but at this stage the variable square has the value undefined square = function(a) ( return a*a; )

When using use strict a function declared as a Function Declaration will only be visible within the block in which it is declared. "use strict"; if (true) ( ​​function sum(a,b,c) ( return a+b+c; ) console.log(sum(10,20,10)); ) // error accessing function sum console.log(sum (4,5,4)); Unlike a Function Declaration, a function can be accessed outside the block in which it is created: "use strict"; if (true) ( ​​var sum = function (a,b,c) ( return a+b+c; ) console.log(sum(10,20,10)); ) // have access to the sum function console.log (sum(4,5,4));
A function declared as a Function Declaration cannot be called immediately.
In order to do this, you need to make the function part of the expression, for example, wrap it in parentheses. The function will then be considered part of the Function Expression and can be called immediately.
For example: var sum = (function sum(a,b,c) ( return a+b+c; ))(5,6,7); console.log(typeof sum); // number console.log(sum); // number
A function declared as a Function Expression can be called immediately. var sum = function (a,b,c) ( return a+b+c; )(5,6,7); console.log(typeof sum); // number console.log(sum); // number In this case, the sum variable (in this case) no longer contains a link to the function, but its result (in this example, a number).

Conclusion: The way you declare a function using a definition expression allows you to use the function as a variable. This opportunity The JavaScript language is very interesting and allows you to create more flexible scripts.

As a C language object, a function must be declared. Declaring a user function, i.e. its declaration is carried out in two forms - in the form of a description and in the form of a definition.

The description of a function consists of first presenting the program file of its prototype. The function prototype informs the compiler that its full definition (its full text) will be given later in the program text: in the current or another source file, or located in the library.

The language standard uses the following method of declaring functions:

result_type ID _functions(variable type1, ..., variable type N);

Note that it is not necessary to specify variable identifiers in prototype parentheses, since the language compiler does not process them.

The prototype description allows the compiler to check that the types and number of parameters match when the function is actually called.

An example of a fun function description with a list of parameters:

float fun(int, float, int, int);

The complete definition of the function is as follows:

result_type ID _functions (parameter list)

function code

The result type determines the type of expression whose value is returned to the point of its call using the operator return<выражение> .

If a function type is not specified, the default type is assumed int .

The parameter list consists of a list of parameter types and parameter identifiers, separated by commas.

The function may not have parameters, but parentheses are required in any case.

If a function does not return any value, it must be declared as a function of type void (blank).

In this case the operator return you don't have to put it.

A function can have multiple statements return , but there may not be any. In such cases, return to the calling program occurs after the last statement in the function is executed.

An example of a function that determines the smallest value of two integer variables:

int min (int x, int y)

return(x

All functions that return a value must be used on the right side of C expressions, otherwise the returned result will be lost.

If a function does not have a list of parameters, then when declaring such a function, it is advisable to also indicate the void keyword in parentheses. For example, void main(void).


Close