1

This is purely a javascript trivia question. When i open my console and type in:

{"a"}

This evaluates to "a". What does the curly brackets mean in this case? It can't be destructuring because there's no assignment, and because the thing inside the curly brackets is a constant string value.

acenturyandabit
  • 1,188
  • 10
  • 24

1 Answers1

3

It's a plain block - like the block of a for loop, only without the loop.

for (let i = 0; i < 1; i++) {
  "a"
}

The block also "evaluates" to "a", the final expression in it, which is why it gets logged by the console.

(This sort of statement completion value of a block, as opposed to an expression, is pretty much never seen or used in JavaScript - except when typing stuff into the console like this.)

A block

{
  // some code
  // NOT containing object literal syntax
}

is a bit like a for loop with a single iteration, and a bit like an IIFE - a segment of code with its own scope. But it's weird and confusing - best not to use plain blocks in real code.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Neat! In fact I do have a use case for it hahaha (and yeah i know its bad practice) - when I'm working on a codebase that could be split into multiple files but i dont want to (because webpack doesn't like my purejs and load time), I would use `(()=>{code})()` to scope chunks of code so my `let` statements are scoped. Bonus points for the IDE collapsing option for code surrounded by `{}`. Just using `{code}` instead of `(()=>{code})()` is so much nicer! – acenturyandabit Jun 18 '21 at 01:47