DEV Community

Solomon Obihan
Solomon Obihan

Posted on

An introduction to Javascript and Its Functions.

What are functions?

A function is a block of code created to carry out or execute a given set of tasks.

Functions are critical to solving probems in most programming languages, and Javascript being the language of the web is no exception.

An example of a function is :

function add (a,b) {
return a + b
}
Enter fullscreen mode Exit fullscreen mode

This is a function that enables us to find the sum of a and b.

Now, let us go into the building blocks of a javascript functions.

BUILDING BLOCKS OF A JAVASCRIPT FUNCTION

A function statement is usually made up of three buiiding blocks:

  • The function keyword , function

  • The parameters enclosed in a bracket or parenthesis and separated by a comma when the parameters are more than one.

  • The Javascript statements that defines the function, enclosed in a curly bracelets, {}.

Now,let us look at the prevous example above:

function add (a,b) {
return a + b
}
Enter fullscreen mode Exit fullscreen mode

The parameters of the function above are a and b;

The Javascript statement is everything enclosed inside the curly brackets. It tells the function what to do. It's basically the characteristic of the function.

The return statement

When Javascript reaches the return statement, the function will stop executing and then it specifies a value to be returned to the function caller.
It is said to have completed.

Let us try a proper example:

const addFunc = function add(a, b){
return a + b
}
addFunc(3,2)
Enter fullscreen mode Exit fullscreen mode

On execution, the return statement gives us a value of 5, and the function is said to have completed.

Conclusion

I hope we have succeeded in getting our feet wet with this brief introduction to functions in Javascript.

This is just the beginning, and there are more advanced concepts in functions that we would be looking at in subsequent releases.

In the meant-time, get into your text Editor and start practicing your functions.

Practice makes perfect.

Top comments (0)