Reputation: 10135
I encountered this piece of code:
var value = this.newTodo && this.newTodo.trim();
In this example: http://codepen.io/anon/pen/rONEMQ?editors=101
I don't understand what the AND (&&) operator is trying to accomplish.
In my understanding the && Operator is to asign multiple properties to a value, but this doesn't seem to be the case here.
I my code example, I don't see any difference, for when I use this:
var value = this.newTodo && this.newTodo.trim();
Instead of this:
var value = this.newTodo;
Or just this:
var value = this.newTodo.trim();
Can anyone explain, what the initial line stated above and in the example does with the &&?
Upvotes: 1
Views: 267
Reputation: 31
Because Javascript is a loosely typed language, the boolean operators &&
and ||
can take any type as operands.
The &&
operator operates from left to right, returning the first "falsy" operand. If no falsy operand is found, the last operand is returned
The ||
operator operates from left to right, returning the first "truthy" operand. If no truthy operand is found, the last operand is returned.
Falsy values are ""
, ''
, 0
, false
, undefined
, null
, NaN
Truthy values are all other values. Interestingly, the empty object {}
and empty array []
are both truthy.
Example:
this.newTodo = "Hello World";
let value = this.newTodo && this.newTodo.trim();
First this.newTodo
is tested if is truthy or falsy. It is truthy so we move to the next operand: this.newTodo.trim()
. this.newTodo.trim()
is also truthy so we return the latest operand, which is this.newTodo.trim()
. So the value
variable is assigned "Hello World"
.
this.newTodo = " Hello World";
let value = this.newTodo && this.newTodo.trim();
this.newTodo
is truthy, so we move to the 2nd operand. this.newTodo.trim()
is also truthy. Since no more operands, and we haven't found a falsy operand, we return this.newTodo.trim()
, which is "Hello World"
. So the value
variable is assigned "Hello World"
.
If this.newTodo
were a falsy value such as null
or undefined
or ""
, then we would never move to the 2nd operand, but just return the 1st operand.
I suppose the purpose of the expression
let value = this.newTodo && this.newTodo.trim();
is to avoid calling the trim function on this.newTodo
if it's falsy.
Upvotes: 1
Reputation: 1
var value = this.newTodo && this.newTodo.trim();
if this.newTodo is not one of "falsey" values, i.e. ""
, 0
, false
, undefined
, null
, []
(I'm sure I'm forgetting some), then value = this.newTodo.trim()
, otherwise value = this.newTodo
(which could be ""
, 0
, false
, undefined
, null
, []
etc)
I my code example, I don't see any difference, for when I use this:
var value = this.newTodo && this.newTodo.trim();
Instead of this:
var value = this.newTodo;
if this.newTodo is "Hello World"
... you're right, there is no difference
if this.newTodo id " Hello World "
... value will be "Hello World"
... i.e. trimmed of leading and trailing spaces
Upvotes: 1