DEV Community

astghikaboyan
astghikaboyan

Posted on

Functions in JavaScript

Function in JavaScript is a set of statements that performs a particular task. We should call the function in order for it to execute.
SYNTAX: We define function using function keyword. Then we name the function and open curly braces{}, in which the statements are written.
Let’s declare a very simple function:
function simpleFunction() {
alert(“Hello World!”);
}
simpleFunction() // this will open a window in which will be written Hello World.

  • There can also be parameters in the function. The function definition lists the function parameters between parentheses (). When a function is called, arguments are the values that are passed to it. function anotherFunction(parameter1, parameter2) { console.log(parameter1 + parameter2); } then we call the function anotherFunction with the following arguments: anotherFunction(“Explaining”, “ functions”); // the arguments “Explaining” and “ functions” are the values which are passed into the function above.

When function reaches to any return, it stops executing. In order to return something in functions, we should write it inside the function as follows:
var a = 1;
function sum() {
var b = 3;
return a+b;
}
The function sum returns a+b. However, there is no variable a inside the function. The function works like this: first it will try to find “a” in the function and if it does not find it, it will go up and search for it outside the function.

  • One special thing for functions is that we can declare it once and reuse it. We can call it every time with different arguments and get different results.
  • Each JavaScript function creates a new scope. The variables which are declared inside the function are not visible outside the function.
  • There also exists function composition. We can have functions inside functions.

Top comments (0)