Reputation: 506
assuming that an input was not equal to 1 or 2 (e.g. an input of 15), it would go through the loop, return false, but wouldn't that return value be overridden by the 'return true' underneath it that's outside of the for loop?
help to understand this would be much appreciated.
function checkIfPrime(numb) {
if (numb === 1) {
return false;
} else if (numb === 2) {
return true;
} else {
for (let x = 2; x < numb; x++) {
if (numb % x === 0) {
return false;
}
}
return true;
}
}
console.log(checkIfPrime(2));
console.log(checkIfPrime(15));
console.log(checkIfPrime(17));
console.log(checkIfPrime(19));
Upvotes: 0
Views: 94
Reputation: 5500
return
is a terminator so the current code block exits upon meeting the statement
the behaviour you are describing would be created by this code
function incorrectCheckIfPrime(numb) {
var returnValue;
if (numb === 1) {
returnValue = false;
} else if (numb === 2) {
returnValue = true;
} else {
for (let x = 2; x < numb; x++) {
if (numb % x === 0) {
returnValue = false;
}
}
returnValue =true;
}
return returnValue;
}
console.log(checkIfPrime(2));
console.log(checkIfPrime(15));
console.log(checkIfPrime(17));
console.log(checkIfPrime(19));
Upvotes: 1
Reputation: 1922
wouldn't that return value be overridden by the 'return true' underneath?
Well, no. When you return false
the entire function execution stops and the return
value is returned.
You give the example of numb = 15
. Obviously 15 is not a prime number. The function will return false
once x =3
within the for-loop
. At this point the function execution will terminate completely and return the value false
. It will not progress to the return true
statement at all.
For a prime number example, say numb= 17
, the for loop will execute and the if-statement
will never be true. This means the function execution will progress and the return true
statement will be executed, thus making the function return true
.
Check out this W3 Schools documentation for furter explanation of the return
statement.
As T.J. Crowder suggested in the comments, using your IDE's debugger would be useful for you to follow the execution.
Upvotes: 1
Reputation:
return is different from a break; it doesn't just break out of the loop, but return the value for the whole function. Hope this helps.
Gav.
Upvotes: 0
Reputation: 381
when return statement is executed, statements after return are not executed. Program leaves the function and go to the statement calling that function.
Upvotes: 0