As per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
The expr1 || expr2 makes sense to me. It short circuits the expression and returns the first one, and it makes sense. I use it often to select the passed variable vs the default one. For ex.
var default_connection = 'localhost:27017/task_master';
function setdb(connection){
var conn_str = connection || default_connection;
//Do something here
}
The &&
behaviour just beats me and appears very unreadable to me.
expr1 && expr2
- Returns expr1
if it can be converted to false; otherwise, returns expr2
.
Can someone please help me understand this and suggest some use cases where the &&
can be useful.
EDIT: Found it from the suggested original question. This gives me a good enough reason to use it.
&& is sometimes called a guard operator.
variable = indicator && value
it can be used to set the value only if the indicator is truthy.
My question was that, "Can someone please help me understand this and suggest some use cases where the &&
can be useful.". I don't know which part of this question was hard to understand. I gave an example of how I found || useful, and the reason above gives a good enough reason how && can be useful too. Yes, I am new to JavaScript, and yes, I am not as smart as you all are. But being a little kind will help me get there. Peace!