1.Truthy and Falsy values :
In javascript, any variable with a value, such as a string that has characters in it,
a numeric that is non-zero,or a Boolean true is considered true,and you can use it in an
if statement like that.
Any variable that is a Boolean false,null,undefined,Not a number,or an empty string is considered false.
ex : check for 'truth' values
let price =100;
let color = "Red";
// Check if price has something other than zero
if(price){
console.log("Price is > 0"); // Price is > 0
}
// Check if color has characters in it.
if(color){
console.log("color has a value"); // color has a value
}
ex: check for 'false' values
let color = "Red";
// Set value to null, it becomes false
color =null;
console.log("color == null = " + Boolean(color)); // color == null = false
// Set value to empty string, it becomes false
color ="";
console.log("color == '' = " + Boolean(color)); // color == '' = false
// Set value to undefined,it becomes false
color=undefined;
console.log(" color == undefined = " + Boolean(color)); // color == undefined = false
// Declare variable and don't initialize, it is false
let value;
console.log(" ' let value ' = " + Boolean(value)); // ' let value ' = false
// Result of NaN is false
value = 100/"test";
console.log(" 100 / 'test' = " + Boolean(value)); // 100 / 'test' = false
2.Logical Operators
Logical AND (&&):
In javascript, the logical AND operator will return true if both operands are true.
When using the AND operator, both sides must return true for the expression to be true.
Logical OR (||):
In javascript, the logical OR operator returns true if either operand is true.
When using the OR opeartor,only one expression needs to be true for the expression to be true;
Logical NOT (!) :
In javascript, the logical NOT operator negate anything
3.short Circuiting :
-> short circuiting is simply an optimization for logical expressions.
-> short circuiting allows javascript to do is to bypass subsequent expressions in And or Or conditions based on truthy or falsy.
ex : short circuiting (&&)
let result;
// if first result is false, the second part is never evaluated
result = isColorRed("Black") && isGreaterThan1400(1400); // false
function isColorRed(value){
console.log("In the isColorRed() function");
return value === "Red";
}
function isGreaterThan1400(value){
console.log(" In the isGreaterThan1400() function");
return value > 1400;
}
ex : short circuiting (||)
let result;
// Each expression is evaluated until one returns a true
result= isColorRed("Red") || isGreaterThan1400(200); // true
// In the isColorRed() function
// Each expression is evaluated until one returns a true the rest are then skipped
result = isGreaterThan1400(200) || isColorRed("Black"); // false
// In the isGreaterThan1400() function
// In the isColorRed() function
No comments:
Post a Comment