"value == var" versus "var == value" - javascript

At many places, I've seen developers doing value == var comparisons, like this:
if ('https' === location.protocol) {
port = 8443;
protocol = 'wss://';
isSecure = true;
}
I know that a == b is same as b == a, so why do people use value == var instead of var == value?
Is there a standard for this? And if yes, which is the standard way?

What you are seeing is yoda condition.
Yoda conditions describe the same expression, but reversed:
if ( 42 == $value ) { /* ... */ }
// Reads like: "If 42 equals the value..."
The advantage is
Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.
Note that it is clearly lack of readability. I personally don't prefer this way.

Related

Javascript comparisons == null alternatives

In JavaScript code I want to replace the double-equals structure of the following if-statement:
if( name == null ) {
//do stuff
}
The double equals fail for the jshint rule "eqeqeq", where it's recommended to replace double equals with triple equals. For a moment, let's imagine the above code changed from == null to === null like this:
if( name === null ) {
//do stuff
}
This would work for a variable explicitly defined having the value null, but unfortunately would fail for any unset variables like this.
var a = null; // works correctly
var b; // will fail in comparison
Previously when the triple-equals rule was important to me I would do the following
if( name === null ||| typeof(name) === 'undefined' )
but I find this extremely bloated.
The best alternative I can come up with now is to use the nature of the if-statement and let it evaluate to a false-ish expression like here where I negate the expression and simply remove the == null part:
if( !name ) {
//do stuff
}
For me, this is much simpler, easy to read, and completely avoids explicit equals comparison. However, I am uncertain if there are any edge causes I am missing out here?
So the question is, can I generally replace == null with the negated expression if statements? If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
My criteria for picking a solution will be
clean code
easy to read and quickly understand
validates jshint rules
works in modern browsers (as of writing January 2015)
I am aware of other slightly related questions for discussing difference in the equality operators == vs ===, but this is merely for a discussion of the evaluation compared to null-ish inside the if-statement.
So the question is, can I generally replace == null with the negated expression if statements?
Probably not universally, no, but perhaps in some places.
If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
The !value check will be true for all of the falsey values, not just null and undefined. The full list is: null, undefined, 0, "", NaN, and of course, false.
So if you have name = "" then
if (!name) {
// ...
}
...will evaluate true and go into the block, where your previous
if (name == null) {
// ...
}
...would not. So just doing it everywhere is likely to introduce problems.
But for situations where you know that you do want to branch on any falsey value, the !value thing is very handy. For instance, if a variable is meant to be undefined (or null) or an object reference, I'll use if (!obj) to test that, because any falsey value is good enough for me there.
If you want to keep using JSHint's === rule, you could give yourself a utility function:
function isNullish(value) {
return value === null || typeof value === "undefined";
}
The overhead of a function call is nothing to be remotely worried about (more), and any decent JavaScript engine will inline it anyway if it's in a hotspot.

What is the use of = sign (single) in a condition?

I had read in some articles that in some languages, like in JavaScript, assignment operators can be used in conditional statements. I want to know what is the logic behind that operation? As far as I know, only comparison operators are allowed in condition checking statements.
Any expression is allowed in a condition checking statement. If the value of the expression isn't boolean, then it will be converted to boolean to determine what the statement should do.
You can for example use a number in an if statement:
if (1) { ... }
Any non-zero number will be converted to true.
In Javascript an assignment is also an expression, i.e. it has a value. The value of the expression is the same value that was assigned to the variable.
So, you can use an assignment expression in a condition checking statement, and the value of the expression is converted to boolean if needed:
if (x = 1) { ... }
Using an assignment in an condition checking statement can be useful, if the value that you assign should be used to control what happens. If you for example have a function that returns different values for the first calls, then a null when there are no more values, you can use that in a loop:
while (line = getLine()) {
document.write(line);
}
You can of couse do that with the assignment separated from the logic, but then the code gets more complicated:
while (true) {
line = getLine();
if (line == null) break;
document.write(line);
}
In JavaScript (and many other languages), when a value is assigned to a variable, the value "returned" is the value that was assigned to a variable. As such, such a statement can be used in a condition with any assigned value being evaluated in the standard way.
For example:
var y = 0;
if(x = y){
alert("Y(and thus X) is Truthy");
}
else{
alert("Y(and thus X) is Falsy");
}
There are two factors that combine to give this effect:
in many languages, including JavaScript, an expression of the form left = right evaluates to the new left. For example, a = b = c = 0 sets all of a, b, and c to zero.
in many languages, including JavaScript, a wide variety of values can be used as conditional expressions. if(7) is equivalent to if(true); so if(a = 7) is equivalent to a = 7; if(true) rather than to the presumably-intended if(a == 7).
Assigning a value with = returns that value. You can use it to make an assignment while testing if the outcome is truthy or falsey (null, 0, "" undefined, NaN, false)
if (myVar = myArgument) ...
//same as:
// myVar=myArgument;
// if (myArgument) ...
This assigns myArgument to myVar while testing myArgument. Another more specific example:
If (myVar = 3+2) ...
// same as:
// myVar=3+2;
// if (5) ...
The benefit is more compact, terse code, sometimes at the expense of clarity.
This could be used to make a condition check and also use the value after it, without writing more lines.
if (value = someFunction()) {
...
}
This is valid syntax, though highly discouraged. In quite a few languages this is explicitely forbidden, but some languages also does not make this rule (e.g. C).

(null != someVariable) OR (someVariable != null)

What is the difference between (null != someVariable) and (someVariable != null)? I have seen a lot of people using 'null' first in the comparison. Which one is better than the other and why?
They're equivalent.
However, the first one will cause an invalid assignment error if you mistype != as =. Some people like this as it's rather easy to type = instead of ==, although the former isn't always an accident.
You can see the precise rules of the specification with regard to the == operator on the Annotated ES5.
They evaluate to the same thing, but it is preferable to choose (someVariable != null), because the other way is a Yoda condition. It deals with readability.
The first might be better of someVariable is actually a function with a very long list of arguments. Your intention would be easier to see at first glance. Otherwise, I always use the second.
Consider you want this :
if (number == 42) { /* ... */ }
// This checks if "number" is equal to 42
// The if-condition is true only if "number" is equal to 42
Now, imagine you forget there should be a double = and you just write a single = instead :
if (number = 42) { /* ... */ }
// This assigns 42 to "number"
// The if-condition is always true
Such errors are pretty common and can be hard to detect in programming languages that allow variable assignments within conditionals.
Now, consider reversing the order of your condition :
if (42 == number) { /* ... */ }
// This checks if "number" is equal to 42
// The if-condition is true only if "number" is equal to 42
The behavior of 42 == number is exactly the same as the behavior of number == 42.
However, if make the same mistake mentioned hereabove (you forget there should be a double = and you just write a single = instead), the behavior is no longer the same :
if (42 = number) { /* ... */ }
// This produces an error
Therefore, some people prefer to reverse the order of their conditions, as it makes a common error much easier to detect. Such "reversed" conditions are known as Yoda conditions.
In programming languages that do not allow variable assignments within conditionals (eg. Python or Swift), there is no advantage whatsover to using Yoda conditions, and it's typically discouraged to use them. In other languages (eg. JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it's still largely a matter of your personal preference or whatever coding standards your project require.
Wordpress & Symfony are two popular open source projects where Yoda conditions are part of the coding standards.

JavaScript and other language that use losely defined vars

Hey anyone out there that uses JavaScript in a professional environment. I wanted to know the standard when comparing values using == and === operators. I was watching a video the explained that if you compared a sting with a value of '5' and an int with a value of 5 it returns true using the == operator. They then suggested to use the === for everything. I know this is wrong because what if you wanted to compare some value nested in some polymorphic objects with different type defs say one being a student and the other being an instructor the === would always return false.
After much thought I came to the conclusion that it might be best to use === whenever possible and the == when only necessary.
Can you give me some insight on what the rule of thumb is in a professional environment?
The rule is simple:
Always use === and !== unless you explicitly WANT a type conversion to be allowed and have thought through the consequences of that type conversion. In otherwords, you should be using === and !== nearly all the time.
Your exception for polymorphic objects does not apply because == and === both require two objects to be the exact same object when comparing two objects. There are no type conversions in that case. If you were comparing two properties of polymorphic objects, then only the type of the property is looked at, not the type of the containing object.
For detailed rules on type conversions with ==, see this http://es5.github.com/#x11.9.3. There are some odd ones like this:
var x; // x is undefined
alert(x == null);​ // alerts true
Check out http://jshint.com which helps enforce these best practices. They (and everyone else pretty much) recommend using ===.
I can rarely think of a reason to use == over ===.
Here's a fancy example of using === even when == might feel easier.
var person = {
name: "Cody",
age: "44"
}
var targetAge = 40;
// explicit type conversion, no wonder what's happening
if (parseInt(person.age, 10) === targetAge) {
alert("You won!")
} else {
alert("Sorry You Lost!");
}
See Also: JavaScript: The Good Parts and Maintainable JavaScript, which also recommend the practice.
it's commonly used in this type of statements:
var x = 0;
if(x == false) {
// this will be executed
}
if(x === false) {
// this not
}
if(false == '') {
// this will be executed
}
if(false === '') {
// this not
}
another example - function which is returning FALSE on error or string on success
function foo(bar) {
// magic
return ''; // this is SUCCESS
}
var result = foo(123);
if(result === false) {
// omg error!!
}else{
// some string returned, event empty one is OK
}
to be honest it's really rare to use === in statements

What's the equivalent way of writing inline assignment and checking PHP 'logic' but in JavaScript

In PHP you could write this:
if(false !== ($value = someFunctionCall())) {
// use $value
}
How would you write an equivalent of this in JavaScript without defining
var value;
before this comparison?
You'd write
if (value = someFunction()) {
I don't trust my knowledge of PHP that heavily, but I suspect that explicit comparisons to false in if statements aren't necessary, as the expression is implicitly boolean. (edit — sometimes, if a function can return either an explicit boolean or some "good" value that evaluates to "falsy", then yes you do need the explicit comparison to boolean.)
edit — if you're squeamish about the ages-old confusion (or potential thereof) between = and ==, then I'd advise avoiding the construct entirely. There's nothing wrong with it, other than the fact that sometimes you want an equality comparison and sometimes you want an assignment.
edit oh also this presumes that "value" has been declared with var somewhere — if the question is about how you do the declaration in the context of an if statement, then the answer is that you cannot do that.
final edit I kind-of promise — to sum it up:
Assuming that "value" is declared:
var value;
somewhere, then:
if (false !== (value = someFunction())) { ... }
has pretty much the same semantics as the PHP original.
You can just have it assign when it's executed and JavaScript will automatically add the var declaration:
function foo(){
return (Math.random() * 0.5) > 0;
}
if (false !== (f = foo())){
alert('True!');
}
alert('f=' + f.toString());
jsFiddle Example
However, this is very bad practice. You should always declare your variables when and where you need them first. Just because PHP and JS accept this syntax doesn't mean it's good practice. The proper style would be as follows:
var f = false;
if (false !== (f = foo())){
alert('True!');
}
alert('f=' + f.toString());
That would be very bad practice in JavaScript,
You would be best to do
if(!(var value = someFunctionCall())) { // use value //}
Personally i would say define it before. Your call though. If you worried about memory then define it and null it after use.

Categories

Resources