Reputation: 1219
I am having query to improve way of writing code in ES6.
I am calling a function when my variable sets to FALSE
Initially this.myVariable
sets to true
but under some logic it becomes false
and I call a function when my boolean is false
if(!this.myVariable) {
this.onClearSearch();
}
I am new to ES6 So i want to know is there any way to write this in some better way or one liner. This could be a very small logic but still it might give me better understanding to improve my code and logic.
Note : My Solution is also working.
Upvotes: 0
Views: 2697
Reputation: 494
If you want to check exactly for the value false
, you can do it like this:
if (this.myVariable === false) {
this.onClearSearch();
}
Note that I used the triple equal comparator (===
) to check for value and also type.
You can also of course do it the same you did it with !this.myVariable
but that would also be true for "falsy" values like 0
or ''
(the empty string).
If that's what you meant, I recommend you to check the concepts of Truthy and Falsy in JavaScript.
Upvotes: 0
Reputation: 3069
The following idiom is quite common in React code for conditional rendering:
!this.myVariable && this.onClearSearch()
Upvotes: 0
Reputation: 23575
There are no magic syntax in es6/7/8 that will improve the piece of code you showed to us.
Thought there are some alternative syntaxes you probably already know of.
I would personnaly recommand to you the styles A or B, because they are easy to understand and quick to write.
function onClearSearch() {
console.log('call');
}
const myVariable = false;
// Writting style A
if (!myVariable) {
onClearSearch();
}
// Writting style B
if (myVariable == false) {
onClearSearch();
}
// Writting style C
if (myVariable == false) onClearSearch();
// Writting style D
myVariable || onClearSearch();
// Writting style E
myVariable ? void 0 : onClearSearch();
// Writting style F
myVariable ? _ : onClearSearch();
Upvotes: 4