DEV Community

Lilit Babakhanyan
Lilit Babakhanyan

Posted on

Functions in JavaScript

Functions are one of the fundamental pieces of JavaScript. A function is a set of statements or a piece of program that performs some task or calculates some values. For that block of code to qualify as a function, it should take some input and return an output.

A function statement consists of the keyword function followed by the name of the function, the parameters of the function in parenthesis (), and JavaScript statements that define the function in curly brackets {}, and the block of code within those curly braces is called the body of the function. For example,

function sum(a, b) {
return a + b;
}

Here the function sum takes two arguments, a and b. The function consists of one statement which says to return the sum (+) of the two arguments.
We just defined a function, but only defining it does not execute the function. It shows what to do when the function Is called. Calling the function performs the statements that are in our function. For example,

function sum(a, b) {
return a + b;
}
console.log(sum(2, 3));

// this will print 5

So what we did is the following. We called the function sum by writing it out and gave two arguments, 2 and 3, to our function. So when we console.log it, it will print 2 + 3, which is equal to 5.

Function scope
Variables declared in a function cannot be accessed anywhere outside the function because the variable is defined only in the scope of that function. In contrast, a function has access to all variables and functions inside the scope that it is defined. For example,

const x = 5;
const y = 10;
function multiply() {
return x * y;
}

multiply(); // returns 50

The constants x and y were defined in the global scope, and the function multiply had access to them; that is why when we called the function, we got x * y = 5 * 10 = 50.

Top comments (0)