JS Operator precedent logical and comparison - javascript

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.

Related

How do I compare code to one another in a console?

I am new to learning code, so I do not know what to do. Through my course online I discovered that you can compare text using ==
So when I put "yes" == "yes" the console will say True
It's a pretty neat feature, but back on topic.
How can I compare code to one another? For example, I want to compare:
"The file located at \"C:\\Desktop\My Documents\Roster\names.txt\" contains the names on the roster."
To another code, but with it telling me if it's similar or not. How do I do it? I read somewhere about using Escaping Strings, but I don't know where to place them.
I appreciate the help,
Zeke
Testing for equality compares data on each side of the operator.
== is the loose equality operator.
=== is the strict equality operator.
They differ in how they respond to arguments.
Example:
The string "9" and the number 9 are evaluated by loose equality operator as true
"9" == 9 // returns true
However, the strict equality operator, as its name might suggest, also compares the type of data (string vs. number)
"9" === 9 // returns false
More examples and cases can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
For comparing the contents of a file, my suggestion in your case would be to parse the file from .json, so that you can treat it as a JavaScript object. Then you can compare the contents with strings of names.

Whats the difference between the comparison and logical "not" operator?

I'm having a hard time understanding the difference between the comparison and logical "not" operators in Javascript. And I am confused about the syntax as well. My questions are:
Since they are both boolean operators, are there any real differences between the two?
And is the syntax for both like this?
x! = 5
Any explanation appreciated - please post examples if you can.
Comparison: take two values and compare them. We could ask various questions, for example:
are these two values "the same", we use == for that
is this value bigger than that value, >
is this value bigger than or equal to that, >=
The result of each of this is a boolean value. So we could write:
boolean areTheyEqual = ( x == y );
So aretheyEqual would be "true" if x was equal to y. Now suppose you wanted a variable "areTheyDifferent". We could get that in two ways, either using the "not" operator, which works on a boolean value:
boolean areTheyDifferent = ! areTheyEqual;
or we could use the "notEqual" comparison
boolean areTheyDifferent = ( x != y );
So the ! operator takes a boolean value and "inverts" it. You need to read the
!=
as a single comparison operator, just like >= is a single operator.
Comparison operators are used in logical statements to determine equality or difference between variables or values.
eg x!=y
Logical operators are used to determine the logic between variables or values.
eg !(x==y)

3 ways to say if:else, but which one?

In an interesting blog post, I read that there are three ways to write an if:else statement:
//method 1 - regular
if(boolean) {true condition} else {false condition}
//method 2 - shorthand
boolean ? (true condition) : (false condition)
//method 3 - logical operators
boolean && (true condition) || (false condition)
//eg: var c = r==0 && "small" || "big";
EDIT: third method IS an if:else statement, when the first part of it becomes true, the whole statement turns to true||(false condition). all modern compilers ignore the false condition then.
Now I have two questions here:
Which one of them is the most optimized? (from performance view, if any of them differs from the other, please explain why)
Is there any more methods to write an if:else statement?
Don't worry about the performance of these statements unless you are planning on running them a few thousand times per second.
If you are going to run them that often, test it yourself, you'll probably find different results under different browsers.

JSLint Expected '===' and instead saw '=='

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

Why is it a bad idea to allow these in JavaScript == , != , ++ , --

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).

Categories