Run Statement As Condition In If Statement In JavaScript
The basic syntax for the if statement in JavaScript is this:
if(true){
do something;
}else{
do something;
};
What else?
One useful feature of the if statement in JavaScript is that we can also run othe statement and verify if the result is true then proceed the if statement.
For example,
if(x = true){
console.log("It is true.");
}else{
console.log("It is false.");
};
console.log(x);
//It is true.
//true
One thing weird about the x?
Note that the x in the above example is a global variable without being declared before used as the output in an if condition expression.
Why is running some code in the if condition expression is useful?
This is useful when I want to find out if somehitng exists in an array and want to do something with this particular item.
For example,
var arr = [1,2,3];
if(x = arr.find(y=>{return y == 1})){
console.log(x + ", which is in the array.");
}else{
console.log(x + ", oops.");
};
//1, which is in the array.
if(x = arr.find(y=>{return y == 4})){
console.log(x + ", which is in the array.");
}else{
console.log(x + ", oops.");
};
//undefined, oops.
Without this method
Let's find out how I would write the code without the above method.
var arr = [1,2,3];
var item = arr.find(y=>{return y == 1});
if(item){
console.log(item + ", which is in the array.");
}else{
console.log(item + ", oops.");
};
//1, which is in the array.
This takes one more line to get the job done and the code block can't be reused.
Consider 2 arrays
Old method:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var item1 = arr1.find(y=>{return y == 1});
var item2 = arr2.find(y=>{return y == 4});
if(item1){
console.log(item1 + ", which is in the array.");
}else{
console.log(item1 + ", oops.");
};
if(item2){
console.log(item2 + ", which is in the array.");
}else{
console.log(item2 + ", oops.");
};
New method:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
if(x = arr1.find(y=>{return y == 1})){
console.log(x + ", which is in the array.");
}else{
console.log(x + ", oops.");
};
if(x = arr2.find(y=>{return y == 1})){
console.log(x + ", which is in the array.");
}else{
console.log(x + ", oops.");
};
The new way makes the code much simpler and more reusable.
Comments
Post a Comment