JavaScript Basic: Study Note For Boolean Logic and Logical Operators

Boolean Logic: True & False

Boolean is one of the five primitives. There are only two possible options for Boolean value:True or False.

Boolean logic is simple writing statements that evaluate to be true or false. Then, we can combine those initial statements to create more complex statement that also evaluate to true or false.

Comparison Operators

2204783-0fd37794d93859bb.JPG
screenshot from Udemy course lecture

Most of those operators are very easy to understand. I just want to mention two of them, which are “==” and “===”.

Those two operators are all equal sign, but they are different. According to the course,“==” performs type coercion which means that it takes two numbers (or strings or variables) and tries to turn them into a similar type so that we can compare them.

In the meanwhile,“===” does not perform type coercion. 

For example:

var x = 5;

x == “5” //true(“5” is a string. The “==” turns the string “5” to a number 5, so they can be equal. The result will be true)

x===”5″ //false(The “===” can’t turn string “5” to a number 5. Since these two “5” are different types, so the result is false)

Logical Operators

For the “&&”, x<5 is true, x!==5 is false, since one true and one false, the result is false. If we want the result to be true, we need to make sure both sides are true.

For “||”, one side is true, the whole thing is true. x===5 is true, so the result is true.

For “!”, x===y is false, but the !(x===y) interprets x is not equal to y, so the result is true.

2204783-d32a5da0347db21d.JPG

Truthy and Falsy Values:

According to the lecture, values that are not actually true or false, are still inherently “truthy” or “falsy” when evaluated in a Boolean context.

Falsy Values are: false, 0, ””, null, undefined, and NaN. Everything else is truthy.

2204783-b36a46615560dc17.JPG

When I type  a “!” (Not) operator in front of each falsy values, the results are all true. Therefore, those values are fasly values.

猜你喜欢

转载自blog.csdn.net/weixin_34232617/article/details/90862005
今日推荐