DEV Community

Elina425
Elina425

Posted on

Functions in Javascript

What is a Function?

Function, generally speaking, is a reusable piece of code that is designed to perform a particular task.

It is composed of a series of statements called function body. Values can be passed to a function and the function can/will return a value.

To create a function we can use a function declaration.

It looks like this:

function showRandomStaff() {
  alert( 'Hello everyone!' );
}
Enter fullscreen mode Exit fullscreen mode

The function keyword goes first, then goes the name of the function, then a list of parameters between the parentheses (comma-separated, empty in the example above, we’ll see examples later) and finally the code of the function, also named “the function body”, between curly braces.

function name(parameter1, parameter2, ... parameterN) {
 // body
}
Enter fullscreen mode Exit fullscreen mode

And if I do like this:

function showRandomStaff() {
  alert( 'Hello everyone!' );
}

showRandomStaff()
showRandomStaff()
Enter fullscreen mode Exit fullscreen mode

The call showRandomStaff() executes the code of the function. Here we will see the message two times.

This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.

If we ever need to change the message or the way it is shown, it’s enough to modify the code in one place: the function which outputs it.

Function that does not take a parameter and doesn’t return anything.

function sayHello () {
  console.log("Hello World!");
}
Enter fullscreen mode Exit fullscreen mode

The above function does not take a parameter and doesn’t return a value;

What do I mean when I say, the above function doesn’t return anything?.

If I try to store the result of calling the function in a variable, it will be undefined.

let greeting = sayHello();
// The below console.log will return undefined as the function 
// doesn't return any value.
console.log (greeting);
Enter fullscreen mode Exit fullscreen mode

A function that takes a parameter and returns a value.

Let’s write a function that takes a number as a parameter and returns the square of the number.

function square(number) {
 return number * number;
}
console.log(square(3));
Enter fullscreen mode Exit fullscreen mode

The output of the above function execution is 9.

When a value is passed as a function parameter, it’s also called an argument.

In other words, to put these terms straight:

  • A parameter is the variable listed inside the parentheses in the function declaration (it’s a declaration time term).
  • An argument is the value that is passed to the function when it is called (it’s a call time term). We declare functions listing their parameters, then call them passing arguments.

In the example above, one might say: "the function square() is declared with 1 parameter, then called with 1 argument: number.

Default values
If a function is called, but an argument is not provided, then the corresponding value becomes undefined.

For instance, the aforementioned function square(number) without argument will print undefined.

Differences between Parameters and Arguments

function add(x, y){
    return x + y
}

add(2, 3)
Enter fullscreen mode Exit fullscreen mode

In the above code x and y are parameters while 2 and 3 are the arguments here.

A parameter is one of the variables in a function. And when a method is called, the arguments are the data you pass into the method's parameters.

When the function is called with add(2, 3) the arguments 2 and 3 are assigned to x and y, respectively. This means that in the function, x will be replaced with 2 and y will be replaced with 3.

If the function is called with a different argument, the add function will work the same way. Parameters are like placeholders for function arguments.

The Power of Arguments
We can use arguments more efficiently when we want to make functions more re-useable, or when we want to make calling functions inside another functions more powerful.

Here is an example:

function add(x, y){
    return x + y
}
function substruct(n1,n2){
        return n1 - n2;
}
function multiply(a, b, c){ // a = 1, b = 2, c = 3
    const num1 = add(a, b) // num1 = add(1, 2) = 3
    const num2 = substruct(b, c) // num2 = substruct(2, 3) = -1

    return num1 * num2 // -3
}

multiply(1, 2, 3)
// returns -3
Enter fullscreen mode Exit fullscreen mode

The first function add() has two parameters, x and y and second function substruct() has two parameters, n1 and n2 . The functions returns the addition and substruction of the two parameters.

The second function multiply() has three parameters: inside the function, two variables are declared in it, num1 and num2. num1 will store the value of the result of add(a, b), and num2 will store the value of the result of substruct(b, c). At the end the multiply function will return the value of num1 multiplied by num2.

multiply is called with three arguments which are 1, 2 and 3. add(a, b) will be add(1, 2) which will return 3. substruct(b, c) will be substruct(2, 3) which will return -1.

num1 will have the value of 3 while num2 will be -1. num1 * num2 will return -3.

Arguments are passed in the multiply function which are also used as arguments for the add function and substruct function.

Functions are treated as First-Class in Javascript

Functions are treated as first-class in Javascript because:

  • We can assign a function to variable
  • We can store function in array
  • A function can be passed to another function as argument
  • A function can be assigned to a property of object But let’s see how to assign the above function into a variable and use it.
const square = function (number) {
  return number * number;
}
console.log(square(3));
Enter fullscreen mode Exit fullscreen mode

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned square above).

There may be many occurrences of return in a single function. For instance:

function checkAge(age) {
  if (age >= 18) {
    return true;
  } else {
    return confirm('Your age is illegal for such activities!!!');
  }
}

let age = prompt('How old are you?', 18);

if ( checkAge(age) ) {
  alert( 'Access granted' );
} else {
  alert( 'Access denied' );
}
Enter fullscreen mode Exit fullscreen mode

Now lets see how can we store function in array:

function sum(num1, num3){
   return num1 + num2
}

let myArray = [10,30,sum]
let result = myArray[2](myArray[0],myArray[1])
console.log(result)//40
Enter fullscreen mode Exit fullscreen mode

10 and 30 are integers and sum is a function. So, I'm passing the first and second elements of myArray to myArray[2] which is basically my function sum(). You should expect this function to print the sum of 10 and 30(which is 40).

Passing function to another function as an argument

function inner(name){
    console.log("Hello " + name)
}

function returnFunc(name){
 return name;
}

function outer(myFunc, name){
    myFunc(name)
    return returnFunc(name)
}

let returnVal = outer(inner, "Bob")
console.log(returnVal)
Enter fullscreen mode Exit fullscreen mode

In this case function inner() will become the first argument of function outer().

*Assigning function to a property of object *

let employee = {
name:"James",
printMessage:function (){
    console.log("Welcome dear " + this.name)
}
employee.printMessage;
Enter fullscreen mode Exit fullscreen mode

Here we are assigning function to printMessage, so when we are writing employee.printMessage, it's basically calling the function and printing the message that we have written there.

Understand Function Scope and Block Scope

Function scope
This scope means that the variables are only accessible in the function in which they are declared.

Consider the code below:

function fun()
{
    var temp ="temp is defined in function scope";
    console.log(temp); 
}

fun();
console.log(temp);
Enter fullscreen mode Exit fullscreen mode

When we run the above code, we can see that the console.log(temp) statement outside of function throws an error because the temp variable is not accessible outside the function it is declared in.

Block scope
The block scope of a variable means that the variable is accessible within the block that is between the curly braces.

Consider the code below:

if(true)
{
  let v1 =10;
  let v2=20;
  console.log(v1);
  console.log(v2); 
}

console.log(v1);
console.log(v2);
Enter fullscreen mode Exit fullscreen mode

Here we defined some variables in the if block and printed them to the console.
When you run the above code, you can see that an error occurs while printing the variables v1 and v2. As let variables are block-scope based, v1 and v2 will not be accessible outside the if block.

Remember if you wanna your programming skills work or function nicely you should know how to use functions as there are gonna be at least 80% of your every code!!!

Top comments (0)