Even if, IF condition is false why statement executes in Javascript? - javascript

This is my code,
columnLength = tColumns.length;
if (parseInt(columnLength) ==2) {
tColumns[0].parentNode.insertBefore(tD, tColumns[0].nextSibling);
}
if (parseInt(columnLength) >= 3)
{
tColumns[0].parentNode.insertBefore(tD, tColumns[0].nextSibling);
tColumns[0].parentNode.insertAfter(tD, tColumns[0].nextSibling);
}`
Suppose columnLength is 1.. 1st IF condition is false and its not executing the inside statements.
Even 2nd condition is false since 1 is not greater than equals to 3, but the statements are being executed!
What is wrong with the code?
I'm using Visual Studio IDE to debug, even in immediate window also IF condition returns false as shown below.

ONTOPIC :
I assume your tColumns.length might not have the value you expect it to have. I guess it has the value of undefined which can not be parsed as an integer.
http://jsfiddle.net/FRXkM/1/
OFFTOPIC :
Might not be related to your problem. But parseInt requires a second parameter in conventional ways.
For example:
parseInt("34", 10);
For info on parseInt and its parameters go to http://www.w3schools.com/jsref/jsref_parseint.asp

Related

Use if-loop to calculate price depending on the input in js

I'm pretty new to Javascript and React, so please bear with me.
I have a component in my app, that is taking a timespan from the user, but now I want to calculate the price the user would have to pay, depending on their input. I figured that it would probably be the easiest way to use an if loop but something is very off with that and I am a little stuck.
Is my attempt okay in general or does it need a separate function that I have to call in order to do what I want to do?
onConfirm(hour, minute) {
this.setState({ time: `Dauer: ${hour}:${minute}` });
this.setState(if((hour) < 4){return price = `Preis: (${hour}* 1.5) €`;}
else {return price= 'Preis: 5.50 €';} );
this.TimePicker.close();
}
Within an object literal, you can't use statements, only expressions. if is a statement.
If you want to do that either/or logic in an expression, you use the conditional operator (? :), like this:
onConfirm(hour, minute) {
this.setState({
time: `Dauer: ${hour}:${minute}`,
price: hour < 4 ? `Preis: (${hour}* 1.5) €` : 'Preis: 5.50 €'
});
this.TimePicker.close();
}
The conditional operator expression in the above is:
hour < 4 ? `Preis: (${hour}* 1.5) €` : 'Preis: 5.50 €'
It's a ternary operator (an operator accepting three operands):
The condition to test (hour < 4)
The expression to evaluate if the condition is truthy¹ (`Preis: (${hour}* 1.5) €`)
The expression to evaluate if the condition is falsy¹ ('Preis: 5.50 €')
Also note you had a closing ' on a template literal (needed a backtick instead).
¹ "truthy" and "falsy" - JavaScript implicitly converts (or coerces) values. When you use a value as a test, such as in an if or a conditional operator, JavaScript converts the value you provide to a boolean value (true or false). Values that convert to true are called "truthy" values, ones that convert to false are called "falsy." The falsy values are NaN, null, undefined, 0, "", and of course false (on browsers, document.all is also falsy for various reasons I explain in my book). All other values are truthy.

js shorthand if/else within echo

What am I doing wrong here? No matter what the value of response.count it always outputs the second condition... 'entries have'. I am familiar with doing this in php, but either I am overlooking something or it is different in js.
response.count is returning correct values...
if (response.success)
{
// show success message
$("#dtAlert").html('Success! \'<b>'+response.count+'</b>\' selected '+(response.count === 1 ? 'entry has' : 'entries have')+' been deleted from your account.');
}
Is the result 1 or "1"? The === operator compares the type of value. Try to change to ==.
See working here: http://jsfiddle.net/aLh4s/

What's wrong with my logic? (JS string Length)

A couple days ago, on a site that I'm the only author on, I added this code to a script:
if (PowerArray[0][0].length < 1);
{
return false;
}
and everything worked fine. When PowerArray[0][0] was "70", the script ran. When PowerArray was empty, the script didn't run past the above quoted line.
This is no longer true. For the life of me, I can't figure it out. I tested with variants of the code, like below:
if (PowerArray[0][0].length < 1);
{
alert(PowerArray[0][0].length);
return false;
}
and set PowerArray[0][0] = "70". When I run the code, I get an alert with "2" in the text. This is the only place that I have an alert in the script. What's going on here, and how do I fix it?
Note: The expected behavior is, of course, no alert, because "70" has a length of 2, and shouldn't trigger the truth of the if.
Edit: 1) Yes, the False in the first block was a typo. It's been corrected. 2) The expected behavior was for it to stop processing if (and only if) PowerArray[0][0].length was 0. 3) I had previously initialized PowerArray as an empty array, and then copied an array (which had the potential to be empty) into it.
You should remove semicolon from if statement, it terminates your statement there.
And yes, when your PowerArray is empty,
PowerArray[0][0] will throw an undefined error,
So should put a null check for that as well.
when PowerArray is empty PowerArray[0] gives undefined then you will get an error for PowerArray[0][0] saying TypeError: Cannot read property '0' of undefined that is why the script is nor running after that line
if (PowerArray && PowerArray[0] && PowerArray[0][0] && PowerArray[0][0].length < 1)
{
return false;
}
I think the semicolon after the if is the issue.
I would also check if PowerArray is a valid 2D array implementation.
Check this link for ideas How can I create a two dimensional array in JavaScript?
Start by changing it to this if (PowerArray[0][0].length < 1)
try this
if (PowerArray[0]) {
if (PowerArray[0][0].length < 1) {
return False;
}
}

Strange result while using Javascript not operator

Before anyone jumps in to answer and bash me for asking a silly question; I'm aware of what the not operator does, at least in other languages it should invert a result from true to false and vice versa. The thing I'm stuck on is the strange behavior I get from time to time. I.e. I had this in my code. It's not doing what I expect it to do.
_checkOnOff: function(inst) {
return (!$.suggestBox.onOff || !$.suggestBox._get(inst, 'onOff')) ? false : true;
},
The actual values for the 'onOff' variables that I'm dealing with here are 0 and 1. I'm assuming that the '!' operator will reverse them.
However I couldn't get it to work until I changed the function to explicitly state '== 0' like so...
_checkOnOff: function(inst) {
return ($.suggestBox.onOff == 0 || $.suggestBox._get(inst, 'onOff') == 0) ? false : true;
},
Edit: Added info Both $.suggestBox.onOff and $.suggestBox._get(inst, 'onOff') will be either 0 or 1.
My question is why didn't !$.suggestBox.onOff produce true when $.suggestBox.onOff was equal to 0? Is Javascript ! equivalant to the bitwise operator?
Edit: Second attempt
I tried using '!!' like was suggested (to get a bool) and found nothing changed. Here is the code and outputs:
console.log('val: ' + $.suggestBox.onOff); // outputs: 0
console.log('! : ' + !$.suggestBox.onOff); // outputs: false
console.log('!! : ' + !!$.suggestBox.onOff); //outputs: true
console.log('!!! : ' + !!!$.suggestBox.onOff); //outputs: false
The output doesn't change if $.suggestBox.onOff is 1 or 0!!! it's still false, true, false. What is going on?!
Edit: Third attempt I found out that it has something to do with my variable. I don't know how, but it has to do with the way that it has been set. Ok, prepare yourselves, what I'm about to tell you, may very well blow your mind and change the way you type on the keyboard. It's that incredible:
//this.onOff = 0;
console.log('this.onOff: ' + this.onOff); //output: 0
console.log('! : ' + ! this.onOff); //output: false
console.log('!! : ' + !! this.onOff); //output: true
If I uncomment out the 'this.onOff = 0', thereby explicitly assigning this.onOff to a literal, it changes the output to:
0
true
false
I just found out why. I will write it down in the answer section. Small clue is that it's the way the variable $.suggestBox.onOff was set.
It seems that $.suggestBox.onOff is set with "0" as a string, which in JavaScript is always truthy.
Since "0" is truthy and 0 is falsy, you'd expect 0 == "0" to be false, but it's not.
Try the following in your console:
!! "0"; // true
!! 0; // false
0 == "0"; // true
Weird? Yes. Welcome to the awkward world of JavaScript!
To get around this issue, you should either have $.suggestBox.onOff be an actual number, or convert it on the fly:
_checkOnOff: function(inst) {
return !! ( +$.suggestBox.onOff && +$.suggestBox._get(inst, 'onOff') );
}
Update: Since you pointed out in the comments that you're setting it by a text value, use this when setting it so that it's always set as a number:
$.suggestBox.onOff = +$(this).val();
I think you're confused, because you're negating a string, not a number. Strings are a bit different and handled a bit funny when it comes to their evaluation as a boolean.
!0
is true, as expected.
!"0"
is false... so, the question, is "0" truthy?
I wish I had a better source (sitepoint isn't bad, but it's not as authoritative as a w3 document), but, according to http://www.sitepoint.com/javascript-truthy-falsy/
The following values are always falsy:
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
All other values are truthy, including
"0" (zero in quotes), "false" (false in quotes), empty functions,
empty arrays, and empty objects.
So, what you are seeing is indeed expected.

If statement condition is met, but contents not executed?

I've got an two if() statements, for which the conditions are both met with the default values in the <select> and <input> form fields I've tested this by assigning the values to a variable and writing the variable. (0 and Url).
However, it seems that neither if() statement's contents execute properly.
Here's a link to my JSFiddle: http://jsfiddle.net/cfRAk/2/
Any edits/answers as to why this is happening would be greatly appreciated!
Change this line:
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
To this:
var geo_select_val = parseInt($('select[name=g_country\\[1\\]]').val());
The thing is geo_select_val is actually "0" and not 0. Converting a string to boolean will only result in false if string is empty. "0" is not empty, so it was being evaluated as true. Since you are going !geo_select_val, it never goes in.
Caveat: this fix will only work if you make sure all values are numbers. If that's not the case, check for equality with "0"
Here's the code you're asking about:
$('#post-form').click( function() {
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
if(!geo_select_val) {
var geo_url_val = $('input[name=g_url\\[1\\]]').val();
if(geo_url_val != "http://google.com") {
$('#notification').html("You need to enter a valid url");
}
}
});
When I set a breakpoint in this click function and then click on the Post Form div, geo_select_val comes back as "0" which means that if(!geo_select_val) will fail because geo_select_val does have a value so the first if condition will never be executed.
Perhaps you want the first if condition to be:
if (geo_select_val != "0") {
which will tell you if some other value besides the default has been selected (assuming you add other options to that select tag with different values).

Categories