0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Julio Rodriguez
  • 499
  • 6
  • 16
  • 1
    Did you try it with `this.searchParam` being `null` or `undefined`? – Rafalon May 02 '22 at 06:39
  • 1
    The code expects that `this.searchParam` *may* be falsey and prevents an error to be thrown in this case. – deceze May 02 '22 at 06:40
  • 1
    the "duplicate" doesn't directly answers the question, but to answer it, its because in case this.searchParams is null or undefined (other falsy values), it will throw the classic `cannot call of null` or `cannot call of undefined`, with `&&` it ensures that it will only trigger the function calls if the searchParam is not falsy – I am L May 02 '22 at 06:42
  • 1
    its the sortcut of `if (this.searchParam) val = this.searchParam.trim().toLowerCase();` – I am L May 02 '22 at 06:44
  • 1
    @IamL That's missing an `else val = this.searchParam`… – deceze May 02 '22 at 06:45
  • 1
    @deceze not if its the default value. – I am L May 02 '22 at 06:56

1 Answers1

1

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

Rafalon
  • 4,450
  • 2
  • 16
  • 30