Javascript functions with parameters. Inverse trigonometric functions. What is a function

Last update: 04/09/2018

Functions are a set of instructions that perform a specific action or calculate a specific value.

Function definition syntax:

Function function_name([parameter [, ...]])( // Instructions )

A function definition begins with the keyword function followed by the name of the function. A function name follows the same rules as a variable name: it can only contain numbers, letters, underscores, and dollar ($) characters, and must begin with a letter, underscore, or dollar.

After the function name, the parameters are listed in parentheses. Even if a function has no parameters, it simply contains empty parentheses. Then, in curly braces, comes the body of the function, which contains a set of instructions.

Let's define the simplest function:

Function display())( document.write("function in JavaScript"); )

This function is called display(). It doesn't accept any parameters and all it does is write a string to the web page.

However, simply defining a function is not enough to make it work. You still need to call her:

function display())( document.write("function in JavaScript"); ) display();

It is not necessary to give functions a specific name. You can use anonymous functions:

Var display = function())( // function definition document.write("function in JavaScript"); ) display();

What we're doing is actually defining a display variable and assigning it a function reference. And then the function is called based on the variable name.

We can also dynamically assign functions to a variable:

Function goodMorning())( document.write("Good morning"); ) function goodEvening())( document.write("Good evening"); ) var message = goodMorning; message(); // Good morning message = goodEvening; message(); // Good evening

Function parameters

Let's consider passing parameters:

Function display(x)( // function definition var z = x * x; document.write(x + " squared equals " + z); ) display(5); // function call

The display function takes one parameter - x. Therefore, when calling a function, we can pass a value for it, for example, the number 5, as in this case.

If a function takes several parameters, then using the spread operator... we can pass a set of values ​​for these parameters from an array:

Function sum(a, b, c)( let d = a + b + c; console.log(d); ) sum(1, 2, 3); let numbers = ; sum(...nums);

In the second case, numbers from the nums array are passed to the function. But in order to transmit not just an array as one value, but numbers from this array, the spread operator (ellipsis...) is used.

Optional Parameters

A function can take many parameters, but some or all of the parameters can be optional. If no value is passed for parameters, they default to "undefined".

Function display(x, y)( if(y === undefined) y = 5; if(x === undefined) x = 8; let z = x * y; console.log(z); ) display() ; // 40 display(6); // 30 display(6, 4) // 24

Here the display function takes two parameters. When calling a function, we can check their values. However, when calling a function, it is not necessary to pass values ​​for these parameters. To check for the presence of a parameter value, a comparison with the undefined value is used.

There is another way to define default values ​​for parameters:

Function display(x = 5, y = 10)( let z = x * y; console.log(z); ) display(); // 50 display(6); // 60 display(6, 4) // 24

If no values ​​are passed to the parameters x and y, they are obtained as the values ​​of the numbers 5 and 10, respectively. This method is more concise and intuitive than comparing with undefined.

In this case, the default value of the parameter can be derived, representing the expression:

Function display(x = 5, y = 10 + x)( let z = x * y; console.log(z); ) display(); // 75 display(6); // 96 display(6, 4) // 24

In this case, the value of the parameter y depends on the value of x.

If necessary, we can get all the passed parameters through the globally accessible arguments array:

Function display())( var z = 1; for(var i=0; i target) return null; else return find(start + 5, "(" + history + " + 5)") || find(start * 3 , "(" + history + " * 3)" ) return find(1, "1"); ) console.log(findSolution(24)); // → (((1 * 3) + 5) * 3)

This example does not necessarily find the shortest solution - it is satisfied by any. I don't expect you to immediately understand how the program works. But let's understand this great exercise in recursive thinking.

The inner function find does recursion. It takes two arguments - the current number and a string that contains a record of how we arrived at this number. And it returns either a string showing our sequence of steps, or null.

To do this, the function performs one of three actions. If the given number is equal to the goal, then the current story is precisely the way to achieve it, so it returns. If the given number is larger than the goal, there is no point in continuing to multiply and add, because it will only increase. And if we haven't reached the goal yet, the function tries both possible paths starting with the given number. She summons herself twice, once with each method. If the first call does not return null, it is returned. In another case, the second one is returned.

To better understand how the function achieves its desired effect, let's look at the calls it makes to find a solution to the number 13.

Find(1, "1") find(6, "(1 + 5)") find(11, "((1 + 5) + 5)") find(16, "(((1 + 5) + 5 ) + 5)") too big find(33, "(((1 + 5) + 5) * 3)") too big find(18, "((1 + 5) * 3)") too big find( 3, "(1 * 3)") find(8, "((1 * 3) + 5)") find(13, "(((1 * 3) + 5) + 5)") found!

The indentation shows the depth of the call stack. The first time, the find function calls itself twice to check solutions starting with (1 + 5) and (1 * 3). The first call looks for a solution starting with (1 + 5) and uses recursion to check all solutions that produce a number less than or equal to the required number. Doesn't find it and returns null. Then the operator || and moves on to a function call that examines the (1 * 3) option. We're in luck here, because in the third recursive call we get 13. This call returns a string, and each of the || along the way it passes this line higher, resulting in returning a solution.

Growing Functions There are two more or less natural ways to introduce functions into a program.

The first is that you write similar code several times. This should be avoided - more code means more room for errors and more reading material for those trying to understand the program. So we take a recurring functionality, give it a good name, and put it into a function.

The second way is that you discover a need for some new functionality that is worthy of being placed in a separate function. You start with the name of the function, and then write its body. You can even start by writing the code that uses the function before the function itself has been defined.

How difficult it is for you to name a function shows how well you understand its functionality. Let's take an example. We need to write a program that prints two numbers, the number of cows and chickens on the farm, followed by the words “cows” and “chickens.” You need to add zeros to the numbers in front so that each one occupies exactly three positions.

007 Cows 011 Chickens

Obviously, we need a function with two arguments. Let's start coding.
// print FarmInventory function printFarmInventory(cows, chickens) ( var cowString = String(cows); while (cowString.length< 3) cowString = "0" + cowString; console.log(cowString + " Коров"); var chickenString = String(chickens); while (chickenString.length < 3) chickenString = "0" + chickenString; console.log(chickenString + " Куриц"); } printFarmInventory(7, 11);

If we add .length to a string, we get its length. It turns out that the while loops add leading zeros to the numbers until they get a line of 3 characters.

Ready! But just as we were about to send the code to the farmer (along with a hefty check, of course), he calls and tells us that he has pigs on his farm, and could we add a display of the number of pigs to the program?

Of course it is possible. But when we start copying and pasting the code from these four lines, we realize that we need to stop and think. There must be a better way. We are trying to improve the program:

// output WITH Adding Zeros AND Labels function printZeroPaddedWithLabel(number, label) ( var numberString = String(number); while (numberString.length< 3) numberString = "0" + numberString; console.log(numberString + " " + label); } // вывестиИнвентаризациюФермы function printFarmInventory(cows, chickens, pigs) { printZeroPaddedWithLabel(cows, "Коров"); printZeroPaddedWithLabel(chickens, "Куриц"); printZeroPaddedWithLabel(pigs, "Свиней"); } printFarmInventory(7, 11, 3);

Works! But the name printZeroPaddedWithLabel is a bit strange. It combines three things—output, adding zeros, and a label—into one function. Instead of inserting an entire repeating fragment into a function, let's highlight one concept:

// add Zero function zeroPad(number, width) ( var string = String(number); while (string.length< width) string = "0" + string; return string; } // вывестиИнвентаризациюФермы function printFarmInventory(cows, chickens, pigs) { console.log(zeroPad(cows, 3) + " Коров"); console.log(zeroPad(chickens, 3) + " Куриц"); console.log(zeroPad(pigs, 3) + " Свиней"); } printFarmInventory(7, 16, 3);

A function with a nice, clear name zeroPad makes the code easier to understand. And it can be used in many situations, not only in our case. For example, to display formatted tables with numbers.

How smart and versatile should the features be? We can write a simple function that pads a number with zeros up to three positions, or a sophisticated general purpose function for formatting numbers that supports fractions, negative numbers, dot alignment, padding, etc.

A good rule of thumb is to add only functionality that you know will be useful. Sometimes it's tempting to create general-purpose frameworks for every little need. Resist him. You'll never finish the job, you'll just end up writing a bunch of code that no one will use.

Functions and Side Effects Functions can be roughly divided into those that are called for their side effects and those that are called to obtain some value. Of course, it is also possible to combine these properties in one function.

The first helper function in the farm example, printZeroPaddedWithLabel, is called because it has a side effect: it prints a string. The second, zeroPad, because of the return value. And it’s not a coincidence that the second function comes in handy more often than the first. Functions that return values ​​are easier to combine with each other than functions that produce side effects.

A pure function is a special kind of value-returning function that not only has no side effects, but also does not depend on the side effects of the rest of the code - for example, it does not work with global variables that could be accidentally changed somewhere else. A pure function, when called with the same arguments, returns the same result (and does nothing else) - which is quite nice. She's easy to work with. A call to such a function can be mentally replaced by the result of its work, without changing the meaning of the code. When you want to test such a function, you can simply call it, and be sure that if it works in a given context, it will work in any context. Less pure functions may return different results depending on many factors, and have side effects that are difficult to test and account for.

However, you should not be embarrassed to write functions that are not entirely pure, or to begin a sacred purge of such functions from the code. Side effects are often beneficial. There is no way to write a clean version of the console.log function, and this function is quite useful. Some operations are easier to express using side effects.

Summary This chapter showed you how to write your own functions. When the function keyword is used as an expression, returns a pointer to the function call. When used as an instruction, you can declare a variable by assigning a function call to it.

The key to understanding functions is local scope. Parameters and variables declared inside a function are local to it, are recreated each time it is called, and are not visible from the outside. Functions declared inside another function have access to its scope.

It is very useful to separate the different tasks performed by a program into functions. You don't have to repeat yourself; functions make code more readable by dividing it into meaningful parts, just as chapters and sections of a book help organize regular text.

ExercisesMinimum In the previous chapter, we mentioned the Math.min function, which returns the smallest of its arguments. Now we can write such a function ourselves. Write a min function that takes two arguments and returns the minimum of them.

Console.log(min(0, 10)); // → 0 console.log(min(0, -10)); // → -10

Recursion We have seen that the % (modulo) operator can be used to determine whether a number (%2) is even. Here's another way to define it:

Zero is even.
The unit is odd.
Any number N has the same parity as N-2.

Write a recursive function isEven according to these rules. It must accept a number and return a boolean value.

Test it at 50 and 75. Try giving it -1. Why is she acting this way? Is it possible to somehow fix it?

Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?

Console.log(isEven(50)); // → true console.log(isEven(75)); // → false console.log(isEven(-1)); // → ??

Counting the beans.

The character number N of a string can be obtained by adding .charAt(N) (“string”.charAt(5)) to it - in a similar way to getting the length of a string using .length. The return value will be a string consisting of one character (for example, “k”). The first character of the string has position 0, which means that the last character will have position string.length - 1. In other words, a string of two characters has length 2, and its character positions will be 0 and 1.

Write a function countBs that takes a string as an argument and returns the number of “B” characters contained in the string.

Then write a function called countChar, which works something like countBs, but takes a second parameter - the character we'll be looking for in the string (instead of just counting the number of "B" characters). To do this, rework the countBs function.

May 24, 2011 at 01:13 Five ways to call a function
  • JavaScript
  • Translation

I often come across JavaScript code where errors are caused by a misunderstanding of how functions work in JavaScript (by the way, much of this code was written by me). JavaScript is a multi-paradigm language, and it has functional programming mechanisms. It's time to explore these possibilities. In this article, I will tell you five ways to call functions in JavaScript.

In the early stages of learning JavaScript, beginners usually think that functions in it work in much the same way as in, say, C#. But the mechanisms for calling functions in JavaScript have a number of important differences, and ignorance of them can result in errors that will not be easy to find.

Let's write a simple function that returns an array of three elements - the current this value and the two arguments passed to the function.
function makeArray(arg1, arg2)( return [ this, arg1, arg2 ]; )

The most common way: global call Beginners often declare functions as shown in the example above. Calling this function is easy:
makeArray("one", "two"); // => [ window, "one", "two" ]
Wait. Where does the window object come from? Why is this equal to window?

In JavaScript, no matter whether the script is executed in the browser or in another environment, it is always defined global object. Any code in our script that is not "bound" to anything (that is, outside of the object declaration) is actually in the context of the global object. In our case, makeArray is not just a function “walking” on its own. In fact, makeArray is a method of the global object (in the case of code execution in the browser) window . It's easy to prove:
alert(typeof window.methodThatDoesntExist); // => undefined alert(typeof window.makeArray); // => function
That is, calling makeArray("one", "two"); is equivalent to calling window.makeArray("one", "two"); .

It saddens me that this is the most common way of calling functions, because it implies the presence of a global function. And we all know that global functions and variables are not the best form in programming. This is especially true for JavaScript. Avoid global definitions, and you won't regret it.

Function calling rule #1: If a function is called directly, without specifying an object (for example, myFunction()), the value of this will be the global object (window if the code is executed in the browser).

Calling a Method Let's create a simple object and make makeArray its method. Let's declare the object using literal notation, and then call our method:
// create an object var arrayMaker = ( someProperty: "some value", make: makeArray ); // call the make() method arrayMaker.make("one", "two"); // => [ arrayMaker, "one", "two" ] // alternative syntax, use square brackets arrayMaker["make"]("one", "two"); // => [ arrayMaker, "one", "two" ]
Do you see the difference? The value of this in this case is the object itself. Why not window , as in the previous case, since the function declaration has not changed? The secret is how functions are passed in JavaScript. Function is a standard JavaScript type that is actually an object, and like any other object, functions can be passed around and copied. In this case, we've essentially copied the entire function, including the argument list and body, and assigned the resulting object to the arrayMaker object's make property. This is equivalent to a declaration like this:
var arrayMaker = ( someProperty: "Some value"; make: function (arg1, arg2) ( return [ this, arg1, arg2]; ) );
Function Calling Rule #2: In a function called using method call syntax, such as obj.myFunction() or obj["myFunction"]() , this will have the value obj .

Misunderstanding of this generally simple principle often leads to errors when processing events:
function buttonClicked())( var text = (this === window) ? "window" : this.id; alert(text); ) var button1 = document.getElementById("btn1"); var button2 = document.getElementById("btn2"); button1.onclick = buttonClicked; button2.onclick = function())( buttonClicked(); );
Clicking the first button will show a message "btn1" because in this case we are calling a function as a method, and this inside the function will get the value of the object that this method belongs to. Clicking the second button will give "window" because in this case we are calling buttonClicked directly (i.e. not like obj.buttonClicked()). The same thing happens when we assign an event handler to the element tag, as in the case of the third button. Clicking the third button will show the same message as the second.

When using libraries like jQuery, you don't need to think about this. jQuery will take care to rewrite the this value in the event handler so that the this value is the element that raised the event:
// use jQuery $("#btn1").click(function() ( alert(this.id); // jQuery will make sure "this" is a button ));
How does jQuery manage to change the value of this ? Read below.

Two more ways: apply() and call() It is logical that the more often you use functions, the more often you have to pass them and call them in different contexts. Often there is a need to override the value of this . If you remember, functions in JavaScript are objects. In practice, this means that functions have predefined methods. apply() and call() are two of them. They allow you to override the this value:
var car = ( year: 2008, model: "Dodge Bailout" ); makeArray.apply(car, [ "one", "two" ]); // => [ car, "one", "two" ] makeArray.call(car, "one", "two"); // => [ car, "one", "two" ]
These two methods are very similar. The first parameter overrides this . The differences between them are in the subsequent arguments: Function.apply() accepts an array of values ​​that will be passed to the function, while Function.call() accepts the arguments separately. In practice, in my opinion, it is more convenient to use apply() .

Function Calling Rule #3: If you want to override the value of this without copying the function to another object, you can use myFunction.apply(obj) or myFunction.call(obj) .

Constructors I won't go into detail about declaring custom types in JavaScript, but I think it's necessary to remind you that there are no classes in JavaScript, and any custom type needs a constructor. In addition, it is better to declare methods of a custom type using prototype , which is a property of the constructor function. Let's create our own type:
// declare the constructor function ArrayMaker(arg1, arg2) ( this.someProperty = "no matter"; this.theArray = [ this, arg1, arg2 ]; ) // declare methods ArrayMaker.prototype = ( someMethod: function () ( alert( "Called by someMethod"); getArray: function () ( return this.theArray; ) ); var am = new ArrayMaker("one", "two"); var other = new ArrayMaker("first", "second"); am.getArray(); // => [ am, "one", "two" ]
The important thing in this example is the presence of the new operator before the function call. If it weren't for it, it would be a global call, and the properties created in the constructor would belong to the global object. We don't need that. Additionally, constructors usually do not return values ​​explicitly. Without the new operator the constructor would return undefined , with it it returns this . It is considered good style to name constructors with a capital letter; This will remind you of the need for the new operator.

Otherwise, the code inside the constructor will likely be similar to code you would write in another language. The value of this in this case is the new object you are creating.

Function Calling Rule #4: When calling a function with the new operator, the value of this will be a new object created by the JavaScript runtime. If this function does not return any object explicitly, this will be returned implicitly.

Conclusion Hopefully, understanding the difference between different ways of calling functions will help you improve your JavaScript code. Sometimes errors related to the this value are difficult to catch, so it makes sense to prevent them in advance.

The ideas of dynamically generating content on a web resource have become the norm. Static pages and template website building have finally completed their mission.

However, a modern web resource does not necessarily have to be represented by a set of pages generated by the server and updated by the browser (JS+AJAX).

When a visitor arrives, a web resource can consist of a couple of headers for the protocol, some text in the “head”, a few lines of code in the “body” and that’s it. The rest " will come up with an idea” during the visitor's experience - this is an ideal site or aspiring to be such.

Place of description and essence of functions

JavaScript is an experience gained over many decades. It has a significant development history and a modern, qualified team of creators and developers. The language is well thought out, reliable, beautiful and provides a real opportunity for developers to write decent code and improve themselves.

The concept of an algorithm outside a function is absent here in principle. Of course, the developer can insert a script anywhere on the page, place the code in it, and it will be executed. But what is the point of code that is executed only once: when the page is loaded (reloaded)? Unless it is possible to set the initial values ​​of some unimportant variables.

A script is a place for describing the necessary variables and functions, rather than a good piece of code written for its own sake. It is the set of functions that is essential and significant, perhaps their mutual direct connection, but more often everything is different. The place where a function is described and the place where it is applied are not at all the same thing.

It is not at all necessary that a function will call another function directly; it can do this indirectly through dynamic code generation. The visitor makes a decision within the framework of this code and a completely different system of functions is triggered.

Functional dynamics

Functional dynamics are not only and not so much the handlers assigned to page elements, they are the functions that form the page elements, and the direct handlers can also change.

The action on the page unfolds depending on its elements and the behavior of the visitor on it. Mouse movements, keyboard buttons, clicks, element events and other circumstances lead to the launch of the necessary functions.

Initially there is no sequence and there is no parallelism. There is an adequate response of the web resource to events. How quickly JavaScript will perform a particular function depends on many technical (computer, communication lines) and semantic (algorithm logic, subject area, meaning of the task) factors.

In fact, one can say that something worked in parallel, and something will be fulfilled after something, but there is no particular meaning in this. It is important that JavaScript functions provide the ability to create an adequate response to visitor actions.

This is new thinking in development: distributed information processing in the bowels of a single browser!

Syntax of Variables and Functions

JavaScript variables are placed both in the “script” tag and in the body of the function. Functions are defined in the same way. There is no particular point in writing another function inside a function, but this may be necessary for various and well-founded reasons.

A function description generally begins with the keyword "function", followed by its name, a list of arguments in parentheses separated by commas, and the function body in curly braces.

This example describes two functions that provide AJAX exchange between the page and the server. The scXHR variable is described above, therefore it is available both in InitXML and inside WaitReplySC.

Function name and "function" parameter

An asynchronous option was introduced here, where the JavaScript function in the function is called after the server responds. At the same time, having received a response from the server, WaitReplySC accesses the page tags, fills them with the received information and calls other functions that may well initiate the next request to the server.

It's also important to note here that WaitReplySC is a function. But in the line scXHR.onreadystatechange = WaitReplySC it is passed as a parameter. This is a general rule for passing functions to other functions as parameters. Specify brackets and pass its parameter(s) into them - the function will be executed immediately. He only gave me his name, but so what. The function call will be made by the one who received its name.

Functionality implemented through AJAX allows you to make a call to a JavaScript function through data received from the server. In fact, when sending a request to the server, a particular function may not “know” at all which function it is accessing and with what information.

Function exit and its result

In the body of the function, you can write any operators of the language, which, in fact, is intended for this purpose. Variables defined inside and outside of a function are available within a function, but not those defined in other functions.

If you want a function to return a result, you can use the JavaScript return statement: return. There can be a sufficient number of return statements in the function body. It is not at all necessary that they all return the same type of result.

Typically, developers highly respect this feature and, depending on the situation, decide to exit the feature as soon as possible.

It is not at all necessary to go through the entire function algorithm when you can exit earlier.

Function Arguments

Arguments to a function are passed as a comma-separated list, enclosed in parentheses and located immediately after its name. Variable names are used as arguments, but values ​​can also be passed directly. To pass a function to a function in JavaScript, you just need to specify its name without parentheses.

Inside the function, the arguments variable is available, which has the length property. You can access any function argument through arguments , arguments , ... until the last arguments .

Changing a function argument is valid inside the function, but not outside it. In order to change something outside the function, you need to use the JavaScript return operator, through which you pass the required value outside.

After the function completes, everything associated with its execution will be destroyed. During execution, a function can change external variables, except those described in other functions, including internal ones.

arguments has a callee property, which is intended to call a function that is being executed at a given time. If you call itself, the JavaScript version of a function within a function allows you to implement recursion.

Using Functions

The main concern of functions is to serve browser events. To do this, in almost every tag it is possible to specify the name of the event and the function that processes it. Multiple events can be specified, but only one function is specified per event.

One function can serve multiple page elements and multiple events. Using the “this” parameter, you can pass information to the function where it was called from.

A classic use of JS functions is event handlers on elements. In this example, the scfWecomeGo() or scfWelcomeCancel() function will be called in the visitor login/logout form, and scfMenuItemClick(this) when selecting the operating mode.

In the latter case, the “this” parameter is passed, which allows you to miraculously find out which div the call came from. In general, JavaScript is so well implanted into the DOM and it allows you to navigate through its elements so conveniently and collect the necessary information that the dynamics of the page can be simply unpredictable.

A function does not have to return a string of characters, a number, or another function. It can return a full-fledged HTML element, which will contain the required number of elements, with its own event handlers.

By placing such an element on the page, the developer creates new functionality, which is good in terms of solving the problem and satisfying the interests of visitors, but quite difficult in terms of implementation.

When starting such a full-featured development, it is easy to get confused in your own code, in function calls, in the moments when this or that content of this or that part of the page is formed. Before taking this direction of development, it doesn't hurt to weigh everything carefully.

About distributed thinking

The developer has to think at the level of all page elements, at the level of all events, and have a clear idea of ​​how everything actually happens. It's difficult, but the work is worth it.

In JavaScript, the execution of a function can be deferred until some event occurs, and there can be many such functions, and events tend to propagate and fall into the “sphere of visibility” of various handlers.

In this example, a function was called somewhere earlier that initiated the creation of a file navigation menu item. A page organization is assumed, that is, there are only seven files in the window that can be deleted and processed. You can navigate either by clicking on a line of the file, using arrows on the keyboard, or in blocks of seven lines.

Each case has its own functions. In other words, in such a simple example it is necessary to write a couple of dozen functions that will respond to various events, and some of these functions will process various options and situations that are not related to events at all.

For example, when you delete a row, the lower ones should move up. To do this, you will either need to make a new selection, which is trivial and resource-intensive, or recalculate the lines, use array functions in javascript and elegantly achieve the goal.

Function Arguments and Results

JavaScript allows you to bring your code to a "fully functional" state. It's normal for a function's argument to be a function. An option is allowed when the function returns a function. JavaScript is completely relaxed about this.

This is a good mechanism, but quite complex in terms of implementation. Technically, everything is permissible; only a qualified developer can semantically provide the logic for transferring the “functionality”.

When in JavaScript there is a function within a function, everything goes well, but when a function generates a function, and that one generates another, then it is quite difficult to follow the logic. Essentially, it's not a question of applying the qualification, it's a question of getting a safe and correct result.

The developer's concern is clear and simple. There is a problem, you need a solution, not an error like “JavaScript error the operation is insecure,” a blank screen, or stopping the entire browser engine.

If the argument is a function, then the developer is passing a variable with special properties, that is, it is not a number, not a string, not an object. But using such an argument can lead to external variables changing and the result of the function being executed. Depending on what is transmitted, adequate changes will be made.

Execution of generated code

You can implement the execution of code generated during the operation of other code using “eval”. This is not considered a great solution, but often you can not complicate the code with unnecessary functions, but limit yourself to the banal formation of a line of JavaScript code and simply execute it.

In this example, a line is generated to insert some information into the current div. The div number and information content are different for different positions, so such a solution in this situation is not guaranteed to provide the “javascript error the operation is insecure” situation, but it will reliably give the desired effect.

A nuance of the JavaScript “function within a function” paradigm

If there is an opportunity to do without frills, it is better to take advantage of it. All of the options listed are good. Of course, in many cases this is the only solution.

A classic example of recursion: calculating factorial. It's quite difficult to write an algorithm that goes into a loop, but it's very easy to go beyond the boundaries of the value. The factorial is growing too quickly.

However, both recursion and a function calling another function that can make a valid callback are the norm.

For example, a regular table. There may be other tables in the table. Nesting cannot be limited. Writing your own set of functions for each table is too much of a luxury.

There are many such examples that can be given, and all of these will be real and pressing tasks, not at all from the field of programming. That is why the problem lies precisely in the fact that it is impossible to do without frills; the created system of functions, or rather its debugging and subsequent reliable operation, becomes the concern not of JavaScript, but of the developer.

Article under development!

An article in which we will consider what a function is, as well as the traditional (classic) version of working with it. In addition, we will analyze what the arguments (parameters) of the function and the return operator are.

What is a function?

A function is a set of instructions that can be given a name and then accessed by that name from anywhere in the program.

A classic example of using a function.

There is JavaScript code on a web page, some fragment of which is repeated several times. To avoid this, you can format this fragment as a function, and then call it in the necessary places in the code using the name of this function. Calling this function will mean executing the instructions contained in it.

  • How to organize the execution of some task in JavaScript using functions? To do this you usually do this:
  • break the task into its component parts (subtasks);
  • subtasks are formalized through functions;

develop the main code using calls to the created functions.

As a result, such a program becomes more structured. It is easier to make various changes and add new features.

Declaring and calling a function

  • Operations with a function in JavaScript can be divided into 2 steps:
  • declaration (creation) of a function.

call (execute) this function.

Function declaration.

Functions of this kind in JavaScript are called function declaration statements. In addition to this type, JavaScript also distinguishes between the function definition expression and arrow function expression functions.

The function name is composed according to the same rules as the variable name. Those. it can contain letters, numbers (0-9), "$" and "_" signs. It is recommended to use only letters of the English alphabet (a-z, A-Z) as letters. The name of a function, just like the name of a variable, cannot begin with a number.

A function can have as many parameters as desired or none at all. Parentheses are included in any case. If there are several parameters, then they must be separated by a comma. Function parameters are accessed by their name.

A set of instructions enclosed in curly braces is the function code that will be executed when it is called.

Function call.

The declared function itself will not be executed. In order to run it, it must be called. A function is called by specifying its name and two parentheses. Arguments are specified inside parentheses if necessary.

// call the function given in the previous example someName();

JavaScript - Function Call Syntax

Is a function an object in JavaScript?

Functions in JavaScript are objects.

In JavaScript, everything is an object except the six primitive data types. And if the function is an object, then a reference to it can be stored in a variable.

// function declaration someName function someName() ( alert("You called the function someName!"); ) var reference = someName;

After this, you can call the function like this:

Reference();

Function parameters and arguments

In other words, function parameters are local variables that are created automatically when the function is launched. The parameters receive as values ​​the corresponding arguments passed to the function during its call. You can access the parameters only inside this function; outside of it they do not exist.

// declaration of a function sayWelcome, which has two parameters function sayWelcome (userFirstName, userLastName) ( // an instruction that displays the values ​​of the parameters “userFirstName” and “userLastName” to the console console.log("Welcome, " + userLastName + " " + userFirstName ; )

In JavaScript, when calling a function, the number of arguments does not have to be the same as the number of parameters. Parameters that were not set to value when called will be equal to undefined .

For example, let's call the function from the example above, without specifying one or two parameters:

// calling the sayWelcome function and passing one argument to it sayWelcome("Peter"); // Welcome, undefined Peter // calling the sayWelcome function without passing any arguments to it sayWelcome(); // Welcome, undefined undefined

An example of a function that will simply output the arguments passed to it to the browser console:

// function declaration function outputParam(param1, param2, param3) ( console.log(param1 + "; " + param2 + "; " + param3); ) // calls to the function outputParam passing it a different number of parameters outputParam("Rain" "Snow","Fog"); // Rain; Snow; Fog outputParam(17); // 17; undefined; undefined outputParam(24,33); // 24; 33; undefined outputParam(); // undefined; undefined; undefined

Another way to access arguments within a function is to use the special arguments object. Arguments are accessed via arguments in the same way as elements of a regular array, i.e. by their serial numbers. Thus, argument - will allow you to get the first argument, arguments - the second argument, etc.

// function declaration sum function sum(num1, num2) ( /* num1 or arguments – get the value of argument 1 num2 or arguments – get the value of argument 2 */ var sum1 = num1 + num2, sum2 = arguments + arguments; return "Sum, obtained by the 1st method is equal to " + sum1 + "; the sum obtained by the 2nd method is " + sum2; ) /* output the result of the sum function to the console 7 - the first argument (it can be accessed either by the name num1 or using arguments) 4 - the second argument (it can be accessed either by the name num2 or using arguments) */ console.log(sum(7,4));

The main difference between these methods is that the first of them allows you to access only those arguments that were given names at the function declaration stage. The second method allows you to get the value of any argument, even if it does not have a name (by serial number). This feature of the JavaScript language allows you to create universal, flexible functions.

In addition to receiving arguments, the arguments object also allows you to know their number. This is done using the length property.

You can iterate over the arguments passed to the function, for example, using a for or for...of loop.

// function declaration sum function sum() ( var i = 0; console.log("Output all arguments using a for loop"); for (i; i< arguments.length; i++) { console.log(i + 1 + " аргумент равен " + arguments[i]); } console.log("Вывод всех аргументов с помощью цикла for...of"); for (arg of arguments) { console.log(arg); } } // вызов функции sum sum(7, 4, 3, 1);

A function that displays to the console all the arguments passed to it and their number:

// function declaration function myFunction () ( var i; console.log("Number of parameters passed = " + arguments.length); // let's go through all the parameters using a for loop for (i = 0; i< arguments.length; i++) { console.log(i + " параметр = " + arguments[i]); } } // вызовы функции myFunction myFunction(3, 7, 27, "JavaScript"); myFunction(); myFunction("Яблоки", "Груши", "Апельсины");

A function that performs the addition of all arguments passed to it (their number is unknown in advance):

// function declaration var myCalc = function() ( // let's go through all the parameters using the for loop var i, sum = 0; for (i = 0; i lt; arguments.length; i++) ( sum += arguments[i] ; ) // return the sum as the result return sum; ) // function call (output to the console) console.log(myCalc(4, 20, 17, -6));

As a result, using the arguments object you can implement the following in the function body:

  • checking the number of arguments passed;
  • processing any number of parameters.

In addition to the function itself, other functions located in it also have access to the arguments that are passed to it at the call stage.

Function mainF(p1, p2) ( function childF() ( console.log("p1 = " + p1 + "; p2 = " + p2); ) childF(); ) mainF(3, 5); // p1 = 3; p2 = 5 mainF(4, 7); // p1 = 4; p2 = 7

Default Settings

Starting with ECMAScript 2015 (6), a function parameter can be set to its default value.

For example, let's set the "color" parameter to its default value, equal to "#009688":

Function setBGColor(color = "#009688") ( document.body.style.backgroundColor = color; ) setBGColor(); // background color will be #009688 setBGColor("red"); // background color will be red

Before ECMAScript 2015, you could set the parameter to its default value, for example, like this:

Function setBGColor(color) ( color = color !== undefined ? color: "#009688"; // set color to the default value of "#009688" document.body.style.backgroundColor = color; )

Remaining parameters

If, when calling a function, you pass more arguments to it than it has parameters, then you can get the remaining ones using the so-called rest patameters. This feature has appeared in the language since ECMAScript 2015.

// ...nums - the remaining parameters, which can be accessed in this case by name nums function doMath(mathAction, ...nums) ( var result = 0; nums.forEach(function(value) ( ​​switch (mathAction) ( case "sum": result += value; case "sumCube": result += value**3; break; ) return result; ) console.log(doMath("sum", 3, 4, 21, -4)); // 24 (3 + 4 + 21 + (-4)) console.log(doMath("sumSquare", 1, 4)); // 17 (1^2 + 4^2) console.log(doMath("sumCube", 3, 2, 4)); // 99 (3^3 + 2^3 + 4^3)

return statement

The return statement is intended to return the value or result of evaluating the expression of the current function. The value or expression must be separated from the return by a space. In addition, the return statement stops the execution of the function, i.e. all instructions following it will not be executed.

A function in JavaScript always returns a result, regardless of whether a return statement is used or not.

// function that returns the result function sayWelcome (userFirstName, userLastName) ( if ((!userFirstName) || (!userLastName)) return "Welcome, anonymous user"; else return "Welcome, " + userLastName + " " + userFirstName ; ) // variable declaration person var person; // assign the result of the sayWelcome function to the person variable person = sayWelcome("Ivan","Ivanov"); // print the value of the variable to the console console.log(person); //Instruction that will output to the console the result of the sayWelcome function console.log(sayWelcome("Petr","Petrov")); //Instruction that will output to the console the result of the sayWelcome function console.log(sayWelcome("Sidorov"));

JavaScript - Function with Parameter Checking

// 1. function that does not return any result function sayWelcome (userFirstName, userLastName) ( console.log("Welcome, " + userLastName + " " + userFirstName); ) // let's try to get the result from a function that does not return anything console .log(sayWelcome("Ivan", "Ivanov")); // 2. function containing a return statement without a value function sayDay (day) ( day = "Today," + day; return; //this instruction will not be executed because it comes after the return statement console.log(day) ; ) // let's try to get the result from a function that contains a return statement without a value console.log(sayDay("February 21, 2016"));

JavaScript - Get value from a function that returns nothing

The same result will be obtained if the return statement does not specify a return value.

Function Overloading in JavaScript

Function overloading in programming is the ability to declare several functions with the same names in the same scope. Such functions differ from each other in the type and number of arguments. Each function has its own program logic. Function overloading is used so that similar actions can be performed using a single function name.

The JavaScript language does not support function overloading in the same way as it is implemented, for example, in C-like languages. Those. In JavaScript, you cannot create multiple functions with the same names that are in the same scope.

  • Similar functionality can be implemented in JavaScript using the following steps:
  • To check whether an argument is passed or not, use a condition that checks its value for undefined .
  • To check the number of arguments passed to a function, use the arguments length property of the object.
  • To find out the type of the argument value passed, use the typeof or instanceof operators.
  • To work with a variable number of arguments, use the arguments object.

Starting with ECMAScript6, you can specify default values ​​for arguments.

//declaration of a function that changes the background color of elements function setBgColor(bgColor,elements) ( //if the elements parameter is not specified when calling if (elements=== undefined) ( //then set its value to "div" elements = "div "; ) //get all elements elements = $(elements); //iterate all elements and set them to the specified background color elements.each(function())( $(this).css("background-color",bgColor) ; )); ) /*Call the setBgColor function, specifying one parameter.

Because 2 parameter is not specified, then this function will change the background color of all div elements.*/ setBgColor("green"); /*Call the setBgColor function, specifying 2 parameters.

Because 2 parameter is specified, then this function will change the background color of only the button elements.*/ setBgColor("#ff0000","button");

Let's make some changes to the above code. Namely, we specify the default value for the second parameter:

//declaration of a function that changes the background color of elements //the elements parameter has the value "div" by default function setBgColor(bgColor,elements = "div") ( //get all elements elements = $(elements); //iterate all elements and set them to the specified background color elements.each(function())( $(this).css("background-color",bgColor); ) ) //call the setBgColor function, specifying one parameter setBgColor("green" ); //call the setBgColor function, specifying 2 parameters setBgColor("#ff0000","button");

An example of how in JavaScript you can implement an “overloaded” function that calculates the number of calories a person needs per day:

Recursion is a call within the body of some function to itself.

A function is usually called depending on how it is declared by name or by a variable containing a reference to the function.

Function fact(n) ( if (n === 1) ( return 1; ) return fact(n-1) * n; ) console.log(fact(5)); // 120

You can call a function inside its body not only by name, but also by using the callee property of the arguments object. But it is better not to use this property, because... it is outdated. In addition, in strict mode it does not work at all.

What are built-in (standard) functions?

JavaScript has a huge set of built-in (standard) functions. These functions are already described in the browser engine itself. Almost all of them are methods of one object or another.

For example, in order to call the built-in function (method) alert, it does not need to be declared first. It is already described in the browser. The alert method is called by specifying a name, parentheses, and an argument inside them. This method is designed to display a message on the screen in the form of a dialog box. The text message is taken from the parameter value of this function.

// calling the alert function alert("Some text");