2

If I have a function like this:

function doSomething(opt)
{
}

And I call it like this:

doSomething({a: 234, b: 567});

Is there a Javascript equivalent of the PHP extract() function so that I could do this:

function doSomething(opt)
{
    extract(opt);

    alert(a); // 234
    alert(b); // 567
}

The with() statement is not recommended any more and using the 'this' variable accesses the global scope - not the functions scope.

UPDATE:

Currently I'm doing the extraction manually like this:

function doSomething (opt)
{
    var a = opt.a,
        b = opt.b;
}
5
  • 3
    Are you looking for destructuring? Commented Oct 2, 2019 at 11:00
  • 3
    could declare your function like function doSomething({a, b}) Commented Oct 2, 2019 at 11:03
  • what you are looking for is called destructuring. you can also do it like { a, b } = opt Commented Oct 2, 2019 at 11:06
  • @DragoşPaulMarinescu That's very close to what I'm after - is it an ES6 thing? Commented Oct 2, 2019 at 11:07
  • see documentation Commented Oct 2, 2019 at 11:10

2 Answers 2

3

You can use ES6 destructuring:

function doSomething({a, b})
{
    alert(a);
    alert(b);
}

Or

function doSomething(opt)
{
    const {a, b} = opt;
    alert(a);
    alert(b);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting note on this: I've now been looking up browser market share and IE11 still shows roughly 5-7% depending on the region. And with this browser not supporting destructuring (AFAIK) and my software being publicly usable on all types of website - I think I'll stick to the old fashioned method, like that shown in the question, in order to preserve BC. Thanks though.
1

Destructuring is one approach. Below is another approach.

JavaScript has a concept called Rest parameters.... collect rest of the parameters in an array. What does that mean?

function doSimething(...items) {
     items.forEach(() => {
        // you can do stuff with each of the items.
    });
}

You can call it doSimething(1); doSomething(3,5,h);

This approach could help you make the function be more generic and used in more places.

Additional information on JavaScript rest / spread parameters

1 Comment

I think this would be best for what I was after - though due to browser share I've decided to stick with an ES5 compatible solution. Which is a shame because this would be perfect for what I want.

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.