What is the JavaScript "return" function for?

One of the functions that I hate the most is the "return" because I do not understand what it does or does not do I will give an example:

var quarter = function(number){
number / 4;
}


if (quarter(12) % 3 === 0 ) {
console.log("A declaração é verdadeira");
} else {
console.log("A declaração é falsa");
}

Well, if you run this code in javaScript it happens that da "the statement is false" being that 12 divided by 4 da the quotient 3, is 3 dividing by 3, da the remainder 0, which should give "the statement is true" but for an obscure reason gives"the statement is false". Now we will do another test:

var quarter = function(number){
 return number / 4;
}


if (quarter(12) % 3 === 0 ) {
console.log("A declaração é verdadeira");
} else {
console.log("A declaração é falsa");
}

Case to the considerate is those who you will not notice, I put the "return" before the variable "number", but for another obscure reason, this example, if it is executed on your computer will give"the statement is true"! since in the first example it only gave "the statement is false!", as only one function changes something that should or should not happen. I want you to explain how variable return works what it does, what it fails to do, all of its functions are its examples of functioning. Besides telling me the reason for the example 1 is 2 to be different. I appreciate it in case leia. but I really need your help please help me! I hope you talk in the chat bye

Author: Tiago S, 2016-06-19

1 answers

return is not a function but rather an instruction (or command/functionality) of functions in many programming languages. What return does is return a value that is the product of the function, and with this stops the rest of the function's processing.

Among the reasons we use functions are complex pieces of logic or need to reuse the same code with different input data. Now the way for the function to return what we want from these pieces of code (functions) is using return.

When a function ends without calling a return the value it leaves or returns is undefined.

Take a look at these examples:

function foo(){
   // sem nada
}

function bar(){
    return 10;
}

console.log(foo()); // dá undefined
console.log(bar()); // dá 10

The difference, as in your example, is that return returns the result of the function. And that result can be saved in a variable! Look at this example:

var a = bar();
console.log(a); // 10

Gives 10 because the return value of the function has now been saved in the variable.

In your first example when you have at the end of the function only number / 4;, without the return, The Interpreter runs this command, or seka calculates the fourth part of number but does not pass this value back to the one who called the function. For this you need return number / 4;

 2
Author: Sergio, 2016-06-19 21:53:11