JS if/else trouble - javascript

I have a simple code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#continue").click(function() {
var value = jQuery('#continue').attr('value')
alert (value);
if (value='next'){
jQuery('#msg_title').html('blablabla');
jQuery('#msg').html('blablabla'');
jQuery('#continue').attr('value','removeConfig');
value = jQuery('#continue').attr('value');
}
else if (value='removeConfig') {
jQuery('#msg_title').html('It Works!');
}
else {
alert ('Something wrong')
}
return false;
});
});
</script>
It works well in firs if phase, changes button's value (as I see from alert), but doesn't make else if and else statements.

Your comparison operator is wrong: if (value='next') should be if (value == 'next'){ or if (value === 'next'){.
Note the extra = signs.

You need ==
(value='next'){
should be:
(value == 'next'){
You are testing if ('next') { which is always true. Only string the evaluates to false is empty string, ""

Use ==, not =. A single = is an assignment operator, which means it's assigning "next" to value, then testing if value is false, not if value equals next

You need double equals signs as singles will return true in this case:
if (value =="next")
Single = is an assignment operator and double == is a comparison operator. Since you were using an assignment operator and setting the variable to a non falsy value the first if statement resolved to true.

Related

Why is the result different from what I expect?

emptyWord = '';
if (emptyWord !== false) {
console.log(1);
} else {
console.log(2);
}
If emptyWord is false, I want the else to run. If emptyWord is true, I want the console.log(1) to run.
I actually expected console.log(2) to run. Because emptyWord is a falsey value. The condition says, 'is a falsey value, not the same as false'. The answer to that is 'no/false'.
I know a better thing to put would've been: emptyWord === true.
But whilst we're here, how do you explain in words what's going on with the condition in the snippet. I think I read somewhere that you should try to avoid 'double-negatives'.
You used !== false and not != false. When you use !== it isn't checking for "falsy", it's checking if it is actually false or not.
console.log('' != false);
console.log('' !== false);
it will always return true, because :
emptyword is not STRICTLY equals (=== means strictly equals) to false!
what you're probably looking for is !=, in this case it will convert the value 0 to false, for example. To note here, there is a difference between strictly equals and just plain equals (=== vs ==).
in english:
is emptyword not equal to false? in this case it is true, so it enters the first clause:
console.log(1);
take a look here for more examples :
https://j11y.io/javascript/truthy-falsey/
You should use !=false because !==false is strictly looking for not false
emptyWord = '';
if (emptyWord != false) {
console.log(1);
} else {
console.log(2);
}
The !== operator checks if the type and the value of the variables are the same.
The != operator checks if only the value is the same.
'' and false are equals the same in terms of value in js, but '' is a string and false is a boolean value.
If you want to get 2 as return, you need to change your code to:
emptyWord = '';
if (emptyWord != false) {
console.log(1);
} else {
console.log(2);
}
('' !== false) is true.
('' != false) is false.

Is there a way to clarify the true and false statements in this JS?

I've been working on learning JS, and I can't seem to figure out why my boolean values keep coming back either always true or always false.
So I believe I understand the basics of the truthy/falsy situation in JS, but I can't seem to get it right. I know that there are data type issues, (can't make different data types do different things).
function lastCharacter(char1, char2) {
if (char1[-1] === '' && char2[-1] === '') {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkine'));
Or
function lastCharacter(char1, char2) {
if (char1[-1] === char2[-1]) {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkina'));
Define a function lastCharacter that accepts two strings as arguments.
lastCharacter should return true if both strings end with the same character.
Otherwise, lastCharacter should return false.
They either return always true or always false. Can anyone help me?
You need a different method for getting the last character of a string, preferably with String#slice and a negative value for getting the last one. Then compare and return the result.
function lastCharacter(string1, string2) {
return string1.slice(-1) === string2.slice(-1);
}
console.log(lastCharacter('apple', 'pumpkine'));
A comparison between taking the last character of an empty string by using an index -1 which returns undefined and slice, which returns an empty string.
var x = '';
console.log('#' + x.slice(-1) + '#');
console.log('#' + x[x.length -1] + '#');
You can use slice
function lastCharacter(char1, char2) {
return char1.slice(-1) === char2.slice(-1)
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
Or you can just access the last index
function lastCharacter(char1, char2) {
return char1[char1.length-1] === char2[char2.length-1]
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
There are no negative array indexes in JavaScript, instead of char1[-1] you have to use char1[char1.length - 1].
Accessing one of a strings characters (e.g. "abc[1]) will always have a length of 1, it will never be equal to "". Your second function makes more sense.
Also
if(condition) { return true; } else { return false; }
is equal to
return condition;
The notation [-1] does not implicitly mean "one character from the end of the string" in JavaScript. You can use str[str.length - 1]. (If you expect possible empty source strings, you'd want to check for that too to avoid ending up with exactly the same problem.)
Instead of an if/else that returns either true or false, just return the results of the logical expression:
return char1[char1.length - 1] === '' && char2[char2.length - 1] === '';
Both the === comparisons return either true or false anyway, so the overall expression value has to be one of those. In general however if you want to make absolutely sure that you end up with a boolean, you can prefix an expression with !! to force the standard JavaScript "truthy-falsy" evaluation:
return !!(expression);

Write shorthand for val++ and if()

I do a val++ at the end of each txt file is loaded and then run doSome() when val is equal to num.
$('#holder').load('item[i].txt',function(){
val++;
if(val==num){
doSome();
}
}
How to I write this shorthand?
val++;
if(val==num){
doSome();
}
val++ already is (basically) shorthand for val = val + 1;
You can use && to replace the if:
val == num && doSome();
(MDN: && Shortcut operation)
Resulting in:
$('#holder').load('item[i].txt',function(){
val++;
val == num && doSome();
}
Personally, I prefer having the increment and the condition on separate lines, for readability purposes.
Another suggestion: The brackets for an if statement ({}) are optional, if the if statement is only used for 1 line of code:
if(condition) {
doSomething();
}
Can be shortened a bit like:
if(condition)
doSomething();
Use pre-increment operator
if (++val === num) {
//code here
}
This will first increment val by one and then compare the updated value with num variable.
Pre-increment could be used where value of variable is incremented first and then returned whereas in Post-increment, value of variable is returned first and then incremented.
if (++val == num) {
doSome();
}
So... maybe this? :) ++val ^ num || doSome();
^ (XOR) is a bitwise operator. It returns 0 if two operands are the same number. For example 2^2 = 0.
So you can firstly pre-increment val this way: ++val. Then you can do XOR operation on num, and when they are equal - it will return 0, which is considered as false in logic statements in js. And then, when left side of || operator is false, it will execute right part of this statement - doSome().
Btw, one interesting thing: for example, if disable code optimisation, in C++ it is much efficient to assign 0 to variable in this way: a ^= a rather than a = 0.

javascript if conditional: object exists and has a value appended

Getting an 'Invalid left-hand side in assignment' error in my console. Am I missing syntax here?
if ($images[next] && images[next].loaded = false){
//stuff
}
Each condition passes on it's own, but fail when combined.
Using a single = means you're assigning a value to a variable. For comparisons, use == or === for strict equality.
Use double equals for comparison. Alternatively, you could just write:
var item = $images[next];
if (item && !item.loaded){
}
it should be
if ($images[next] && $images[next].loaded == false){
//stuff
}
Or Better
var images = $images[next];
if (images && images .loaded === false){
//stuff
}
As everybody already told you, you should be using == (or ===) for comparison. What caused the error is that the assignment operator = has a lower precedence than the boolean && operator, unlike == or any other comparison operator. So your expression was evaluated as:
($images[next] && images[next].loaded) = false
The left-hand part, in parentheses, will be either true or false. So that becomes either
true = false
or
false = false
Neither is allowed, because you can't assign anything to a boolean value (only to a variable or object property). Hence an Invalid left-hand side in assignment error is thrown.
When you use a proper comparison operator, the precedence rules cause it to be evaluated like this:
$images[next] && (images[next].loaded == false)
That becomes true && true, or true && false, or false && false, or false && true, then eventually just true or false, which is what an if statement expects.
Maybe a "==" instead of a "=" in the equality check would help
if ($images[next] && images[next].loaded == false)
{
//stuff
}
For a list of the javascript comparison operators, have a look here
Everyone'll prly say the same thing: ... .loaded = false should be ... .loaded == false. = is an assignment operator, == is a comparative operator..
Sometimes you'll see if (x = someFunction()) which will run the code block as long as someFunction() doesn't return false or throw an error (as it does in your case).
Let me know if you have any questions :)
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators

Convert string to Boolean in javascript [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 5 years ago.
How to convert a string to Boolean ?
I tried using the constructor Boolean("false"), but it's always true.
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).
var myBool = myString == "true";
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
you can also use JSON.parse() function
JSON.parse("true") returns true (Boolean)
JSON.parse("false") return false (Boolean)
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return true
else
return false
You can't use Boolean as you think.
trick string to boolean conversion in javascript. e.g.
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
I am still amazed how people vote blindly for solutions that won't work, like:
var myBool = myString == "true";
The above is so BUGGY!!!
Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!
Alternative
var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!
will always evaluate right!
Depends on what you see as false in a string.
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
I believe the following code will do the work.
function isBoolean(foo) {
if((foo + "") == 'true' || (foo + "") == 'false') {
foo = (foo + "") == 'true';
} else {
console.log("The variable does not have a boolean value.");
return;
}
return foo;
}
Explaining the code:
foo + ""
converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.
(foo + "") == 'true'
This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.
(foo + "") == 'true' || (foo + "") == 'false'
Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.
In the 3rd line, the value of 'foo' is finally "converted" to boolean.
These lines give the following output:
Boolean(1).toString(); // true
Boolean(0).toString(); // false
Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#.
So workaround is
var setActive = 'true';
setActive = setActive == "true";
if(setActive)
// statements
else
// statements.
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
See this question for reference:
How can I convert a string to boolean in JavaScript?
There are a few ways:
// Watch case sensitivity!
var boolVal = (string == "true");
or
var boolVal = Boolean("false");
or
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
You can try this:
var myBoolean = Boolean.parse(boolString);

Categories

Resources