Is it possible to automatically detect redundant conditional statements? - javascript

In JavaScript, is it possible to automatically detect redundant if-statements so that they can be written more concisely? I want to automatically detect redundant if-statements in the code that I've written, but I'm not sure how feasible it would be to detect redundant if-statements automatically, or whether there are existing source code optimizers for this purpose.
var x = prompt("Enter a number:");
if(x == 5 || x == 10){
}
if(x==5){
console.log("This if-statement is redundant!");
}
if(x == 5){
console.log("This if-statement is redundant! Is there any way to merge redundant if-statements like this one?")
}
if(x==10){
console.log("x is 10.")
}
I tried to remove the redundant if-statements using Google's Closure Compiler (using the advanced optimization setting), but the redundant if-statements still were not eliminated:
var a = prompt("Enter a number:");
5 == a && console.log("This if-statement is redundant!");
5 == a && console.log("This if-statement is redundant! Is there any way to merge redundant if-statements like this one?");
10 == a && console.log("x is 10.");

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');

Syntax for an onChange event

I have an Adobe Acrobat form and I use a small java script to obscure certain areas of the form based on selections in other fields.
if (event.value = "No") {
event.target.fillColor = color.white ;
} else {
event.target.fillColor = color.transparent ;
}
This works ok for me the first time I make a selection but once I select "No" for the first time it doesn't matter if I go in and change my selection, the backgrounds stay white.
I've been told I need to add an onChange event but I have no idea where to start.
Any help will be appreciated.
In JavaScript, = assigns to a value, and == compares against that value, without assigning.
Let's look at the following code:
if (event.value = "No") { }
It works the first time because it assigns event.value to No (regardless of what it was before), and the assignment is successful, so the condition evaluates to true.
It then subsequently succeeds every time for the same reason.
To fix this, you're looking for if (event.value == "No") { }, or the stricter if (event.value === "No") { }, which also checks that event.value matches the type of No.
=== is really important when dealing with numbers, because in JavaScript, a string representation of 1 is not the same thing as an integer representation of 1:
console.log("1" == 1);
console.log("1" === 1);
console.log("1" + 1);
console.log(1 + 1);
Hope this helps! :)

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. :)

&& / || operator strangeness in JavaScript

So, I was working on a project of mine, when I came across a problem like this:
var one = 1;
var two = 2;
var three = 7;
if (one === 1 || two === 2 && three === 3) {
console.log("ok"); // prints out ok
}
I'm pretty confused with this since I don't think it should print out "ok". I thought that since the condition after the && operator was false, it shouldn't run, but I'm evidently wrong. Can anyone clarify why it's working?
In Javascript, operators are not just evaluated left-to-right, certain operators have more precedence than others. Those with higher precedence (in this case, the && operator of precedence 13) will be evaluated before others (||, precedence 14).
For your particular case, you need to group your conditionals in order to achieve the functionality you want:
if ((one === 1 || two === 2) && three === 3) {
console.log("ok"); // prints out ok
}
JSFiddle

Are commas meant to be syntactically valid in Javascript if statements? [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 9 years ago.
The last few days, I've been helping a friend learn Javascript. It's his first language in years and he remembers virtually nothing, so he's been starting pretty much entirely from scratch. He's been going through a simple tutorial and I've been providing him with some exercises to help him practice. The most recent exercise I gave him was the (apparently) classic FizzBuzz problem. He solved it with a bit of help, but he did something very interesting while working out his solution. He came up with the following code:
for (var x = 1; x <= 100; x++) {
if (x%3 == 0, x%5 != 0) {
console.log("Fizz");
}
else if (x%3 != 0, x%5 == 0) {
console.log("Buzz");
}
else if (x%3 == 0, x%5 == 0) {
console.log("FizzBuzz");
}
else {
console.log(x);
}
}
He wasn't familiar with boolean comparison operators, so he didn't use && and instead used commas. My expectation was that it would crash and say something about a syntax error, but to my surprise it ended up running fine and just printing out a bunch of "Fizz" and "Buzz" lines, with no "FizzBuzz" or numbers. Needless to say, I was confused, so I did a bit of experimentation. My first test was to run this:
if (true, true) console.log('true, true');
if (true, false) console.log('true, false');
if (false, true) console.log('false, true');
if (false, false) console.log('false, false');
Which gave me two lines of output:
'true, true'
'false, true'
From that, I made the guess that all comma did was cause it to evaluate nothing but the last expression in the list. I then tried running this code:
for (var i = 0; i < 16; i++) {
if ((Math.floor(i / 8) == 1), (Math.floor(i / 4) == 1), (Math.floor(i / 2) == 1), (i % 2 == 1)) {
console.log(i);
}
}
The output I got was all the odd numbers from 1-15, which confirmed my guess from my first test (since the last boolean in the comma-separated list was flipping every other iteration).
After all that long-winded context, my question is this: Is this comma syntax a known and intentional piece of the Javascript engine, or is it a strange, overlooked quirk of the interpreter? I know commas can be used for a few other things (initializing multiple variables in one line, declaring arrays, and separating parameters jump to mind), but I've never heard of them being used in conditional statements like this in any language, and I'm curious if anyone else knows whether or not this code should even run.
For reference, the FizzBuzz code and the second test I ran were both done using node, and the first test I ran was done in the Javascript console in Chrome, so it doesn't seem to be just a browser- or node-exclusive quirk if indeed it is one. Also, if you actually read this far, thank you.
The comma is an actual operator. It evaluates both of its operands (from left to right) and returns the value of the second operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
Its most common usage is to supply multiple parameters in a for loop, but it can also be used for other purposes.

Categories

Resources