Why IF parameters doesn't seems like IF parameters? - javascript

Recently, I came over a script where the if parameters are not evaluated. The code and quantity in the following JScript is not judged on and =, > or < equations.
if (CODE && QTY) {
// do something
}
But as per my understanding, it should be something like this:
if (CODE > 100 && QTY < 200) {
// do something
}
What's the solution?

An if statement is executed if the statement within the brackets evaluates is truthy.
In your first example, // do something will be executed as long as CODE and QTY are truthy values.
This means that both CODE and QTY are checked that they are not:
false
0
"" (empty string)
null
undefined
NaN
It's used more of a validity check to make sure that the variables can be worked with, than a check of the specific values.

Related

Can greater than comparison return anything other than true or false?

I found the following in a code example at datatables.net.
return value > 20 ? true : false;
Why wouldn't they have just written
return value > 20;
Could the latter return values other than true or false? Trying to figure out whether they were maybe just thinking the code was more readable this way, or whether there is actually a significant reason for doing this that I'm not aware of.
The only possible result is true or false. I don't think it makes it more readable. The only reason they may have done it that I can think of is that they were a new developer and didn't realize value > 20 was valid to return.
This is along the same lines as someone writing this:
if(value > 20 === true){ . . . }
Which is unnecessary because if conditions are implicitly compared against their "truthy-ness". The statement should be:
if(value > 20){ . . . }
As such, in your example, the code should just be:
return value > 20;
Because (as you correctly surmize) a greater-than/less-than expression can only result in true or false.
Now, if someone wanted to return an alternate set of binary results, then you could see something like this being used:
return value > 20 ? "acceptable" : "unacceptable";

what would happen if you use two equals rather than only one in your execution block after an if conditional in JavaScript?

I am still learning, so I'm sorry if my question is not well formatted.
I was trying to write a function to insert a word to a string in a specified position, however I made a mistake which is writing two equal signs == rather than one in the execution block and this resulted in wrong output when tested.
However, I already know that the execution of code after if/else needs to not be boolean and I noticed this typo and I corrected it by removing one equal sign and the function worked perfectly fine but I was just left wondering why have I never questioned the significance of strictly having one equal sign when executing code after if conditionals.
so here is the wrong code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position == 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//Wrong output >>>> "We are doing some exercises.JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
and here is the correct code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position = 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//correct output >>>> JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
would you please explain what happens inside my wrong code, like what causes the function to not run properly when booleans were used, obviously the function runs once at a time, so what difference would an absolute value of position make compared to a variable value of position.
Thanks in advance
else if (position == undefined){position == 0}
In your wrong code, position remains undefined since you did not do an assignment, you simply checked if position (which is undefined) is equal to 0
So, when you did var x = original.slice(0,position); slice() simply ignored the 2nd argument, which in this case is undefined and sliced from start to end, which is the default behaviour in case the 2nd argument is not used.
From MDN:
The slice() method extracts a section of a string and returns a new string.
str.slice(beginSlice[, endSlice])
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).
In your case, since you pass undefined (because position == undefined), it's like you omitted it
One equal is to assign values to variables, two equals are for camparing two variables. This is the simplest way to explain it.
= - assigning operator
== - comparing operator
if (position == undefined){position == 0}
This mean if your position is undefined position must be 0. Like it should be 0 but you are not defining it. Two equals is usually use to do comparution actually : does position is equals to 0
However one equal mean you assign the value 0 to position.
I can see two problems in your code.
if (to_insert == "undefined" && position == undefined){return original;}
Here you are checking if to_insert is equal to the string "undefined", but not undefined.
else if (position == undefined){position == 0}
Writing position == 0 will just return a boolean. So in this case, it'll return false (because it execute only if position == undefined returns true).
So it's like if in your code, you had a false between two lines, and you don't change the value of any variable.
else if (position == undefined){position = 0}
By writing only one =, you assign the value 0 to the variable position.
So, when you call the slice() method, the second argument is still undefined, so the method ignore it and just slice the string to the end.
Hope I helped you understand !
You're essentially asking, "What is the difference between using one equals sign (=) and using two equals signs (==)?"
Assume we have the following initialization for both examples:
var pikachu_hp;
One equality sign (=):
pikachu_hp = 50;
This sets the variable, pikachu_hp, to have the Number data type with a value of 50.
Two equality signs (==):
pikachu_hp == 60;
This compares the value (not data type, that's three (===) equals signs in JavaScript) of pikachu_hp against what is on the right hand side; in this case, that's the Number 60. If pikachu_hp has a data value of 60, the expression returns true. If pikachu_hp has a data value of anything else but 60, the expression returns false. Again, I call this an "expression" because it does not equate to anything; it represents either a true or false value.

JavaScript Short Circuit Logic

After seeing some examples online, I've collected two different explanations:
Ex: var x = A || B;
If A exists and B does not, left side is returned.
If A exists and B exists , return right side (last evaluated value).
Based on that logic, I would assume that x would return: v.item(0).click(). But when testing it x first returned B then A, aka fired B then fired A as well. Why? (http://jsfiddle.net/nysteve/QHumL/59/)
HTML:
<div class="indeed-apply-button" onclick="alert('BOOM BUTTON');">boo</div>
<div class='view_job_link' onclick="alert('BOOM LINK');">boo</div>
JavaScript
var v = document.getElementsByClassName('view_job_link');
var i = document.getElementsByClassName('indeed-apply-button');
var x = v.item(0).click() || i.item(0).click();
EDIT 1:02 PM 10/10/2013
Did not mention my true intentions, but based on the answer and discussion, my goal was essentially to convert the following piece of code into the JavaScript code I originally mentioned.
var v = document.getElementsByClassName('view_job_link');
var i = document.getElementsByClassName('indeed-apply-button');
if(v){v.item(0).click();}
else if(i){i.item(0).click();}
else{}
In the code above, how would you read if(v){v.item(0).click();} vs. the short-circuit?
Neither of your two descriptions are accurate.
var x = A || B;
What that does is:
Evaluate "A". Call the result VA.
If VA is not null, undefined, 0, NaN, false, or the empty string, then the value of the overall expression is VA and evaluation stops.
Evaluate "B". Call the result VB. That value, VB, is the value of the expression.
Your test code first tests the return value of calling the "click" function on the first element and then the second. Those functions both return undefined, so the subexpressions on both sides of the || are evaluated. That is, the first call gets VA and it's undefined, so that means that the other side will be evaluated too, and that'll be the value of the expression. (It's going to come out undefined.)
edit — OK now that you've added more to the answer, I think I see what you're up to.
In your actual code (or, I guess, the sample code that's closer to reality), you've got:
if(v){v.item(0).click();}
else if(i){i.item(0).click();}
else{}
That means something quite different than:
var x = v.item(0).click() || i.item(0).click();
Note that in the if statement version, it's explicitly checking "v". A test like that will perform a "truthy/falsy" test on the value of "v". In this case, it's really checking to make sure that "v" isn't either null or undefined. In the || version, however, there's no such explicit test for the "goodness" of variable "v"; it's just used directly. (If it happens to be null there, that'd result in a runtime error.)
A version of the actual code using || and && is possible, but in my opinion the existing code is clearer. However, just for discussion purposes, you could replace the if version with:
v && (v.item(0).click(), true) || i && i.item(0).click();
Personally I think that looks kind-of ugly.

Evaluate prompt value wont

I'm very new to JS - only a couple days in.
Trying to write a very basic prompt evaluated by an if statement.
When I run the code below, the user is prompted, but the statement is never evaluated by the if statement.
Any help? -- I realize the answer is probably simple and obvious, but as a SUPER beginner, what do I do?
var bool = prompt("What is an example of a boolean?");
if (typeof(bool) === "boolean") {
print("correct! that is a boolean");
print(bool) ;
};
In this case, assuming the user inputs something in the prompt, the type of the bool variable will always be a string. You'd rather check if the input compares to the string "true" or "false" etc., like this:
if (bool.toLowerCase() == "true" || bool.toLowerCase() == "false") {
...
}

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

Categories

Resources