2

If I have this piece of code (which uses destructuring) seems it's creating new variables ss and pp.

But what is the scope of these? Are they created as var or as let variables?
Are they function or block scoped?

let config = {
    server: 'localhost',
    port: '8080',
    timeout: 900,
};
/* no let or var here */ ({server : ss, port : pp} = config); 
console.log(ss, pp);

My question is not duplicate of the one suggested. I know about var and what happens if you omit it. The real answer I was looking for here is the one Barmar provided. I just wasn't sure if destructuring assignment behaves exactly the same as normal assignment, or under the hood it assumes var (function) or let (block) scope. That's all. Destructuring was introduced in JS many years after the other question was asked. So it was logical to assume destructuring assignment may have somewhat different semantics than usual assignment. As Barmar confirmed, this is not the case, so I am all set.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • 2
    Possible duplicate of [What is the purpose of the var keyword and when should I use it (or omit it)?](https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it) – JK. Nov 14 '19 at 00:42

3 Answers3

3

They're global variables, just like in normal assignments. Your code is just shorthand for:

ss = config.server;
pp = config.port;
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

They are global. You can even prove this out through slight modification of your example. The console.log statements both work in the following snippet. Both would fail if it was block-scoped, the first would pass but second would fail if it was function-scoped, but clearly both work.

(function() {
  {
    let config = {
        server: 'localhost',
        port: '8080',
        timeout: 900,
    };
    ({server : ss, port : pp} = config); 
  }

  console.log(ss, pp);
})();

console.log(ss, pp);
Nick
  • 16,066
  • 3
  • 16
  • 32
1

They will be global variables. Any assignment of a variable that is not declared will be global.

Source: https://www.w3schools.com/js/js_scope.asp

Skylar
  • 928
  • 5
  • 18