functions in JavaScript

testYourselfJavaScript JavaScript function1348 3 0

The function is one of the basic components of any programming language. A function is a block of code designed to perform a specific task or perform specific calculations.

The advantage of the function is that you can write it once and call it many times at any time without duplicating the same code. It can receive inputs and generate outputs. Using the function, you can use different arguments to get different results.

All programming languages allow you to write and use your own functions.

Functions in JavaScript can additionally be nested (a function can have one or more internal functions).

Predefined functions in JavaScript

JavaScript provides many predefined functions that allow you to achieve a specific result. You may have already seen some frequently used functions in JavaScript such as alert(), prompt(), confirm() or parseInt().

parseInt(5.34); //5

Creating functions in JavaScript

There are several ways to define functions in JavaScript: function declaration, function expression, and arrow function. Let's start with the function declaration. To define a function in JavaScript using a function declaration, use the function keyword, followed by the name, round brackets, and finally the function code, also called the function body. The function body is surrounded by curly brackets.

function print() {
    console.log('Hello World');
}

In addition, the function name should be unique. If we create two functions in JavaScript with the same names, the second will overwrite the first.

function print() {
    console.log('abc');
}
function print() {
    console.log('xyz');
}
console.log(print()); // 'xyz'

Using functions in JavaScript

Defining a function does not call it. Defining simply creates a function with a specific name, specifies what arguments to expect, and what to do when the function is called. To perform a function in JavaScript, you must call it with round brackets.

function get() {
    return 100;
}
get(); // 100

Accessing to a function without round brackets returns only its definition.

function get() {
    return 100;
}
console.log(get); // ƒ () {return 100;}
get(); // 100

Remember that the function you want to call must be in the scope in which it will be called, otherwise it will not be available.

Parameters and arguments

Parameters

A function can have zero or more parameters. Multiple parameters are separated by commas. Parameters are declared in round brackets in the function definition.

function welcome(firstName, lastName) {
    return 'Hello ' + firstName + ' ' + lastName;
}
welcome('John', 'Smith'); //"Hello John Smith"

You can pass more or less arguments than defined. If you pass less arguments, the rest of the parameters will return undefined.

function welcome(firstName, lastName) {
    return 'Hello ' + firstName + ' ' + lastName;
}
welcome('John'); //"Hello John undefined"

If you pass more arguments, additional arguments will be ignored.

function welcome(firstName, lastName) {
    return 'Hello ' + firstName + ' ' + lastName;
}
welcome('John', 'Smith', 40); //"Hello John Smith"

You can pass any value, not just primitives values (e.g. array, object, function).

function getSize(arr) {
    return arr.length;
}
getSize([5,9,4]); // 3

Some people have trouble distinguishing parameters from arguments. Parameters are used when defining a function, and the arguments are the values ​​received by the function from each parameter when the function is called.

Default values

If you want the arguments to have their default values, if no value is given, then there are two ways to achieve this.

The new way is to use the default parameters of ES2015 (ES6).

function multiple(x, y = 1) {
    return x * y;
}
console.log(multiple(5)); // 5

The old way is an alternative way to set defaults and is very useful when you want to support old browsers that don't support ES6 default parameters.

function multiple(x, y) {
    y = y || 1;
    return x * y;
}
console.log(multiple(5)); // 5

Arguments object

Inside each function (except the arrow function), JavaScript provides an array-like object called arguments. The arguments object stores the values ​​of each argument passed to the function.

function foo() {
    console.log(arguments); // [1,3,5]
}
foo(1,3, 5);

You can access its values using the index, the same as you can access array elements, however this object does not support array methods such as join(), push(), forEach() etc.

function foo() {
    arguments.forEach(function (el) {
        console.log(el);
    });
}
foo(1,3, 5);

The above code will return an error similar to the one below:

Uncaught TypeError: arguments.forEach is not a function

Although the arguments object has no methods, it can be iterated through a loop and has the length property.

function foo() {
    for(var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}
foo(1,3, 5);

the result of the above code will be:

1
3
5

Inside a function, the arguments object behaves like a local variable (there are not available outside the function).

return statement

Each function can return one value using the return keyword. If the function has no return statement, it returns undefined.

function getDiscount() {
}
console.log(getDiscount()); // undefined 

The return statement is optional, and when the JavaScript reaches the return statement, the function will end. Usually the return statement is the last statement in the function. The value returned by the function is returned to the object calling the function.

function getDiscount() {
    return 10;
}
console.log(getDiscount()); // 10

It is possible to use an empty return statement, which is equivalent to returning undefined, which immediately exits the function.

function getDiscount() {
     return;
     console.log('calculate discount'); // won't be executed
 }

The first return statement immediately terminates the function, so console.log will not be executed at all.

You are not limited to returning only primitive types. You can return object, array, other function and many others.

There can be multiple return statements in one function.

function getDiscount(count) {
    if (count > 50) {
        return 20;
    }
    if (count > 30) {
        return 10;
    }
    if (count > 20) {
        return 5;
    }
}

Also, remember to never add a new line between the return statement and the returned value. If there is no semicolon after the return statement, JavaScript will add it automatically.

function getDiscount() {
	return 
	10;
}
console.log(getDiscount()); // undefined

Function expression

The second way to create a function is to use a function expression. JavaScript allows you to assign a function to a variable and then use that variable as a function.

var divide = function(a, b) {
     return a / b;
 }

By default, a function created using a function expression is an anonymous function. However, it may have a name that will allow the function to reference to itself and also help idenity the function during debugging.

var divide = function divide(a, b) {
     return a / b;
 }

Arrow function

An arrow function has a shorter syntax than a regular function expression and does not have its own this and the arguments object.

var devide = (a,b) => a / b;

Function scope in JavaScript

Each time you create a new function in JavaScript, all variables declared in this function become local to that function and belong to the scope of that function. Variables defined in the function are not accessible from the outside.

function getUserId() {
    var userId = 2;
    return userId;
}
console.log(getUserId()); // 2
console.log(userId); // ReferenceError: userId is not defined

This allows you to use the same variable name in different functions.

function getUserId() {
    var userId = 2;
    return userId;
}
function getId() {
    var userId = 5;
    return userId;
}
console.log(getUserId()); // 2
console.log(getId()); // 5

In addition, the function can access all external variables and functions defined in the scope in which it is defined.

var userId = 2;
function getUserId() {
    return userId;
}
console.log(getUserId()); // 2

A function defined in the global scope can access all variables defined in the global scope.

The outer variable is only used when there is no local variable. If a variable with the same name is declared in the function, it shadows the outer variable.

var userId = 2;
function getUserId() {
    var userId = 5;
    return userId;
}
console.log(getUserId()); // 5

A function defined in another function has access to all variables defined in the parent function and any other variables to which the parent function has access (e.g. global scope).

var userId = 2;
function login() {
    var userName = 'Kate';
    function getUserId() {
        return {id: userId, name: userName};
    }
    console.log(getUserId()); // {id: 2, name: "Kate"}
}
login();

Local variables are created when the function starts and deleted after the function ends.

Summary

  • JavaScript provides many predefined functions – alert(), confirm(), prompt().
  • There are several ways to define functions in JavaScript:
    • function declaration
    • function expression - assigning a function to a variable
    • arrow function - does not have its own this and arguments object
  • to execute a function in JavaScript, you must call it with round brackets
  • parametrs and arguments
    • the function can have zero or more parameters, which are defined in round brackets
    • parameters without values will be an undefined value
    • if we pass more arguments, additional arguments are ignored
    • arguments can have default values
    • arguments object - contains the values of each argument, does not support array methods, it can be iterated through a loop, and has the length property
  • return
    • if the function has no return statement, it returns undefined
    • one function can contain multiple return statements
    • you can use an empty return statement to end the function immediately
  • function scope
    • variables declared inside a function become local to that function and are not accessible from the outside
    • the function can access variables and outer functions