-3

I have a very silly question to understand, Can you please help me with this

I want to do the check as below in javascript, which is better and can you please explain to me why

I am just checking whether my string path contains the value / at the last or not

  if (!(path.slice(-1) == '/')) {...}

OR

if (path.slice(-1) != '/'){...}

I have gone through all these questions and I didn't get the correct answer (I am okay to get downvotes but please answer me :))

Which is better way? Variables related

Code comparison - Which is better or unnecessary?

Which is better in GWT?

Which is better?

Which is better Intrinsics or assembly coding?

Mahesh G
  • 1,226
  • 4
  • 30
  • 57
  • 1
    Your question is about whether `x != y` or `!(x == y)` is better? Why would you presume that one is objectively better than the other? I would say neither should be used because both `!=` and `==` are crappy (better to use `!==` and `===`). But aside from that, my preference would be for `x !== y` because it avoids the extra parentheses. – JLRishe Aug 03 '18 at 14:41
  • 4
    If the you're debating between two logically equivalent approaches, choose the one that's easier to read. "Not equal" is more easily understood than "Equal, not." – Bucket Aug 03 '18 at 14:43
  • 1
    Here is your answer https://crockford.com/javascript/encyclopedia/#213D%20infix%20operator – pavi2410 Aug 03 '18 at 14:44
  • 1
    Array.prototype.slice() returns an array. So you're better off with this statement: path.slice(-1)[0] !== '/' – Harish Vangavolu Aug 03 '18 at 14:45

1 Answers1

4

First, for comparison it is preferred to use strict comparison operators (i.e., === and !==) when possible. Second, path.slice(-1) !== '/' is easier to understand for other people that read your code. Apart from that, these logical operators are equivalent and should have the same performance.

MTMD
  • 1,162
  • 2
  • 11
  • 23