-5

I've was given this is a multiple choice JS question. I said [], I just wanted to check if this is correct and if not why?

Consider this if statement:

if (loggedIn) {
  body_classes = ["user-active"];
}

Which pair of characters in this code is optional?

""
()
{}
[]
Barmar
  • 741,623
  • 53
  • 500
  • 612
Pianoc
  • 763
  • 1
  • 11
  • 32
  • 6
    No, the answer is `{}` because they are not necessary in single-line if-statements. – Wais Kamal Dec 21 '20 at 17:26
  • The braces `{}` are optional as it is a single line if statement. The brackets `[]` aren't optional because in this case they are creating a single element array. – imvain2 Dec 21 '20 at 17:28
  • In your question you should explain *why* you think `[]` are optional? Then we could help you understand the error. – Barmar Dec 21 '20 at 17:29
  • Note that while the `{}` are optional, they're highly recommended. See https://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar Dec 21 '20 at 17:30
  • if two variables `user` and `active` exist, three are optional. If not, only two are optional, in the sense that they can be omitted but still produce valid syntax (wether they are semantically "optional" is another thing). So the answer depends on what "optional" means. – Jonas Wilms Dec 21 '20 at 17:30

1 Answers1

3

The optional characters are the braces {}

if (loggedIn) {
  body_classes = ["user-active"];
}

is the same as

if (loggedIn)
  body_classes = ["user-active"];

If you remove the square brackets then body_classes becomes a string rather than an array.

Fraser
  • 15,275
  • 8
  • 53
  • 104