JS: What is the difference in assigning a processed value directly to a variable and assigning without processing and then processed using && operator

I saw a function that receives a string parameter then performs some operations with it; like this:

const val = this.searchParam && this.searchParam.trim().toLowerCase();

My question is, why don’t assign directly the processed string? Like this:

const val = this.searchParam.trim().toLowerCase();

I tried this in JS Bin to see if there’s a difference, and the result is the same.

What do they exactly use the && operator?

Thanks,

>Solution :

In code snippet below, the first log writes undefined, the second throws an error:

searchParam = undefined

console.log(searchParam && searchParam.trim().toLowerCase());
console.log(searchParam.trim().toLowerCase());

Therefore, the result is not the same

Leave a Reply