I'm trying to write a function that checks whether a value is odd or even, but it isn't quite working as it should, or rather, at all.
The code I got was from this question.
function isEven(value) {
if (value % 2 == 0) {
return true;
console.log("True");
}
else {
return false;
console.log("False");
}
console.log(value);
}
isEven(3);
I get no errors in the browser's console, but it also does not log True, False, or value.
Note: I will also accept jQuery solutions, but would prefer Javascript.
You are returning before logging. Anything after return will not be executed.
return after logging
function isEven(value) {
if (value % 2 == 0) {
console.log("True");
return true;
} else {
console.log("False");
return false;
}
}
isEven(3);
Ensure value is an integer first by parsing it with
parseInt(value)
Related
The isEmpty() algorithm is asking me to return true when the stack contains no values and to return false when stack contains one or more values. it also asks to complete this without modifying the stack
i can only use 3 methods
.pop() which pops the top value of the stack
.push() which pushes a value on to the stack
.peek() which shows me the top value of the stack without modifying the stack
i tried doing the algorithm this way but it only completed the last two requirements which where to return false when the stack contains one or more values and to not modify the stack but it wont return true when the stack contains no values enter image description here
function isEmpty(stack) {
if(stack!==''){
return false
}else if(stack===''){
return true
}
}
function isEmpty(stack) {
if (stack.peek() === undefined) {
return true;
} else {
return false;
}
}
OR
function isEmpty(stack) {
return stack.peek() === undefined;
}
Here is one way you could use the peek() method to solve this problem:
function isEmpty(stack) {
if(stack.peek() === undefined){
return true;
}else{
return false;
}
}
Another approach is to use the pop() method, but you will have to add the values again to the stack:
function isEmpty(stack) {
var temp = stack.pop();
if(temp === undefined){
return true;
}else{
stack.push(temp);
return false;
}
}
just check if the peek() function is equalto undefined
function isEmpty(){
return peek() == undefined;
}
I have this funtion
function riddle (parme) {
if(parme !== parme) {
return true;
}
return false;
}
when will it return true (I dont know the language)
There is only a single value in JS which is not equal to itself which is NaN. Rest in all cases, it will print false
To check for NaN equality, You should use isNaN
function riddle(parme) {
if (parme !== parme) {
return true;
}
return false;
}
console.log(riddle(NaN));
$("#submit").click(function()
{
function checkZeros()
{
if ([0] == 0) {
if ([1] != '.') {
alert("alert message");
return false;
}
}
}
checkZeros($("#user-input-currency").val());
if(!$.isNumeric($("#user-input-currency").val())) {
alert("Please provide price in numeric value");
return false;
}
})
I have function that checks if user-input-currency first number is 0 followed with '.' if not then gives alert, and returns false so the user can input right value. but in my case I get the alert message but page still refreshes.
what could be the problem here?
The next code that checks isNumeric works correct returns alert message and doesnt refreshes page.
Your return is in another scope than your click handler, so even if checkZeros returns false, your click handler wont stop.
You can use the following instead:
if(checkZeros($("#user-input-currency").val() === false)) return false;
The strict comparison here is used since your function doesn't have a return trueand functions returns undefined by default.
You can, for a better readability, change your function so it always returns a boolean and simplify your if to:
if(checkZeros($("#user-input-currency"))) return false;
p.s.: your code doesn't make sense, is it pseudo code?
Your click handler callback is not returning any value as only the checkZeros function is returning false value.
So you have to return the value which checkZeros function is returning to the click handler so that it won't proceed to submit.
$("#submit").click(function() {
function checkZeros() {
if ([0] == 0) {
if ([1] != '.') {
alert("alert message");
return false;
}
}
}
if (!$.isNumeric($("#user-input-currency").val())) {
alert("Please provide price in numeric value");
return false;
}
// in your case checkZeros function returns false, a function explicitly returns undefined if you haven't return any value, so you have to use conditional operator here
return !checkZeros($("#user-input-currency").val()) ? false : true;
})
I'm reviewing some code where the logic looks flawed. I'm not sure if the following code will ever return false because of the if else return flow. My question is, will the following code ever return false, or even throw an error?
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
var select = document.getElementById("selectmenusearch");
var selected = select.options[select.selectedIndex].value;
if(selected === 'organisation') {
submitSearchForm('<%= doOrganisationSearchURL %>');
} else {
submitSearchForm('<%= doIndividualSearchURL %>');
}
} else {
return false;
}
return true;
}
So the flow to me looks like
if (this condition is true) {
//execute some code
} else {
return false
}
else return true
NB: I know it would be better to refactor to have only one return statement but it looks to me like there are two else statements.
It depend of e.keyCode but if e.keyCode is not always equal to RETURN_KEY_CODE it will not always return false. You have 2 return. The first one is in the else of the first if so if e.keyCode !== RETURN_KEY_CODE, false is return. Else, you if will end normally and the instruction after it is return true.
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
return true; // RETURN_KEY_KEYCODE === e.keyCode
}
I don't see any wait it can alway return false if e.keyCode is not always the same value. :)
If you want to make it more clear, you can just put the return in the end of the first if. Like that:
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
return true; // RETURN_KEY_KEYCODE === e.keyCode
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
}
Just run a test. Seems like you were confused with what happens when there is more than one "return" statement in a function.
A return statement is a regular statement, just like any other - except for the fact that it will interrupt the local block execution and return flow control to the code that called the function. It is indifferent for you the fact that you have one, two, three returns... the language interpreter strictly follows the IF/ELSE rules - if a condition is met, then the block (delimited with "{ }" defined immediately under the if is the one that is executed, if the condition is not met, then the respective if's else block is executed. Whatever is the case, both if and else blocks, upon reaching their ends, will return flow to the next statement right after the if block (the if block is comprised by the if + else blocks), in the example here, "return true".
(function() {
if (k) {
console('k renders true');
}
else {
console.log('else reached');
return false;
}
return true;
console.log('bottom return true reached');
})();
I want to use return false to break a .each() but also return a value at the same time. How can I do this?
Please refer to a work-around function to see what I am trying to do:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store) {
if (state == store.state && store.category == "meyers") {
statehasstores = true;
return false; // break
}
});
return statehasstores;
}
What Id like to do in pseudo code is:
Function () {
for() {
if found {
return true;
}
}
return false;
}
You're doing it right...
Quote from http://api.jquery.com/each/
"We can stop the loop from within the callback function by returning false."
Be creative:
try {
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
throw store;
}
});
}
catch(e) {
// you got e with the value
}
No, I was just kidding, don't use this :). It came as an idea I liked to share.
Use a variable outside the loop to get the value and use it afterward.
var value;
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
statehasstores = true;
value = store; // added line
return false; //break
}
});
alert(value);
The way you're doing is just fine. I've tested on jsFiddle, see an example here.
It's not working for you? Can you show more context?
jQuery .each
Alternatively, you could use a for loop instead of each(), and just return the value.
What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.
How about:
$.each( myObj, function( key, value ){
...
if( sthg... ){
myObj.somethingWentHorriblyWrong = true;
return false;
}
});
if( myObj.somethingWentHorriblyWrong ){
// ... do something, not forgetting to go:
delete myObj.somethingWentHorriblyWrong;
}
PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page, "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...
PPS Need a function that returns a value? Wrap in an outer function of course.
Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :
When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :
Function () {
for() {
if found {
return true;
}
}
return false;
}
This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.
So to make your function work as you whish I propose to do so :
Function () {
variable found = false;
foreach() {
if found {
found = true;
return false; // This statement doesn't make your function return false but just cut the loop
}
}
return found;
}
Of course there are many other ways to perform this but I think this is the simplest one.
Coopa - Easy !
As others have noted from jQuery Each, returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store){
// continue or break;
statehasstores = !(state == store.state && store.category == "meyers"))
return statehasstores;
});
return !statehasstores;
}
This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.