JS object null checking - weird JS problem [duplicate] - javascript

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Javascript AND operator within assignment
(7 answers)
Closed 4 years ago.
Imagine this simple scenario. I have variable that can be plain JS object with one property, ID, that is a number or obj variable can be null. I have simple test() function that checks if the variable is not null and that it must have valid id property.
var obj = { id: 111 };
function test() {
return (obj && obj.id);
}
I am expecting that this function will always return boolean but in fact it returns undefined if the obj is undefined or value of obj.id if object exists like in case above. Why this function return 111 instead of true.
I am going to rip off hair of my head ... Please illuminate my mind :)

It's a common misconception. In JS (unlike in e.g. PHP) an expression like x && y does this:
execute the expression x
if the expression x returned true, then execute the expression y as well and return it (y). Otherwise return x (which would be falsy in this case e.g. 0, '', false, null, undefined).
In other words it works more like a ternary expression x ? y : z.
If you want a boolean, then use !!(x && y).

When obj is defined, why does if (obj && obj.id) return 111?
The logical AND (&&) operator returns expr1 if it can be converted to false; otherwise, returns expr2.
MDN: Logical Operators - Description (slightly paraphrased)
expr1 (obj) cannot be converted to false, therefore it returns expr2 (111).
Why does it not return true?
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
MDN: Logical Operators
Because you are using the logical operator with non-Boolean values, the result will be non-Boolean as well.

Related

I can't understand the logical operator error in JavaScript [duplicate]

This question already has answers here:
Logical operators in JavaScript — how do you use them?
(2 answers)
Closed last year.
I was coding in node, so I got an error, will you explain this error to me?
When I write a statement console.log(Email||Password||Song)
It's returning the value of Email variable.
But when I write statement console.log(!Email||!Password||!Song);
It's returning actual value which is true/false
Can you Please explain me
So, first up the or (||) operator:
a || b === a if a is truthy, otherwise b
So the or operator isn't strictly useful for boolean types. For example, you could set a default value for data like
function makePerson(name, age) {
return { name: name, age: age || 0 }
}
Next, the not (!) operator:
!a === false if a is truthy, true otherwise
So note that the ! operator strictly provides boolean outputs.
So with your example,
Email||Password||Song
will be Email if truthy, then Password if truthy, and finally Song
!Email||!Password||!Song
is going to end up evaluating to something like
false||false||true
or
true||false||false
etc. By adding in the unary not, you're effectively casting all your inputs to booleans, and the output of the or operator is the type of its inputs.

Why the Javascript logical operator behaving this way? [duplicate]

I am unable to understand this.
Following is expression uses OR operator
var subCond1 = adj.getData('relationEnabled') == 'true' || adj.getData('unhideIfHidden') || adj.getData('hlFixed') == 'true';
I am expecting that since it is OR operation, it should return boolean true/false, but instead I get string 'false' as a result.
Can anyone explain this please?
Yup, that's just one of the features of || in JavaScript, and it's deliberate. It doesn't return a boolean (necessarily), it works like this: It evaluates the left-hand operand and if that operand is truthy, it returns it; otherwise, it evalutes and returns the right-hand operand.
So what's "truthy"? Anything that isn't "falsy". :-) The falsy values are 0, "", null, undefined, NaN, and of course, false. Anything else is truthy.
If you need a boolean, just !! the result:
var subCond1 = !!(adj.getData('relationEnabled') == 'true' || adj.getData('unhideIfHidden') || adj.getData('hlFixed') == 'true');
...but you frequently don't need to bother.
This behavior of || is really useful, particularly (I find) when dealing with object references that may be null, when you want to provide a default:
var obj = thisMayBeNull || {};
Now, obj will be thisMayBeNull if it's truthy (non-null object references are truthy), or {} if thisMayBeNull is falsy.
More in this article on my blog: JavaScript's Curiously-Powerful OR Operator (||)
Just to round things out: The && operator has a similar behavior: It evaluates the left-hand operand and, if it's falsy, returns it; otherwise it evaluates and returns the right-hand operator. This is useful if you want an object property from a variable which may be null:
var value = obj && obj.property;
value will be the value of obj if obj is falsy (for instance, null), or the value of obj.property if obj is truthy.
Javascript returns the first operand that has a truthy value, whatever that truthy value is or the value of the last operand if none before are truthy. That is a designed feature of Javascript (yes it is different than other languages).
You can turn that into a boolean by comparing to see if it is == true if you want or it is sometimes done with !!.

Javascript Logical OR and Objects

Can someone explain everything that's happening in a statement like this:
POJO.someProperty = POJO.someProperty || {}
Is this checking for undefined then simply assigning an empty object if undefined = true?
The logical operators in javasript can return non boolean values. The Logical OR operator will return the first truthy value it finds in the operands. The Logical AND will return the first falsy value, or the last operand if all other operands are truhty.
Logical operators are typically used with Boolean (logical) values.
When they are, they return a Boolean value. However, the && and ||
operators actually return the value of one of the specified operands,
so if these operators are used with non-Boolean values, they may
return a non-Boolean value.
1 || 0 -> 1
1 && '' -> ''
So when your code is evaluated if POJO.someProperty is undefined then the operator will process the second operator which is an empty object(which is a truthy value) so that value will be returned and assigned back to someProperty.
Why is it used, it is used normally to escape the property not defined error. Assume you are trying to access a property of POJO.someProperty, like POJO.someProperty.somekey but then if POJO.someProperty is undefined then you will get an error. But here if it is undefined then we are assigning an empty object so POJO.someProperty.somekey will return undefined not an error.
This statement is checking to see if POJO.someProperty has a truthy value. If it does, then nothing happens. If the property is falsy, then the property is assigned an empty object literal.
Falsy means one of several things:
A false literal
The number 0
null
undefined
An empty string
If the property has any of these values, it will be reassigned to an empty object.
In JavaScript, as in C, the value of an assignment expression is the value of the right-side operand. In the example you provided, the expression on the right side of the assignment is evaluated before the assignment happens. Because it's a logical OR, it will evaluate to an object literal {} if POJO.someProperty is falsy.
You might see assignment expressions used like this in other places too (notice the single equal sign in the if expression):
var x = 1;
var y = 0;
if (y = x) {
// This block executes because x is 1 (also, y is now 1)
}

Javascript ORing in variable how it works?

I want to know the process of ORing in javascript variable. I used below code for just testing purpose. I want just know the process behind these ORing in var. I know the process when we are using in if condition. Please any one explain me in details.
var a = a || "2010" || "Gunjan" || 20;
console.log(a);
//output 2010
When I console var a then it gives me output like 2010.
Why?
How?
Can anyone one explain me background process?
The Logical Operators returns the value of one of the operands, so if the operands returns a non boolean value then the logical operation could return a non boolean value
Logical operators are typically used with Boolean (logical) values.
When they are, they return a Boolean value. However, the && and ||
operators actually return the value of one of the specified operands,
so if these operators are used with non-Boolean values, they may
return a non-Boolean value.
Also looking at Short-Circuit Evaluation, the OR operator will stop executing of further conditions once one of the operands is true.
Now looking at your condition var a = a || "2010" || "Gunjan" || 20;, since you have used var a, I'm assuming you are declaring the variable a here, so when the RHS is executed a has a value undefined which is falsy so the OR operator executes the second operand which is a string literal 2010 which is a non boolean but truthy value so that is returned as a result of this operations
Oring will return the first true value or the last value if all are false.
True value means not null,not undefined,not 0 ,not empty etc.

use of OR in javascript object in my case confusion [duplicate]

This question already has answers here:
Javascript || operator
(5 answers)
Closed 8 years ago.
Question 1
What does options.left = options.left || _KSM.drawOption.left means? I know _KSM.drawOption is referring to the object (also a function), but how does the || operator work here? Does it mean if _KMS.drawOption.left is undefinded, assign options.left to options.left?
Question 2
Why the author didn't use this keyword in this case? I assume it's because in this demo he didn't create an instance, because he just do the calling once. Rigtht? (I've seen a lots of this in jquery plugin that's why I'm consufed when the author call the function name instead of this within a function)
Question 1
This is a way to set a default value to a variable. It actually evaluate the left side and if it is falsy, the variable will be equal to the right side (even if it is also falsy).
That is a bad way of assigning default variable especially when working with integer. 0 is considered as falsy, so you will never be able to assign 0 as a left property. Instead, it will always be the default parameter of _KMS.drawOption .
Question 2
We don't have the full code so we can only assume. But my assumption would be that draw is an event, a function bind with addEventListener. That mean the context (this value) is the target of the event. My guess would be a canvas.
Logical Operators in JavaScript work a bit differently than most people expect.
Logical OR (||)
Returns expr1 if it can be converted to true; otherwise, returns
expr2. Thus, when used with Boolean values, || returns true if either
operand is true; if both are false, returns false.
So instead of the expression resulting in a boolean value, it returns the first value that isn't "falsey". This has the benefit of being a great way to fill in default values in case it is undefined, null, 0, or an empty string.
var myObj = { name: 'Josh' };
myObj.age = myObj.age || 33;
Logical AND (&&)
Returns expr1 if it can be converted to false; otherwise, returns
expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
Basically just the opposite. Since any expression that evaluates to false will short circuit the logical check, it can be useful to test for the existence of a field, before trying to use it.
var myObj = null;
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {};
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {person: {}};
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {person: {name: "Josh"}};
if(myObj && myObj.person && myObj.person.name === "Josh") // true
However! Caution should be taken here because in the case of both boolean values true or false and integer values 0 or anything not 0 you might end up overwriting a legitimate value.
Question 2: Not enough context

Categories

Resources