What does this javascript code snippet mean? - javascript

Here is the code snippet:
var prjId = navObj.itemId || navObj
Does this mean that prjId is either equal to navObj.itemId or navObj? What does it then mean that a variable is equal to navigation object?
Thank you in advance for answers!

This is equivalent to the following:
var prjId;
if(navObj.itemId)
prjId = navObj.itemId;
else
prjId = navObj;

If navObj.itemId is set to false or has not been defined at all,
prjId = navObj;
otherwise:
prjId = navObj.itemId;.

No. The || operator first tries to convert navObj.itemId to a Boolean value.
It will be converted to true if it is already the Boolean value, true, a number other than 0 or NaN, a non-empty string, or an object that is not null or undefined. These are known as "truthy" values.
It will be converted to false if it is already the Boolean value false, 0, NaN, an empty string, null or undefined. These are known as "falsey" values.
If navObj.itemId is "truthy", navObj.itemId is assigned to prjId, otherwise navObj is assigned to prjId.
Further Reading
Logical Operators

It simply means that if the left operand of the logical or operator (||) is a truthy value then return it otherwise return the right operand.
The following values are always falsy:
false
0
empty string
null
undefined
NAN (not a number)
So if navObj.itemId doesn't evaluate to anything of the above, then it will be assigned to the prjId variable.
This is widely used when we have optional parameters in a function, for example. It is a way of specifying the default value for an optional parameter. But of course that's not the only use of it.

It sets prjId to the property of itemId on navObj, if it exists (evaluates to 'truthy'), if it doesn't exist (or it evaluates to 'falsy'), prjId gets set to navObj.

Related

Conditional `&&` operator on object property renders the value of the property in React [duplicate]

I know that in JavaScript you can do:
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";
where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.
However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?
var oneOrTheOther = someOtherVar && "some string";
What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?
Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.
Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:
true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything"; // 0
Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.
&& is sometimes called a guard operator.
variable = indicator && value
it can be used to set the value only if the indicator is truthy.
Beginners Example
If you are trying to access "user.name" but then this happens:
Uncaught TypeError: Cannot read property 'name' of undefined
Fear not. You can use ES6 optional chaining on modern browsers today.
const username = user?.name;
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Here's some deeper explanations on guard operators that may prove useful in understanding.
Before optional chaining was introduced, you would solve this using the && operator in an assignment or often called the guard operator since it "guards" from the undefined error happening.
Here are some examples you may find odd but keep reading as it is explained later.
var user = undefined;
var username = user && user.username;
// no error, "username" assigned value of "user" which is undefined
user = { username: 'Johnny' };
username = user && user.username;
// no error, "username" assigned 'Johnny'
user = { };
username = user && user.username;
// no error, "username" assigned value of "username" which is undefined
Explanation: In the guard operation, each term is evaluated left-to-right one at a time. If a value evaluated is falsy, evaluation stops and that value is then assigned. If the last item is reached, it is then assigned whether or not it is falsy.
falsy means it is any one of these values undefined, false, 0, null, NaN, '' and truthy just means NOT falsy.
Bonus: The OR Operator
The other useful strange assignment that is in practical use is the OR operator which is typically used for plugins like so:
this.myWidget = this.myWidget || (function() {
// define widget
})();
which will only assign the code portion if "this.myWidget" is falsy. This is handy because you can declare code anywhere and multiple times not caring if its been assigned or not previously, knowing it will only be assigned once since people using a plugin might accidentally declare your script tag src multiple times.
Explanation: Each value is evaluated from left-to-right, one at a time. If a value is truthy, it stops evaluation and assigns that value, otherwise, keeps going, if the last item is reached, it is assigned regardless if it is falsy or not.
Extra Credit: Combining && and || in an assignment
You now have ultimate power and can do very strange things such as this very odd example of using it in a palindrome.
function palindrome(s,i) {
return (i=i || 0) < 0 || i >= s.length >> 1 || s[i] == s[s.length - 1 - i] && isPalindrome(s,++i);
}
In depth explanation here: Palindrome check in Javascript
Happy coding.
Quoting Douglas Crockford1:
The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.
1 Douglas Crockford: JavaScript: The Good Parts - Page 16
According to Annotated ECMAScript 5.1 section 11.11:
In case of the Logical OR operator(||),
expr1 || expr2 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.
In the given example,
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";
The result would be the value of someOtherVar, if Boolean(someOtherVar) is true.(Please refer. Truthiness of an expression). If it is false the result would be "these are not the droids you are looking for...move along";
And In case of the Logical AND operator(&&),
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.
In the given example,
case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.
case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".
I see this differently then most answers, so I hope this helps someone.
To calculate an expression involving ||, you can stop evaluating the expression as soon as you find a term that is truthy. In that case, you have two pieces of knowledge, not just one:
Given the term that is truthy, the whole expression evaluates to true.
Knowing 1, you can terminate the evaluation and return the last evaluated term.
For instance, false || 5 || "hello" evaluates up until and including 5, which is truthy, so this expression evaluates to true and returns 5.
So the expression's value is what's used for an if-statement, but the last evaluated term is what is returned when assigning a variable.
Similarly, evaluating an expression with && involves terminating at the first term which is falsy. It then yields a value of false and it returns the last term which was evaluated. (Edit: actually, it returns the last evaluated term which wasn't falsy. If there are none of those, it returns the first.)
If you now read all examples in the above answers, everything makes perfect sense :)
(This is just my view on the matter, and my guess as to how this actually works. But it's unverified.)
I have been seeing && overused here at work for assignment statements. The concern is twofold:
1) The 'indicator' check is sometimes a function with overhead that developers don't account for.
2) It is easy for devs to just see it as a safety check and not consider they are assigning false to their var. I like them to have a type-safe attitude, so I have them change this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex();
to this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex() || 0;
so they get an integer as expected.

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

Is empty string treated as falsy in javascript?

I've noticed that if you have a statement as the following:
var test = "" || null
test will evaluate to null but if we do something like the following:
var test = "test" || null
test will evaluate to "test", the same holds true for any object in place of the string, so does javascript treat empty string as either a falsy or null value, and if so why? Isn't an empty string still an object, so shouldn't it be handled the same?
I've tested this out in FireFox, Chrome, IE7/8/9, and Node.
Does javascript treat empty string as either a falsy or null value, and if so why?
Yes it does, and because the spec says so (ยง9.2).
Isn't an empty string still an object
No. An primitive string value is no object, only a new String("") would be (and would be truthy)
String is not an object, it's a primitive like number or boolean.
The empty string, NaN, +0, -0, false, undefined and null are the only values which evaluate to false in direct boolean conversion.
A string isn't an object in JS. Other "falsy" values are: 0, NaN, null, undefined.
One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.
Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using
if (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */
In this case, you must check for it being really present or not:
if (typeof someObject.someProperty == "undefined")
/* now it's really not available */
SEE HERE
Yes an empty string is falsy, however new String("") is not.
Note also that it's well possible that
if (x) { ... }
is verified, but that
if (x == false) { ... }
is verified too (this happens for example with an empty array [] or with new String("")).

what does if(a) exactly check in javascript

What does if(a) exactly check in javascript? Can it check undefined? Can it check null? Can it check an empty string?
When do we need to use typeof a == 'undefined' or it could be covered by if(a)?
if evaluates a in a boolean context and uses the result to determine which code branch to execute. undefined, null and the empty string all evaluate to false in a boolean context.
typeof a === "undefined" is useful to check if the name a is defined (e.g. if a variable with that name exists in the current scope). Without this construct, accessing a directly would throw an exception if it is not defined.
Taken from the ECMAscript language specification, the if-Statement works as the following:
12.5 The if Statement
The production IfStatement : if ( Expression ) Statement is evaluated as follows:
Let exprRef be the result of evaluating Expression.
If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
Return the result of evaluating Statement.
Means, in such cases, it would try a toBoolean conversion which acts like this:
Table 11 - ToBoolean Conversions
Undefined: false
Null: false
Boolean: The result equals the input argument (no conversion).
Number: The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String: The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Object: true
It checks for a value not being false-ish, i. e. false, 0, undefined and null or an empty string. typeof a == 'undefined' is useful when you are curious if a value is undefined or not, since if (a) can't make the distinction between the false-ish values.
The conditional statement will only check for 'true' or 'false'.
in case of undefined the condition is not satisfied and control does not go into the loop.
typeof returns the type of operand. for details you may want to see this link
following values are considered as false in javascript conditions: false, null, undefined,'', 0, NaN
the answer by h2co3 is actually almost correct, you can not check for undefined variables in an if without typeof as this will cause a script error.
if you do this:
<script>
if (a) alert('hello');
</script>
you will get a script error and the if will not be evaluated (the result is the same in the sense that alert is not shown, but that's because the thread execution ended due to the script error.)
if you want to make sure a is defined you need to use the typeof test.

Categories

Resources