One-line short-circuit evaluation with && || in JavaScript - javascript

var prefix = options && options.prefix || '';
In JavaScipt in my case. Can someone explain what kind of statement or condition is this? Or at the end what's the value of prefix variable?
I know about (ternary operator):
condition ? expr1 : expr2
but this was different.

This one-liner is the equivalent of saying:
var prefix;
if(options && options.prefix){
prefix = options.prefix;
} else{
prefix = '';
}

The statement is setting the variable "prefix" to either the value of "options.prefix", or an empty string, in such a way that if "options" does not exist, it does not throw an error.

The reason this works is in Javascript logical operators evaluate to the value of the last operand.
So is options object exist, the && part of the expression will be evaulated to options.prefix.
If that is not set, the left part of the || expression will be false and the right part = the '' string - will be returned.

Its similar to following:
var prefix;
if(options){ // or for better understanding, its if(options != undefined)
prefix = options.prefix;
}
else
prefix = '';
Try the following fiddle for better understanding:
http://jsfiddle.net/n41tfnh4/1/

Translated into human language
If variable optionsis defined with some non-falsey value
and it also has a property options.prefix whose value is also non-falsey
then set the variable prefix with this options.prefix value.
Otherwise, our prefix is set to empty string by default.
PS. Quickly check the complete list of falsey values in JavaScript by google "javascript falsy values"
Quicker explanation
This is a quick value check (and get) of options.prefix which is empty string by default.
(without throwing an exception when options is undefined)

It means, it options is an object, use options.prefix. If options.prefix is undefined or null or other falsy value, return empty string.
Nearly same meaning of options ? options.prefix : ''.

If prefix is available on options, set it to var prefix. Otherwise, set it to an empty string.

Related

Javascript Ternary operator with empty else

I'm trying to convert the following if-else to it's ternary operator representation in javascript as follows
var x = 2;
if (x === 2) {alert("2");}
else
{ //do nothing}
But when I do this:
(t==2)?(alert("1")):();
Chrome throws a SyntaxError.
My question is -
How to have a ternary operator in javascript with an empty "else" branch - i.e the part that comes after ":".
Also, is this allowed- using a ternary operator in javascript to execute statements - NOT do assignment.
Also: the above code was just a base case. I'm actually trying to get all the DOM elements of the page as an array (called all2) and then add only those elements to another array (called only) only if they have non-null class names. Here is my code:
all2.forEach(function(e){ e.getAttribute("class") ? (only.push(e.getAttribute("class"))) : (); });
If I leave the third operand blank, it throws a syntax error. Passing a null works
Answer to your real question in the comments:
all2.forEach(function (e) {
e.getAttribute("class") && only.push(e.getAttribute("class"));
});
Do this :
(t==2)?(alert("1")):null;
You could replace null by any expression that has no side effect. () is not a valid expression.
You putted a lot of useless parentheses, and the best NULL value in js is undefined.
document.getElementById('btn-ok').onclick = function(){
var val = document.getElementById('txt-val').value;
val == 2 ? alert(val) : undefined;
}
<input id="txt-val" type="number" />
<button type="button" id="btn-ok">Ok</button>
using a single line if statement is better though
if(value === 2) alert(value);
you have a few options to do this nicely in one line:
option1 - noop function
set a global noop function:
function noop(){}
(t==2)?(alert("1")):(noop());
option2 - && operator
when you use && operater, operands are evaluted only if previos ones where true, so you could miply write:
(t==2) && alert("1");
or, for exapmle if you have an arry you want to push to, you could test it is not null before:
arr && arr.push(obj)
I don't like it's either. So you're on the right track looking for alternatives.
In this case, I would write:
t===2 && alert("2")
Your idea is valid too, for instance you can do this:
t===2 ? alert("2") : null
But it's four extra chars.
In that case you don't need to use Ternary operator. Ternary operator requires a third argument.
condition ? expr1 : expr2
Lokki at Conditional (ternary) Operator
You can use the if statement
if ( t == 2 ) alert(1);
NO, you can't have empty else, better don't use the ternary operator, it requires a third argument. Go with simple if condition.
if(t==2) alert("2");

Var's boolean value in JavaScript

I am not so expert in JavaScript and I am wonder if there is a way to test the boolean value of a variable in javascript.
In Python I can do this:
>>>list_var = []
>>>bool(list_var)
False # This is the boolean value of a empty list
>>>
And if I try get an element in JS that does not exist, i.e:
document.getElementById('b-advanced')
[] // This is what returns
Is there a way to test the expression above as boolean without using an if... statement?
EDIT
I think I need to point something.
This is the full expression I use:
angular.element(document.getElementById('b-advanced'))
There is not. The best you can do is list_var.length === 0. For a full test, you'd want to test as follows
// Return true if arg is an array or string containing at least one item
function isTrueness(arg) {
return !!(arg && arg.length > 0);
}
angular.element(isTrueness(document.getElementById('b-advanced')));
You can use !! in front which will return its boolean status.
!![] // true
!!null // false
var x = Boolean(document.getElementById('b-advanced'));
Boolean is a wrapper for boolean values.
you can test to see what type a variable is by using typeof so for example:
var myVar = true;
if (typeof myVar === "boolean") console.log("It is a boolean");
In Python, an empty list is false. In Javascript, an empty array is true. You can mimic this by saying myArray.length && myArray. If myArray is empty, then its length is zero and the expression is false. If myArray isn’t empty, then Javascript returns the second operand, just like Python.

Is it safe to use length instead of ==""?

Is it safe to use length property instead of =="" for empty string validation?
Is it valid on all bool operators?
It might be a very simple question and I am pretty sure that the answer is a yes/yes, but I am using it a lot recently and I am a bit worried about any possible pitfall.
For completeness, here is a simple example
var valid = name.length && (foo.length||bar.length);
It is always safe to use .length IF you know for sure that you have something in the variable that can have properties (like a string).
But, if the variable might be undefined or null, then .length will not be valid and will not do what you want and name === "" would be safer.
Many Javascript developers simply do:
if (name) {
//
}
This checks for any truthy value in name. So, the if will not be satisfied if name is undefined, null or even an empty string "" and, in some cases, protects your code a bit more than what you were doing.
Or, in your example, you could perhaps just do:
var valid = name && (foo || bar);
This will require name and either foo or bar to be truthy. This won't protect against name, foo or bar being some type of data without a .length property like your original code would, but it would do a better job of protecting against any of these variables being undefined or null.
Remember that an empty string "" is a falsey value so you can use that to your advantage in boolean comparisons.

What's this JavaScript syntax?

I am new to JavaScript. The following code is from some production codebase.
The regDefinition is passed in JSON form. But I am not quite sure about the syntax in the method body.
Especially the || and [] parts.
function getCookieValue(regDefinition) {
return (document.cookie.match(regDefiniation.regEx) || [])[regDefiniation.index] || null;
}
It looks like someone has made a lot of effort to make this very hard to read.
If I interpret it right, it does something like this:
call the match method.
it returns an array of matches, or nothing (null, undefined?). If it doesn't return anything, default to an empty array.
Of the array, get the element with index 'regDefiniation.index'.
If that item doesn't exist (which can be the case for matches, and will always be the case for the empty default array), return null.
There are some good answers here, but nobody seems to really be explaining why you'd do
(foo || [])[bar]; // or similarly (foo || {})[bar]
instead of just
foo[bar]
Consider case the RegExp failed,
var foo = null, bar = 0;
Now without anything special you'd get an error thrown and the code would stop
foo[bar]; // TypeError: Cannot read property '0' of null
However the parenthesised-or version will be different
(foo || [])[bar]; // undefined (note, no error)
This is because the result of (null || []) is [], and you can now try to read a property of it safely
document.cookie is a string that contains the cookies associated with the current page. The document.cookie.match(regDefiniation.regEx) function call is searching this string with a regular expression to get a list of substrings that match.
If nothing in the cookie string matches the regex, the match call will return null, so the || [] is there to replace that null with an empty array. This ensures that the expression (document.cookie.match(regDefiniation.regEx) || []) always returns an array.
The [regDefiniation.index] is just retrieving an element from that array. But if the requested index doesn't exist in the array — for example, if the array is empty because the regex didn't match anything in the cookie string — the result will be undefined, so the || null changes the result to null in that case.
So to understand this let's dig into this example
var myValue = someValue || otherValue
So here if someValue can be converted into true then myValue would contain someValue else it would contain otherValue
// Values that evaluate to false:
false
"" // An empty string.
NaN // JavaScript's "not-a-number" variable.
null
undefined // Be careful -- undefined can be redefined!
0 // The number zero.
Anything else would return true
So to understand your code let's break it
var myCookie = document.cookie.match(regDefiniation.regEx) || []
So here if document.cookie.match(regDefiniation.regEx) returns true then return it else return the empty array.
Same for other part too. For more information of logical operators in JavaScript please follow the following link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Here's the step-by-step:
document.cookie returns a string and match method (inbuilt) is applied to that. If the parameter is in regDefiniation.regEx found, then do this else return [] (i.e., array)
After this, whatever is returned by above step, apply indexing to that with [regDefiniation.index].
`If all the above steps fail, then return null.

is there any function like string.isnullorempty() in javascript

I always (thing != undefined || thing != null)?...:...; check. Is there any method will return bool after this check in javascript or jquery ?
And how would you add this check in jquery as a function?
if (thing)
{
//your code
}
Is that what you are looking for?
In Javascript, the values null, undefined, "", 0, NaN, and false are all "falsy" and will fail a conditional.
All other values are "truthy" and will pass a conditional.
Therefore, you can simply write thing ? ... : ....
Try this
function SringisEmpty(str) {
str=str.trim();
return (!str || 0 === str.length);
}
As the others here have mentioned, several things evaluate as "falsy" that you might not want to (such as empty strings or zero). The simplest way I've found in JavaScript to check for both null and undefined in one statement is:
thing != null
This is using type coercion (double equals instead of triple equals), so undefined values are coerced to null here, while empty strings, zero, etc. do not.

Categories

Resources