26.1.2022 |

Strings and logic in javascript

What happens if you compare two strings with a logical AND in javascript.

var pet = "Dog" && "Cat"

What ist the value of pet?

a) Dog

b) Cat

c) DogCat

d) an error occurred

e) Something else

Result b) the value is "Cat", cause Javascript ignores the operator and keeps the (last) value.

Because you're using &&, JavaScript is promising you that it will verify that both sides of the expression are true. In this case, "Cat" is just the last evaluated thing.

What happens if you compare two strings with a logical OR in javascript.

var pet = "Dog" || "Cat"

What ist the value of pet?

a) Dog

b) Cat

c) DogCat

d) an error occurred

e) Something else

Result a) the value is "Dog"

Using ||, JavaScript is promising you that at least one of the sides is true. Since "Dog" is true, it stops there and returns "Dog".

Lars Silberg
Zur Übersicht

Mehr vom DevSquad...

Sophia Brandt

Budibase: Open-Source Low Code Plattform

Sven Röttering

How To: Convert country codes to flag emojis