Shortening my IF statement containing both: & and || - javascript

Here's my code:
if(whats.above(x,y)=="g" && whats.onLeft(x,y)=="g") {
$(this).css("border-top-color","green").css("border-left-color","green");
}
whats.above and whats.onLeft can return some letters. In this case, my statement checks if it's going to return g in both cases.
However, I have more letters now, and I want this statement to be true for more of them. Here, there's only one letter, g, but I want some others, for example n. I know I cannot do something like this:
if(whats.above(x,y)==("g"||"n"))
What can I do to minimalize my code in this case?

You could use String#indexOf with a string with the letters.
if ('gn'.indexOf(whats.above(x,y)) !== -1) {

Well, The problem is in your statement is it should be
if(whats.above(x,y)=="g"|| whats.above(x,y) == "n"){ }
For a better solution, I would go with
if (["g","n"].indexOf(whats.above(x,y)) > -1){ }

Related

"Do nothings" as statment in Javascript Condition

I want a ternary operator in JavaScript to return nothing if the statment is false
I have tried this:
1 == 1 ? alert('YES') : '';
But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.
No, use if.
if (1 == 1) {
alert('YES');
}
Don't abuse the conditional operator as a replacement for if/else - it's confusing to read. I'd also recommend always using === instead of ==.
If you really want to do it, && will be one way.
1 == 1 && alert('ALERTED');
1 == 2 && alert('NOT ALERTED');
It is single statement.
A condition after an AND operator is only run if the first is true. So it is like an if statement.
did you try a single line if statement without brackets?
if(1 == 1) alert('Yes');

If statement in a switch

I am working on a question for a course for learning javascript. I am running into trouble trying to add an if statement inside of a switch. I currently have:
var user = prompt("Are you ready for battle?!").toUpperCase();
switch(user) {
case'YES':
if(YES && NO) {
console.log("Great, let's do it.");
} else {
console.log("Bye");
}
console.log("Great! It will be a long exciting battle.");
break;
case'NO':
console.log("Come back when you are ready.");
break;
case'MAYBE':
console.log("Go away. This is only for the brave");
break;
default:
console.log("You obviously do not belong here. It was a simple yes/no question.")
}
The question is this:
Add some if/else statements to your cases that check to see whether one
condition and another condition are true, as well as whether one condition
or another condition are true. Use && and || at least one time each.
The error I am getting is this: ReferenceError: YES is not defined
What can I put in the if's condition to make this work or how do I define YES?
It would appear that you have two problems working against you here.
First is the issue pointed out in comments that you're treating YES and NO like variables, and they aren't. To avoid robbing you of the opportunity to learn by providing a corrected version of your code, I'll only give relevant examples.
var word = "test";
// If we compare against the string literally, it will have an error
// because it's looking for a variable with that name.
if (word === test) { } // ReferenceError: test is not defined
// we fix this by quoting what we're comparing against
if (word === "test") { } // Code inside the block would be executed :)
// But what about checking the value of "test" by itself?
// A string is "truthy", meaning that it passes the conditional test always.
if ("test") { } // Code would be executed always regardless of the content of var word
// Stringing multiple constants together doesn't make sense
if ("test" && "word") { } // This is equivalent...
if (true && true) { } // ... to this, which doesn't make sense
This brings us to the second problem you're trying to solve. The requirements for your problem specify checking if one condition AND another are true, as well as one condition OR another. The problem is that you only have one conditional to check: the status of the variable user.
It only makes sense to test the condition of something if you don't know what it is. Input received from a user is a perfect example. So I'd recommend that you take more inputs from the user such as name, age, gender, shoe size, or anything else. You can then check conditions as follows:
// You would need to store user input in variables username and age previously...
if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); }
// Or to only allow people within an age range...
if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); }
Once you have multiple conditions to check, you can check them anywhere--inside a function, inside a case statement, inside another if. It doesn't matter. Just add an if block and test the conditions. :)

JavaScript Replace function check

I am doing a java script replace as :
var featureTitle;
featureTitle = row.cells[1].text();
if (!featureTitle.indexOf('*') != -1)
{
featureTitle = featureTitle.replace('*', '');
}
Is if (!featureTitle.indexOf('*') != -1) needed check here??
OR replace will take care of it?
replace will do nothing if the asterisk does not exist, so it's safe to call without the check first.
Speaking of which, the check has a bug which makes the code as a whole behave incorrectly:
if (!featureTitle.indexOf('*') != -1) // what's that ! in front doing?
Since !featureTitle.indexOf('*') is always true or false, this condition will always succeed (both booleans compare unequal to -1).
Here is the referenced JSFiddle for you
if (!featureTitle.indexOf('*') != -1){...}
is not mandatory to place, you can do .replace() directly
var featureTitle;
featureTitle = row.cells[1].text();
featureTitle = featureTitle.replace('*', '');
There is no need of that if statement. I think .replace() will take care of it(if *exists it will replace it else no action). If you want to replace all the * in the string then use \g global attribute.
featureTitle = featureTitle.replace(/*/g,'');
replace will work on first occurence of '*'. If there is none, then nothing will be replaced, therefore "if" is not needed

javascript if condition && condition doesn't work

the AND && operator doesn't work, but when i replace it with an OR || operation it is workin, why? I just used OR || operator for testing, what i need is an && operator.
Please help. thanks
function validate() {
if ((document.form.option.value == 1) && (document.form.des.value == '')) {
alert("Please complete the form!");
return false
} else return true;
}
i also tried nested if but it doesn't work too
if(document.form.option.value==1)
{
if(document.form.des.value=='')
{
alert ("Please complete the form!");
return false
}
}
It sounds like || is what you are looking for here. The && operator is only true if both the left and right side of the && are true. In this case you appear to want to display the message if the value is 1 or empty. This is exactly what the || operator is for. It is true if either the left or right is true
If Or operator is working, means there are some javascript errors in your second part of condition. check document.form.des.value=='' (maybe just open your javascript console in Chrome/Firefox/IE8+)
its because one of the conditions specified above returns false and loop breaks. Is you use OR ,only one must be validated and returns true.. check your code for both the conditions.

Regexp Numeric with Single Decimal

I've written the following js with regexp. It works as expected, however I'm looking to simplify it. Could somebody help me out?
.12345 - success
0.12345 - success
12345.12345 - success
0.123456 fail - this I wish was dynamic and not restricted to 5
1.123.45 fail
1.. fail
.. fail
abc - fail
function clearNonNumericChars(field) {
field.val(field.val().replace(/([^0-9\.])/g,""));
field.val(field.val().replace(/^(\d*\.[0-9]{5})\d+$/g,"$1"));
field.val(field.val().replace(/(\.\d*)(\.)$/g,"$1"));
}
Don't deal with numbers as strings.
isNumberValid = function(n) {
return (n == Math.round(n*10000)/10000)
}
You don't need a regex if you don't want one, if you are doing this on keyup. Just filter by keycode/which in your event handler. You've marked the question jQuery, so:
$('input').on('keyup', function (e) {
if ($.inArray(e.which, [48,49,50,51,52,53,54,55,56,57,190]) === -1) {
return true;
}
return false;
});
Note I haven't really tested this, but this basically makes it so the user can't enter anything but numbers or the decimal. Note that they can still paste bad characters in. I'll leave the solution for that to the reader...
Is this what you are looking for? >>
var str = "1a2..b3.C4;56";
str = str.replace(/[^0-9\.]/g,"").replace(/\./,",").replace(/\./g,"").replace(/,/,".");
print(str);
Live test at http://ideone.com/F7wWV

Categories

Resources