-3

I have 3 questions about my code here...

  1. I am trying to understand what the ! before the passenders.paid means?
  2. And also, what other options do I have for putting operators before the logic?
  3. In this example, why are all my answers true when Sue has false?

var passengers = [{
    name: "Jane Doloop",
    paid: true
  },
  {
    name: "Dr. Evel",
    paid: true
  },
  {
    name: "Sue Property",
    paid: false
  },
  {
    name: "John Funcall",
    paid: true
  },
];

for (var i = 0; i < passengers.length; i++) {
  if (!passengers.paid) {
    console.log(true);
  } else {
    console.log(false);
  }
}
Vinn
  • 1,030
  • 5
  • 13
  • 4
    `!` is a not operator. It makes `True` into `False` and `False` into `True` [Logical Not](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT) – ahsan Sep 08 '21 at 08:58
  • Does this answer your question? [What is the !! (not not) operator in JavaScript?](https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) – ahsan Sep 08 '21 at 08:59
  • You probably want `!passengers[i].paid`. Elements in the `passengers` array have a `paid` property, but the array itself probably never will. – Cat Sep 08 '21 at 09:01
  • I guess what I really want to know is... even if I have !passengers[i].paid.... the if logic is still TRUE. Why? I havent provided the " == true then" part – Vinn Sep 08 '21 at 09:03
  • @Vinn in js, and many other languages, if a property has value is considered `true` (except if that value is `false` or `null`) – sorioli computec Sep 08 '21 at 09:05
  • 1
    @soriolicomputec not if the value of that property is false. – Alnitak Sep 08 '21 at 09:06

3 Answers3

2

You're missing array indicator in if statement

var passengers = [{
    name: "Jane Doloop",
    paid: true
  },
  {
    name: "Dr. Evel",
    paid: true
  },
  {
    name: "Sue Property",
    paid: false
  },
  {
    name: "John Funcall",
    paid: true
  },
];

for (var i = 0; i < passengers.length; i++) {
  if (!passengers[i].paid) {
    console.log(true);
  } else {
    console.log(false);
  }
}

! is negative logic operator, it's fundamental and used in most programming languages.

maki000
  • 339
  • 1
  • 8
1

The ! is a Javascript NOT operator. It will negate any truthy value.

Documentation for it can be found Here.

Essentially it will flip any boolean value:

$> !true
false

$> !false
true
CEbbinghaus
  • 86
  • 1
  • 10
1
1. The ! is a Javascript NOT operator. It will make false if value is true and true if value is false.

2. You should put directly like as if (passengers.paid) {...}else{...}

3.It always true because passengers.paid always undefined so it will false in condition but you had put ! sign before it so it will true so it always print true. for right condition you should use if (!passengers[i].paid)
laxman
  • 1,338
  • 2
  • 10
  • 27