Consider the following code:
if(boolean) return;
What is the purpose if this condition?
Is it logically the same as:
if(boolean) { return true; }
Thank you for answering!
Consider the following code:
if(boolean) return;
What is the purpose if this condition?
Is it logically the same as:
if(boolean) { return true; }
Thank you for answering!
Basically, in the first case you don't care about the return value: return by itself is often used to stop a function when a particular condition is met.
The second case if radically different: return true means you're interested in the return value of a function: for example, a function called isEmpty() that checks if a given list contains at least one element is expected to return a value that can be either true or false. In this case, the return statement alone would have no meaning.
Let consider an example, you have a text box and a submit button. You want to validate the textbox for not being submitted with empty.
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out"); return; }}
Try submitting the form without a value in txt box.
Case 1 (return) : it will show the alert but won't restrict submission. Case 2(return true) : same as above. Case 3 (return false) : finally it will restrict the submission. First to behaves like similar because return; will return undefined which is anything but not false.
Return statement interrupts the execution of function and leave the current function with a value or undefined value.
In First case the return statement interrupts the execution of function and send the Boolean value.
function returnValue(){
return true;
}
returnWithValue();// this function hold the Boolean value
var value = returnWithValue();//true
In second case the return statement interrupts the execution of function and send the undefined value because we haven't provide value. The variable which hold the return value is created but not assigned any value.
function returnWithoutValue(){
return;
}
returnWithoutValue();// this function hold the undefined value because we have not send any value var value = returnWithoutValue();//undefined
In the First Case you are returning undefined, the "if" condition is useless and when no return statement is specified, undefined is returned.
In the Second Case again "if" the condition is redundant when you return a boolean, you only need to return the condition (in this case is also boolean)