5

In ES6/ES2015 I can use Object destructuring to pull fields from objects passed as function parameters:

function userId({id}) {
  return id;
}

var user = { 
  id: 42, 
};

console.log("userId: " + userId(user)); // "userId: 42"

In the above example, is the id variable set in the userId function equivalent to setting it via var, const, or let ?

So which of the below is the equivalent function:

Var

function userId(user) {
    var id = user.id
    return id;
}

Let

function userId(user) {
    let id = user.id
    return id;
}

Const

function userId(user) {
    const id = user.id
    return id;
}

(Example function from MDN page linked above, jump to "Pulling fields from objects passed as function parameter)

2
  • Well you know it's not const, because within the function you can assign another value to id. Commented Dec 22, 2016 at 1:36
  • 1
    There's no meaningful difference between let and var in this case, since the scope of function arguments are always the entire function. Commented Dec 22, 2016 at 1:37

2 Answers 2

7

Declaring variables with destructuring uses the same scope as if you'd declared ordinary variables in the same position. So if you do:

let {id} = {id: 42};

then it's a let binding, if you do:

var {id} = {id: 42};

then it's a var binding.

Function parameters are like var bindings, since they're scoped to the entire function and they're not const. They're also like let bindings because they're scoped to the current block, which is the entire function body.

Sign up to request clarification or add additional context in comments.

4 Comments

"for a variable declared in the top-level block of a function, there's no difference between let and var": I like my wording better. function x() { var a = b; var b = a; } is okay; function x() { var a = b; let b = a; } is a ReferenceError. They are equivalent at the top of the function, not necessarily at top level of a function, because let doesn't hoist.
I think this is functionally true, yes, but is there anywhere I can read on an implementation level what is happening under the hood? I can't find anything on MDN.
@komali_2: Everything is in ECMAScript specification. It is a bit hard to read though if you're not used to it.
1

It will be a local variable scoped over the whole function (as all function parameters are), as in your first and second example (which are equivalent: there is no difference between let and var when at the top of the function).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.