DEV Community

Keema
Keema

Posted on

Functions in JavaScript

Function is a piece of code created to preform a certain task. The function structure is built once, then it works every time we "call" it, and produces different results different with arguments.

There are some functions already created in local libraries of JavaScript, such as Math.sqrt(), console.log(), alert(), toString(), etc.

Yet we can create functions for the particular project.

Functions have certain design which we need to use to declare them. It has the following stracture:

              function name(argument) {
                          statements
                       }
Enter fullscreen mode Exit fullscreen mode

We write function, give it a unique name, argumennt(s) (if necessary) in the brackets, then, inside the curly brackets, we write the code that defines the function, which should work every time we call the function.

In the code there may be used the given arguments, which are new variables created within the function. Inside the function, the arguments behave as local variables and the change is not reflected globally. The function may also not require arguments and work without them. In this case the brackets are left empty.

After the necessary code that should be working when we call the function is written inside the function and we want to give back some value out of the function, we should return that value. For that, at the end of the function, we write return and add the value that should be returned.

                function sayHi(name) {
                        return "Hello " + name;
                          }
Enter fullscreen mode Exit fullscreen mode

A function can return only one value. If additional returns are added, JavaScript will just ignore them.

When the function is ready, we can call it every time we need it by writing the function name and adding the brackets, necesserally with the arguments:

          function sayHi(name) {
                        return "Hello " + name;
                          }

          let firstHi = myFunction(Kima);
          console.log(firstHi);
Enter fullscreen mode Exit fullscreen mode

As a result in a console we'll have printed Hello Kima.

Functions can be used in all types of formulas, assignments, and calculations.

          let x = German(library);
          let text = "This word is " + x + " in German";
Enter fullscreen mode Exit fullscreen mode

or we can use the function directly in the variable:

  let text = "This word is " + German(library) + " in German";
Enter fullscreen mode Exit fullscreen mode

Top comments (0)