DEV Community

Arpine Tadevosyan
Arpine Tadevosyan

Posted on

JavaScript Functions

One of the core components of JavaScript are functions. A JavaScript function is a block of code created to perform a certain task. We can call JavaScript function how many times we want to reuse the code.

The code must accept input and return an output with an evident relationship between the input and the output in order to qualify as a function. A function must be defined someplace in the scope from which it will be called in order to be used.

Function declarations
a function declaration consists of the function keyword, followed by:

  • The name of the function.
  • A list of parameters to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly brackets, { }.
  • Inside the function, the arguments (the parameters) behave as local variables.

Example of a function in JavaScript
// Function to compute the sum of x1 and x2
function sumFunction(x1, x2) {
return x1 + x2;
}

The function sumFunction takes two parameters, called x1 and x2. The function consists of one statement that says to return the parameters of the function (that is, x1 and x2) are added together. The statement return specifies the value returned by the function.

Functions can also be created by a function expression, which can be anonymous. For example, the function square could be been defined as:

const square = function (number) {
return number * number;
}
const x = square(6); // x gets the value 36

However, a function expression may include a name. Providing a name allows the function to refer to itself.

Important: Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called (which is when the function actually performs the specified actions with the indicated parameters)

  • Functions must be in scope when they are called, but the function declaration can be hoisted(means when the declaration appears below the call of the code).

Function scope
From the explanation of the variable, we already know that variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. A function, however, has access to every variable and functions defined inside the defined scope.

Recursion is when the function refers to itself.

There are three ways for a function to refer to itself:

  • The function's name
  • arguments.callee
  • An in-scope variable that refers to the function

Example with a loop.

let x = 0;
while (x < 10) { // "x < 10" is the loop condition
// do stuff
x++;
}

Top comments (0)