In this lesson we will delve into the functions in JavaScript, already introduced in the previous lesson. The lesson can be consulted at the following link: introduction to functions.

functions in JavaScript – examples

In particular, in this example I propose a demonstration of how it is possible to use multiple returns. So let’s create a function named isPositivo and return a value depending on the result of our conditional statement contained within the function.

We therefore pass a number a as a parameter. After, if the number is positive, the function returns 1, if it is null it returns 0, otherwise if it is negative it returns -1.

This is an example of functions in JavaScript:



function isPositive (a) {
  if (a> 0) {
    return 1;
  }
  else if (a == 0) {
    return 0;
  }
  else {
    return -1
  }
}

So we call the function, passing as a parameter, for example, the number -6. We store the return value in a variable named result. Finally we print the result obtained in the console.log().



var result = isPositive(-6);
console.log(result);

In this case we display the value -1 in our console.

Of course, you can return any value, even a string.

So, this is another example of using functions in JavaScript:



function isPositive(a){
  if (a > 0){
    return 'Positive';
  }
  else if (a == 0){
    return 'Null';
  }
  else {
    return 'Negative';
  }
}

var result = isPositive(-6);
console.log(result);

The same function could be written using a variable that for example I set to an initial value. Then only if certain conditions occur I change the value.

Here is a possible change to the previous function, using a string:



function isPositive(a){
  var result = 'Negative';
  if (a > 0){
    result = 'Positive';
  }
  else if (a == 0){
    result = 'Null';
  }
 return result ;
}

var result = isPositive(-6);
console.log(result);

So I change the value of the variable only if the number is positive or null.

Note that the variable result contained within the function is not visible externally. In fact it is a local variable of the isPositivo function. So I can use the same name to store the return value from the function.

Conclusion

In this lesson we have developed a simple example of a function with the possibility of handling different returns, in the next lessons we will talk more about functions in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts