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".

Jörg

CEO

LinkedIn
Zur Übersicht

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund