Функции в Javascript

Что такое функции?

Функции позволяют группировать операторы вместе для выполнения определенной задачи, все они упакованы в блок кода, который состоит из одного или нескольких операторов в фигурных скобках. Когда вы просите функцию выполнить задачу, это называется «вызовом» функции. Информация, передаваемая функциям, называется параметрами. Вы объявляете функцию, используя ключевое слово function, как показано ниже.

// here we have given the function keyword a name and then written some code in the code block between the curly braces
function sayHello() {
  document.write('Hello!');
}
// here we call the function to print the code
sayHello();

Функциям иногда требуется информация, которая представляет собой значения, хранящиеся в круглых скобках после имени функции. Они могут храниться как значения или переменные. Информация, необходимая для получения значения из переменных, называется аргументами, как показано ниже.

Примечание. Существует разница между аргументами и параметрами. Параметр — это переменная, определяемая функцией, которая получает значение при вызове функции. Аргумент — это значение, которое передается функции.

// the calculatearea() function returns the area to the code that calls it. The values inide the paranthesis are specified because they will be used inside the code block. The area variable inside hold the calculated area of the box.
function calculateArea(width, height) {
  var area = width * height;
  // the return keyword is used to return a value to the code that called it
  return area;
}
// Here we have the declared the function and passed arguments acting as the values for the parameters above
wallOne = calculateArea(3,5);
wallTwo = calculateArea(3,6);
// this displays the answer on terminal
console.log(wallOne, wallTwo);

Функции также могут возвращать более одного значения, используя массив, а затем вызывая его, как показано в коде ниже.

// First a new function is created with the name calculateArea with three parameters
// inside the function we have set variabes with values telling them to multiply
// then we have set a size variable with the previous variable names in an array
function calculateArea(height, width, depth) {
  var area = height * width;
  var volume = height * width * depth;
  var sizes = [area, volume];
  // now we want to return the values
  return sizes;
}
// this areaOne variable holds the value of area as as as the volumeOne
// we give it the function name followed by values we wish to multiply and the number of the array in the sizes variable
// remember that every array starts with 0
var areaOne = calculateArea(2,3,2)[0];
var volumeOne = calculateArea(2,3,2)[1];
// this is used to print the answer on terminal
console.log(areaOne)
console.log(volumeOne)

Операторы функций и выражения

В javascript функции (функции первого класса) являются объектами и, как и любой другой объект, хранятся в памяти; и могут передаваться как параметры, присваиваться как значение переменным.

Существуют различные типы функций, включая операторы функций (объявления) и функциональные выражения (анонимные функции, то есть у них нет имени). Выражение производит значение, тогда как операторы просто работают и не возвращают значения.

Описание функции

// when this was created the function object was put in memory
// it has both a name and a code property
function greet() {
  console.log('hello');
}
// because functions in javascript are objects we were able to give it a property
greet.language = 'english';
// here we have envoked it and the javascript engine begins running
greet();

Выражение функции (анонимно)

// remember when i said functions in javascript are objects? so what we have done is created an object and set it to the anonymous greet variable
// we have an = operator which results in an object being created
var anonymousGreet = function (){
  console.log('hi');
}
// when this is run the javascript engine still creates an object but this time we didn't have a name so it becomes anonymous and we don't need it because we already have a variable that knows where that object lives
// we have invoked the code with the variable and it returns the object, it cannot be called at the top because it will be undefined
anonymousGreet();

Зная, что контекст выполнения сначала помещает переменные и функции в память и выполняет код в однопоточном режиме, если бы мы вызвали anonymGreet(); в верхней части кода вместо нижней части в анонимной функции мы получим ошибку, потому что выражения функции не подняты, движок видит переменную и помещает ее в память и устанавливает ее в undefined, как и все переменные, затем запускает код. Переменная не содержит объекта до тех пор, пока не будет запущен код функции.

Анонимные функции используются для кода, который нужно запустить только один раз в рамках задачи.