0

In javascript re-introduction, I went through 2 examples that I have no clue when or where to use them. Below a quote:

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes: var name = o && o.getName();

Or for caching values (when falsy values are invalid): var name = cachedName || (cachedName = getName());

Will the name contain boolean, if yes, what is the use then? This is might be a noob question, but I wish someone can explain it with an example.

Community
  • 1
  • 1
  • https://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean , https://stackoverflow.com/questions/6970346/what-is-x-foo – Teemu Feb 11 '20 at 18:34

1 Answers1

0

var name = o && o.getName();

This code is used to avoid errors if o is undefined.

var name = cachedName || (cachedName = getName());

This code will be used if getName is costly operation like network call. This will help us to call the getName only the first time and second time it gets from the cachedName

vishnu sandhireddy
  • 1,148
  • 1
  • 7
  • 12