DEV Community

Veronika Khachatryan
Veronika Khachatryan

Posted on

Learning JS - Functions

What is "Function"?
In JavaScript, a function is a collection of statements that executes an action or calculates a value (same as in maths). Function is a team that we can call when needed. However, to be considered a function, a process must accept input and provide an output.

The function keyword is used to define a JavaScript function, which is then followed by the function's name and parenthesis ().
A function is composed of a sequence of statements called the function body.

Image description

One of the Advantages of Functions is that we can reuse a code. Define the code once, and use it many times. We also can can use the same code many times with different arguments, to produce different results.

How to name a Function?
As in variables, function names can contain letters, digits, underscores and dollar signs. It is better to write a descriptive name for your function. For example, if a function is used to add two numbers, you could name the function "add".

Image description

Function arguments are the values received by the function when it is invoked (called). The arguments are inside the () braces.

We are capable of using the Function as a variable value.
`let x = function() {

}`

Later, we can call the function using the variable like this:
x();

While calling a function x(), we can input a value in the braces such as x(19). In this case, the value 19 will be conveyed to the argument of the function and used for calculating results.

Image description

Also we can have multitude of arguments:

Image description

A specific value from the function is returned to the function caller using the "return" statement. When the return statement is called, the function will end. The code that follows the return statement won't be accessible, thus it should be the last statement of the function.

Image description

Java Script has Function Scope. A new scope is created by each function in JavaScript. A function's declared variables cannot be accessed or seen from outside the function.

Simple right? If you have questions do not hesitate to write me! Thanks for your attention. See you :))

Top comments (0)