What is the "return" JavaScript function for?

0

One of the functions I hate the most is "return" because I do not understand what it does or does not do, I'll give you 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 "The statement is false" being that 12 divided by 4 of the quotient 3, is 3 dividing by 3, of the rest 0, which should give "The statement is true "but for an obscure reason it gives" The Declaration is false. " Now we'll 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");
}

If the attentive are those who will not notice, I put the "return" before the variable "number", but for ANY OTHER REASON, this example, if it is executed on your computer it will give "The Declaration is true"! being that in the first example it only gave "The Declaration is false!", as only one function changes something that should or should not happen. I want you to explain how the variable returns what it does, what it fails to do, ALL its functions are its working examples. In addition to telling me the reason for example 1 is 2 are different. I thank you if you read. but I really need your help to help me PLEASE! I hope to speak in chat bye

asked by anonymous 19.06.2016 / 23:44

1 answer

2

return is not a function but a statement (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 it interrupts the rest of the processing of the function.

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 the function returns what we want from those pieces of code (functions) is by 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 the return returns the result of the function. And this 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 that value back to the caller the function. For this you need return number / 4;

    
19.06.2016 / 23:53