This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 4 years ago.
In JavaScript, what is the difference between doing:
if (a !b)
{
// something here
}
and
if (a != b)
{
// something here
}
I know that '!' is 'logical not' and '!=' is 'not equal to', but I am not sure on the difference between the two.
I have seen both examples used on SoloLearn projects though.
Neither of the above give any errors or warnings in my web browser (chrome).
I'm not sure how to use chrome's debug console yet.
I don't mean "difference between !== and !===" btw.
In JavaScript !foo is a boolean toggle so if foo = true; then !foo is checking to see if foo equals the opposite value in this case false,
your function:
if (a !b)
{
// something here
}
doesn't do anything, and should actually just be:
if (!b)
{
// something here
}
which tests to see if bis in the opposite state.
When you use != you are comparing two values to see if one doesn't equal to the other.
so your function:
if {a != b)
{
// something here
}
checks to see if a doesn't equal b.
Cheers.
A plain ! is a logical operator and indicates opposite. For example a common practice for toggling a boolean operator when you don't always know the current state would be the following:
// Toggle Foo, regardless of current value, assuming its of a boolean type.
var foo = !foo;
!= is an inequality operator and is used to test for "not equal" operator, it simply checks whether something is equal to whatever you are comparing it to.
Here is a great question about this in a more broad context.
Related
I've been studying JavaScript for a couple months, and I have some questions.
Say we have some if statements like this:
if (something)
if (!something)
From what I have looked up, the first statement checks whether something evaluates to true, whereas the second one checks for whether the condition is not true(I recall reading the ! coerces it into boolean and then 'inverses' it).
However, I'd like to know what are these statements' direct equivalents when not "shortened". I'd like to understand code like this more in depth before really using it.
Is if (something) the same as if (something == true)? Or even if (something === true)?
And what would be the "non-shortened" (for my lack of a better term) direct equivalent of if (!something)?
Thank you for any help.
Part 1:
When we use if(something) javascript will check if it is a 'Truthy' or 'Falsy' value.
So if we say
if(1) {
alert("Yes, it's true...");
}
javscript will check if 1 is a "truthy" value and it is.
Everything that is not a falsy value is truthy by extension.
Falsy values are:
0, 0n, null, undefined, false, NaN, and the empty string “”.
So if we directly put any of the above into a parenthesis it will return false.
e.g. if (null) ... the if clause won't be executed because null is falsy.
Part 2:
When we use if(something == true), we check if one value is equal to another value. If the types are not the same, since we're using == coercion will happen.
What is this about 'coercion'?
If we say if('1' == 1) this will execute the if clause as it returns true. Javascript will convert 1(number) to '1'(string) in this case.
If we want to be strict and say "I only want true if they're both numbers, I don't care if 1 is a string" then we use
if(1 === '1') and this will not execute the if clause(because the condition returns false).
So if we say if(false == false) this will return true because false is equal to false, and the if clause will be executed.
Note the difference if we said if(false) or if('') the if statement will not be executed.
Next, if we want to use negation, we have to put the ! in front of the boolean we're negating, regardless of whether it's part of an if condition or... There is no way around it.
However, there is a shorter version of this:
var a = 3;
var b = 2;
if(a===b) {
alert('A is equal to B');
} else {
alert('B is not equal to A');
}
This is considered shorter(ternary operator):
Note that if we want to use more than one statement, we should use the if else
a = 3;
b = 2;
a===b ? alert('A is equal to B') : alert('B is not equal to A');
This question already has answers here:
Empty arrays seem to equal true and false at the same time
(10 answers)
Closed 4 years ago.
I was trying out a code snippet and the results are different for an empty array check inside a console.log statement and in a conditional statement.
Help/Thoughts on why this is different?
Thanks in advance!
//Output: true
if([]) {
console.log(true)
} else{
console.log(false)
}
//Output: false
console.log([] == true)
You seem to be running into a known JavaScript quirk.
"[] is truthy, but not true"
The problem isn't where you are doing the evaluations, but rather that the two evaluations which seem identical are actually different.
See
https://github.com/denysdovhan/wtfjs#-is-truthy-but-not-true
My assumption is that the if/else block, in part of its "truthful" test is checking if something exists (not just if it is true or not) -- wherein the straight console print is comparing the value of the empty array against a boolean (which would be false)
let test = 'apple';
if( test ){
console.log( 'if/else: ' + true );
}else{
console.log( 'if/else: ' + false );
}
console.log( 'log: ' + ( test == true ) );
The two snippets are actually doing different things, hence the different results.
The first, with [] as the condition of the if statement, coerces the array to a Boolean value. (if, naturally enough, only works on Booleans, and JS will happily convert the given value if it isn't already Boolean.) This produces true - all objects in JS are "truthy", which includes all arrays.
For the second snippet, you are using the "loose equality" operator == - for which the JS specification provides a set of rules for how to convert the values into other types, eventually reaching a straightforward comparison between two values of the same type. You might want, or hope, that comparing a non-Boolean to true or false in this situation coerced the non-Boolean to Boolean - but this isn't what happens. What the specification says is that first the Boolean is coerced to number value - resulting in 1 for true (and 0 for false). So it reduces to [] == 1 - which will go through a few more conversions before resulting in a false result.
The key point is that no conversion to Boolean happens in the second case. If you think this is stupid, you're probably right. This is a bit of a gotcha, and one of the reasons many guides tell you never to use == in JS. I don't actually agree with that advice in general (and hate linters telling me to always use === in any circumstances) - but you do have to be aware of some dangers. And using == to compare a value to true or false is something to always avoid.
Luckily, if you want to test if x is truthy or falsy, you have a very short and understandable way to do it - the one you used in the first snippet here: if (x)
[edit] So my original answer was confusing as heck, and there are some incongruencies in the many answers you find on this subject all over the internet; so, let me try this again:
Part 1: Why they are Different
if([]) and if([] == true) are not the same operation. If you see the below example, you will get the same result when doing the same operation.
//Output: false
if([] == true) {
console.log(true);
} else{
console.log(false);
}
//Output: false
console.log([] == true);
Part 2: Why it matters AKA: the confusing bits
In JS, the following is a common expression used to see if an object/variable exists:
var foo = "Hello World";
if (foo) ...
From a design perspective, this test is not important to see if foo is equal to true or false, it is a test to see if the program can find the object or variable foo. If it finds foo, then it executes the results in the "then" condition, otherwise you get the "else" condition. So, in this case, it will convert foo to either false for does not exist, or true for does exist. So in this case the string is reduced to a boolean.
In contrast:
var foo = "Hello World";
if (foo == true) ...
Is typically trying to find out if the value of foo actually equals true. In this case, you are comparing the value of foo "Hello World" to a boolean, so in this case, "Hello World" does not equal true.
Just like foo, [] can be evaluated more than one way. An empty array is still an object; so, in the first case, it coerces to true because it wants to know if [] can be found; however, [] also equals ['']. So now picture this:
if (['bar'] == 'bar') ...
In this case, JS will not look at ['bar'] to see if it is there, but as an object containing a single value which it can convert to the string, 'bar'.
So:
if([]); // is true because it is an object test that evaluates as (1 === 1)
and
if([] == true) // is false because it is a string test that evaluates as ('' == 1) to (0 === 1)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
If you have a function that checks 4 conditions (let's say A, B, C and D) and that if any one of them is true the function should return false.
It works if you write it like this:
function is () {
return (
!A && !B && !C && !D
)
}
However, in this case (correct me if I'm wrong) - all of the conditions will be checked each time (while it can be enough that for example A is true to stop and return false
You can simply reverse the functionality of the function and use return (A || B || C ||D ), but what if you want it to stay like that.
i.e., what I'm looking for is a one-liner return that is equivalent to:
if (a) return false;
if (b) return false;
if (c) return false;
if (d) return false;
return true;
EDIT:
As pointed out in the answers and comments, it is wrong to assume that in the first example all of the conditions will be checked each time. Once one of them evaluates to false (which means that at least one of A,B,C,D is true, i.e. "not not-true") it will stop and return false.
You are wrong about this :
However, in this case (correct me if I'm wrong) - all of the
conditions will be checked each time (while it can be enough that for
example A is true to stop and return false
In the case of a && the expression is evaluated as falseas soon as one term is false
Here is an excerpt of MDN :
Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested
for possible "short-circuit" evaluation using the following rules:
false && anything is short-circuit evaluated to false.
true ||
anything is short-circuit evaluated to true.
EDIT
As mentioned in another answers and comments you can of course rewrite your expression this way:
return !(A || B || C || D)
There still should be a short circuit evaluation so there should no signifiant performance improvement but the expression might look clearer to some. IMO it is more a matter of taste.
You're wrong about how it works. Boolean operators like && and || shortcircuit; as soon as the whole expression has a known value, they stop testing. So in the code provided, if A is true, then !A is false, and it's impossible for false && <anything> to be true, so it immediately stops testing.
Every programming language I know of uses short-circuiting in cases like these, and it's not just an efficiency hack, it's a guaranteed part of the language standard, so expressions to the right of a test know that the earlier test passed. Otherwise, in a language like C, a test like if (p && p->someattr) wouldn't be safe, because without short-circuiting, p could be NULL but it would still be dereferenced to test p->someattr.
For the record, should you need to test some huge number of values to see if any are truthy, and you have them stored as an Array, you can use .some() to check them. For example:
var resultarray = ...;
if (resultarray.some(Boolean)) {
}
Or to simulate your case, where you're testing for all of them to be falsy:
var resultarray = ...;
if (!resultarray.some(Boolean)) {
}
Both of these short-circuit as soon as the find a single truthy value. Similarly, Array.every can be used to test that all entries satisfy a condition, rather than at least one, and it short-circuits when at least one falsy value is found.
How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on
As mentioned in the title, I need a general overview how to check javascript variables in several cases without returning any error causing the browser to stop processing the pageload.
(now I have several issues in this topic.
For example IE stops with error in case _os is undefined, other browsers doesnt:
var _os = fbuser.orders;
var o =0;
var _ret = false;
for (var i = 0; i < _os.length; i++){
...
Furthermore i also need a guide of the proper using operators like == , ===.
As mentioned in the title, I need a general overview how to check
javascript variables in several cases without returning any error
causing the browser to stop processing the pageload.
To check whether or not variables is there, you can simply use typeof:
if (typeof _os != 'undefined'){
// your code
}
The typeof will also help you avoid var undefined error when checking that way.
Furthermore i also need a guide of the proper using operators like ==
, ===.
Both are equality operators. First one does loose comparison to check for values while latter not only checks value but also type of operands being compared.
Here is an example:
4 == "4" // true
4 === "4" // false because types are different eg number and string
With == javascript does type cohersion automatically. When you are sure about type and value of both operands, always use strict equality operator eg ===.
Generally, using typeof is problematic, you should ONLY use it to check whether or not a variables is present.
Read More at MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
The typeof operator is very helpful here:
typeof asdf
// "undefined"
Perhaps you want something like this in your case:
// Handle cases where `fbuser.orders` is not an array:
var _os = fbuser.orders || []
This is from Crockford's JavaScript: The Good Parts
var is_array = function (value) {
return Object.prototype.toString.apply(value) === '[object Array]';
};
Would this code have worked just as well if he had used a simple equality compare == instead of the identity compare ===?
My understanding of identity is that it allows you to check if a value is really set to something specific, and not just something equivalent. For example:
x == true
Will evaluate to true if x is 1, or true, but
x === true will only be true if x is true.
Is it ever possible for the is_array function above to work with either == or ===, but not the other?
In this particular case == and === will work identically.
There would be no real difference in this case because both sides of the quality test are already strings so the extra type conversion that == could do won't come into play here. Since there's never any type conversion here, then == and === will generate the same result.
In my own personal opinion, I tend to use === unless I explicitly want to allow type conversion as I think there is less likelihood of getting surprised by some result.
You are correct. With == instead of === it should work fine.
=== is a strict match, and will not return true for 'falsy' or 'truthy' values (see this for more details). Which shouldn't apply in this situation.