JavaScript functions are interesting and important.

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. The web page has JavaScript code , some fragment in which is repeated several times. To avoid this, you can design this fragment as a function, and then call it in in the right places

code by 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's easier to add 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..

Creating a function in JavaScript begins with writing the keyword function, then the name of the function is indicated, then parameters are listed in parentheses x, if necessary, then instructions are indicated, which are enclosed in

braces // function declaration someName function someName() ( alert("You called function someName!"); ) JavaScript - Function declaration syntax Functions of this kind in JavaScript are called function declaration statements. In addition to this type, JavaScript also distinguishes

function

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

Function arguments are values ​​that are passed to the function when it is called. Arguments are separated from each other using a comma.

// call the sayWelcome function passing two arguments to it sayWelcome("Ivan", "Ivanov"); // another call to the sayWelcome function with two arguments sayWelcome("Peter", "Petrov");

Function parameters are one of the ways in JavaScript that you can access arguments within a function. The parameters of the function at the stage of its declaration are described in parentheses. 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 ; )

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 is an opportunity 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 for loop or for...of .

// 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 opportunity appeared in the language starting with ECMAScript 2015.

// ...nums - the remaining parameters that can be accessed in in this case by name nums function doMath(mathAction, ...nums) ( var result = 0; nums.forEach(function(value) ( ​​switch (mathAction) ( case "sum": result += value; break; case "sumCube": result += value**3; break; case "sumSquare": result += value**2; break: result = 0; return result; 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 a value or the result of evaluating an expression 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 multiple functions with same names

in one 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 variable number
  • arguments, use the arguments object.

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

For example, let's create a function that can be called with one or two arguments: //declaration of a function that changes color 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 through 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 the button elements only.*/ 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:

// description of the function function countCal(sex, height) ( // parameters: sex (sex) and height (height) var result; if ((sex === 0) || (sex === "man")) ( result = (height - 100) * 20; ) else if ((sex === 1) || (sex === "woman")) ( result = (height - 105) * 19; ) if (result) ( // arguments - activity level if (arguments) ( result *= arguments; ) console.log("Amount of kcal for normal life: " + result) else ( console.log("Incorrect parameters"); ) ) / * calling a function and passing 2 arguments to it (1 - "man", it can be accessed using the name sex and arguments; 2 - the value 185, it can be accessed using the name sex and arguments) */ countCal("man", 185); /* calling a function and passing 3 parameters to it, although only 2 are present in the function description (in this case, you can get the value of the 3rd parameter only as arguments) */ countCal(0, 185, 2);

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 this property It's better not to use it, because... it is outdated. In addition, in strict regime it doesn't 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. Call alert method is done by specifying a name, parentheses, and an argument inside them. This method designed to display a message on the screen in the form of a dialog box. Text message is taken from the parameter value of this function.

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

JavaScript - Calling the alert function

To quickly perform actions in the browser and not to repeat them, special JavaScript functions have been developed that significantly simplify working with various documents. Using a specific program , you often have to repeat the same action several times. For example, every time a visitor visits a site, you need to run beautiful window

greetings or farewells if the user leaves the site.

And in order not to constantly repeat one action, special JavaScript functions were created. It is worth immediately noting the fact that these functions are the main building material of the program.

JavaScript functions - basic information Functions are a set of specific commands that perform a specific action, for example: subtracting numbers, summing numbers, highlighting square root

. The code that the function contains will only be executed if it is called.

Functions can be placed either in a department called , or in a department - this is the body of the document. However, to be 100% sure that your browser will be able to read the function before it is called, it is best to place it in a section.

Any string functions JavaScript are full-fledged objects belonging to the built-in Function class. Due to this feature, functions have their own specific properties, and they can also be assigned variables.

To perform actions in a program, you can use not only built-in functions such as alert(message) , prompt(message, default) and confirm(question) , but also create your own.

It is important to remember that there are two types of functions:

  • Anonymous;
  • Named.

The difference is that named functions are visible and accessible in any scope, while anonymous functions become visible only after they are called.

For example, you need to display the message “Hello everyone! " To do this, you indicate at the very beginning of the document keyword function , which must be charmingly placed when creating any function, after which you must specify the name as well as the body of the function:

function showMessage () ( alert("Hello Everyone!"); ) showMessage () ;

How to Call a JavaScript Function

Today, there are quite a lot of ways to call a JavaScript function, but this article will discuss only 2 of them, which are the simplest. It is worth noting that there is only 1 function operator.

  • Function Invocation - Function Invocation;
  • Apply And Call Invocation

In the first case, the call is made using the () operator, and the this pattern is bound to the global object . However, if you continually bind in this way, the context may be destroyed:

var value = 500; //Global variable var obj = ( value: 0, increment: function() ( this.value++; var innerFunction = function() ( alert(this.value); ) innerFunction(); //Function invocation pattern ) ) obj. increment(); //Method invocation pattern

The main advantage of the second method is that it allows you not only to run a function, but also to provide it with certain parameters.

In this case, two parameters are used: the object to which this is to be bound, as well as an array that is associated with the parameters:

var add = function(num1, num2) ( return num1+num2; ) array = ; add.apply(null,array); //7

Making a call PHP functions from JavaScript

The syntax of a PHP function is practically no different from a JS function. Many users often have the question of how to call a PHP function from JavaScript.

It is worth noting that it is not possible to do this directly, since these functions are processed different programs. But, if you need to make a PHP function call, then you can use AJAX:

$.ajax(( url:"script.php", data:"id=2", success:function(prin)( $(".data").html(prin); ) ))

In the above example, the PHP function call from JavaScript is made from another file. In this case PHP script a variable is sent, and depending on what it is, the function is run.

We hope you found this article helpful! Good luck!

Good bad

Date of publication: 05/15/2013

Writing something in Java is not so easy, and without basic knowledge you are unlikely to be able to do it. However, if you liked some application written in this language, then you can download it and install it on your website. What it will serve is up to you to decide; maybe it will attract users, maybe it will just decorate, or maybe it will perform some actions. Let's say you downloaded it, now the most main question, how to run a JS script. In this article we will try to answer this question.

In order to connect Javascrip you need to have access to simple html page code. One of the most simple ways– write a command in a tag anywhere inside the page.

How to connect the script anywhere on the site?

Process Java displays The script begins from the time the browser displays your html page, when it encounters a tag, it begins to open everything written in it, executing its code. At the same time, the browser continues to open all the material on the page.
Function parameters are one of the ways in JavaScript that you can access arguments within a function. The parameters of the function at the stage of its declaration are described in parentheses. in this example We will show how the browser will execute the alert function three times, and only after executing this command will it display the rest.

01
02
03 Counting rabbits
04
05
06 for(var i=1; i 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 standard type JavaScript, which is actually an object, and like any other object, functions can be passed 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 be related to 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 . Good style the names of the constructors are considered 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 meaning of this in this case is new object, which you create.

Function calling rule No. 4: When calling a function with operator new, 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 function calls will allow you to improve your JavaScript code. Sometimes errors related to the this value are difficult to catch, so it makes sense to prevent them in advance.

JavaScript code can be run in several ways - from an external file, from an inline fragment in the head section of the page, and directly from an HTML element's event handler. Let's consider all these methods in more detail.

External code

The first and recommended option is to write the code in external file(with a .js extension), which can then be included in our web page using an HTML tag and specifying the location of the file in the src attribute. Availability of JavaScript separate file will reduce code duplication if you reuse it on another page. This will also allow the browser to cache the file on the computer remote client, reducing page loading time.

Embedded code

The second option is to embed the code directly into the web page. This is also achieved using HTML tags, but instead of specifying the file in the src attribute, the code is placed between the tags. While there are cases where it is appropriate to use this option, in most cases it is best to store our code in an external file as described above.

alert("Hello World!");

Attributes

The last option is to use event handler attributes HTML elements. This method is strictly not recommended:

Example



Click Me!

Click Me Too!


Try it yourself » Location

The placement of the previous two options is important and may vary depending on the situation. If you include JavaScript that does not access elements on the page, it is safe to place the script before the end HTML tag. However, if your code will interact with elements on the page, you must ensure that those elements already exist at the time the script is executed. This common mistake can be illustrated with the example below. The script for finding an element with ID hello-world will be executed before the element is defined in the document.

Example





// Attempting to access an element too early
will lead to unpredictable results.
var title = document.getElementById("hello-world");
console.log(title);


Hello World

The way out is to place the scripts at the end of the page before the final HTML tag. This ensures that the elements are already defined when the script is executed.