I saw a do-while loop that looked something like
var guess = false;
do {
stuff stuff stufff
if ( things === things){
guess = true;
}
} while ( ! guess )
This confused me because the ! operator changes the boolean value to the opposite, so that guess becomes true instead of false. So "while not false" the do-while keeps running? Or does this mean "while true" it keeps running or...?
thanks for the help!
while(!guess) means "while guess is not true".
It also can be written as while(guess == false). Maybe that way is easier to understand, although it is not a good practice.
There are some examples here: MDN - Logical operators
the actual format would be
if (things == things)
{
coding here......
}
the == mean is equal to.
the >= means greater than or equal too.
the <= means less than or equal to.
the != means that its not equal to.
so if you change the operators this would be
if (things == things) which means things are equal to things.
if (things >= things) which means things is greater than or equal to the things.
Follow the steps and for example when you use this in speech it would look like
if (speech == "things")
{
do coding.........
}
the speech is equal to things then the code will be executed
Related
I know this has been asked a million times. But I can't find one that answers my questions directly. Just similar kinds of questions.
So this statement.
1 == !""
According to MDN operator precedent: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Logical NOT has a higher precedent than equality.
It also mentions, assignment operators are right-associativity. Thus everything else must be left-associativity.
So on that statement. I'd of thought it would run as
!"" (coerce to a bool value, flip the value)
1 == true (compare the value)
But based on reading further down and the associativity mentions. It should run from left-to-right. Right? Which end up being the same thing, but it checks
1 ==
... then does the type coerce stuff
is my thinking right? Just wanted to make sure.
I see in the code I am working on often the following code style;
var1 == true && (var2 = true)
After some testing I figured it comes down to:
if (var1 == true) {
var2 = true;
}
Is this correct, or is there more to it? And why would anyone use this since the readability just dramatically reduces, since your assume at first glance it is just a check on two variables. So you really have to start looking at single or double equal sings and where the parentheses are, which just kinda, you know.. Just curious here..
Yes, this is equivalent. As far as I know, it is called short-circuit evaluation, describing the fact that the interpreter will return false for the whole boolean expression as soon as one of its parts is falsy.
Indeed, in your example it DOES reduce readability. But I think of it as just another tool in your toolbox you may use when you feel it could be useful. Consider the following:
return user && user.name;
This is one example when I tend to use it. In this case, I think it's actually more readable than
if (user) {
return user.name;
} else {
return undefined; // or null or something alike
}
UPDATE
I want to give you another example when I consider this kinds of constructs useful. Think of ES6 arrow functions like user => user.name. It does not need {} to open a body since it just has one line. If you wish to log something to the console (for debugging), you would end up having
user => {
console.log(user); // or something alike
return user.name;
}
You might as well use the shorter variant
user => console.log(user) || user.name
since console.log returns undefined after logging into the console, hence user.name is returned.
Yes, as you've mentioned there's more to it.
the first part var1 == true checks whether ther result is true or false.
if the condition is false the code after it doesn't get checked or evaluated and thus var2 doesn't get set to true.
But if the first part of the condition var1 == true is true which obviously is true, the second part of the conditional statement the part after && is checked.
now the second part of the condition is an operation it sets (var2 = true) which is kind of a truthy operation.
we could edit your code a little bit to help you understand the operation more clearly:
if( var1 === true && (var2 = true)){console.log('good');}
I hope this helps
I am writing a JS library, and there are two things that have been on my mind for quite some time though.
Consider an option:
var option = { bool : true } ;
Now, imagine I do either
if(option.bool)
or
if(option.bool === true)
The first case, despite knowing for sure that it's either true or false, I imagine is the equivalent of:
var tmp = options.bool;
if ( tmp !== undefined && tmp !== null && ( tmp === true || tmp ... )
That means that to try the options.bool = true it has to check both undefined and not null, before testing for true.
Therefore the latter case should be more performant. However, the latter case, takes a considerably more characters and will lead to a larger lib, if repeated many times.
But maybe my understanding is incorrect.
Right now, even if I do:
var bool = window.t ? true : false;
if ( bool === true ) // I still have to check for true to 'have the optmimal version'?
Maybe the last case can be optimized by the compiler, but when it's a global option I imagine it's different?
Please share with me your thoughts on this.
The answer is simple. It's less about coding patterns and more about logic.
In this scenario there are always 3 possibilities and you need to cater for each of them.
Ie. 1. TRUE 2. FALSE 3. undefined
If the value is undefined then do you want it to fall under the true or false clause? OR should it be catered for differently?
Another important thing to remember is that if it is undefined then it will always execute the code in the false clause. Is that what you want?
If you know that the value will always be either true or false then I suggest that you still use the syntax == true as this is more readable. Someone browsing over the code would know that you are looking for the boolean value and not testing if the field has been set.
You have to think about these 3 cases every time you have a boolean in an if statement, so there is no 1 answer for you.
Recently I was running some of my code through JSLint when I came up with this error. The thing I think is funny about this error though is that it automatically assumes that all == should be ===.
Does that really make any sense? I could see a lot of instances that you would not want to compare type, and I am worried that this could actually cause problems.
The word "Expected" would imply that this should be done EVERY time.....That is what does not make sense to me.
IMO, blindly using ===, without trying to understand how type conversion works doesn't make much sense.
The primary fear about the Equals operator == is that the comparison rules depending on the types compared can make the operator non-transitive, for example, if:
A == B AND
B == C
Doesn't really guarantees that:
A == C
For example:
'0' == 0; // true
0 == ''; // true
'0' == ''; // false
The Strict Equals operator === is not really necessary when you compare values of the same type, the most common example:
if (typeof foo == "function") {
//..
}
We compare the result of the typeof operator, which is always a string, with a string literal...
Or when you know the type coercion rules, for example, check if something is null or undefinedsomething:
if (foo == null) {
// foo is null or undefined
}
// Vs. the following non-sense version:
if (foo === null || typeof foo === "undefined") {
// foo is null or undefined
}
JSLint is inherently more defensive than the Javascript syntax allows for.
From the JSLint documentation:
The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.
When comparing to any of the following values, use the === or !== operators (which do not do type coercion): 0 '' undefined null false true
If you only care that a value is truthy or falsy, then use the short form. Instead of
(foo != 0)
just say
(foo)
and instead of
(foo == 0)
say
(!foo)
The === and !== operators are preferred.
Keep in mind that JSLint enforces one persons idea of what good JavaScript should be. You still have to use common sense when implementing the changes it suggests.
In general, comparing type and value will make your code safer (you will not run into the unexpected behavior when type conversion doesn't do what you think it should).
Triple-equal is different to double-equal because in addition to checking whether the two sides are the same value, triple-equal also checks that they are the same data type.
So ("4" == 4) is true, whereas ("4" === 4) is false.
Triple-equal also runs slightly quicker, because JavaScript doesn't have to waste time doing any type conversions prior to giving you the answer.
JSLint is deliberately aimed at making your JavaScript code as strict as possible, with the aim of reducing obscure bugs. It highlights this sort of thing to try to get you to code in a way that forces you to respect data types.
But the good thing about JSLint is that it is just a guide. As they say on the site, it will hurt your feelings, even if you're a very good JavaScript programmer. But you shouldn't feel obliged to follow its advice. If you've read what it has to say and you understand it, but you are sure your code isn't going to break, then there's no compulsion on you to change anything.
You can even tell JSLint to ignore categories of checks if you don't want to be bombarded with warnings that you're not going to do anything about.
A quote from http://javascript.crockford.com/code.html:
=== and !== Operators.
It is almost always better to use the
=== and !== operators. The == and != operators do type coercion. In
particular, do not use == to compare
against falsy values.
JSLint is very strict, their 'webjslint.js' does not even pass their own validation.
If you want to test for falsyness. JSLint does not allow
if (foo == null)
but does allow
if (!foo)
To help explain this question and also explain why NetBeans (from) 7.3 has started showing this warning this is an extract from the response on the NetBeans bug tracker when someone reported this as a bug:
It is good practice to use === rather than == in JavaScript.
The == and != operators do type coercion before comparing. This is bad because
it causes ' \t\r\n' == 0 to be true. This can mask type errors. JSLint cannot
reliably determine if == is being used correctly, so it is best to not use ==
and != at all and to always use the more reliable === and !== operators
instead.
Reference
Well it can't really cause problems, it's just giving you advice. Take it or leave it. That said, I'm not sure how clever it is. There may well be contexts in which it doesn't present it as an issue.
You can add this to the previous line to disable these warning.
// eslint-disable-next-line
I was checking out JSLint, and some of the rules piqued my interest. Particularly this:
Disallow == and !=
Disallow ++ and --
Why is it a bad idea to disallow these? I understand the first part, basically it wants me to do === instead of ==. I don't understand why though. I understand the difference between the two, I just want to know why is it bad practice. Some times I really want to do == for example so that it would evaluate true for undefined == null
The second one, well I don't understand at all. Does it want me to do myInt += 1 instead of myInt++ ?
Thanks!
I don't agree too much with those rules, instead of discouraging the use of ==, I would recommend to learn about type coercion.
The primary reason about why Crockford wants to avoid == is that the comparison rules depending on the types of the operands can make this operator non-transitive, for example, if:
A == B AND
B == C
Doesn't guarantees that:
A == C
A real example:
'0' == 0; // true
0 == ''; // true
'0' == ''; // false
The strict === operator is not really necessary when you compare values of the same type, for example:
if (typeof foo == "function") { }
We compare the result of the typeof operator, which is always a string, with a string literal...
Another example, when you compare something against null, == also compares against undefined, for example:
if (something == null) {}
VS
if (something === null || typeof something === "undefined") {}
The above two conditions are at the end equivalent, but the first one much more readable, of course if you know about type coercion and how == behaves.
Learning how the == operator works, will help you to wisely decide which to use.
Recommended articles:
ECMAScript. Equality operators (Great tips to remember how == works)
typeof, == and ===
Doug Crockford has his own ideas about what is "good" and "bad" in Javascript. Accordingly, JSLint implements these checks, but makes them optional if you don't completely agree with him.
Disallowing == helps prevent you from making mistakes when you really meant ===. Of course this assumes that you never really want to use ==.
Disallowing ++ and -- is a style thing, some people believe they are harder to read than += 1 and -= 1.
Douglas crockford (the guy who wrote JSLint) explains himself in this video :
http://www.youtube.com/watch?v=hQVTIJBZook#t=14m45s
but basically (as everyone else has mentioned) it's because of the type coercian.
Worth watching the who video to be honest - very interesting and useful.
From the instructions:
The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.
and
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.
The == and != operators do implicit converson of the operators if needed, while the === and !== operators don't. The expression 4 == '4' for example will be true, while the expression 4 === '4' will be false.
Preferrably you should know the data types you are dealing with, so that you can do the proper comparisons in the code.
The ++ and -- operators doesn't cause any problems if they are used alone in a statement, but they are often used to make a statement that does more than one thing in a not so obvious way, like:
arr[++idx] = 42;
which would be clearer as:
idx += 1;
arr[idx] = 42;
The behavior of the standard equality operators (== and !=) depends on the JavaScript version. So that's one reason for not using them.
Another reason is that the behavior of the = tends to be very vague.
See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
I understand ==. (the undefined == null thing is an exception)
("0" == false) === true
("0" === false) === false
I've never understood the ++ and -- thing though. I don't like doing i+=1 all over my code (it's slower than ++i).