Just JavaScript - Parameters, and Destructuring
Written by Ian Elliot   
Monday, 05 March 2018
Article Index
Just JavaScript - Parameters, and Destructuring
Rest, Default Parameters, Destructuring

JustJavaScripticon

Rest (ES2015)

You can find out how many parameters are specified in a functions declaration using the function’s length property. For example:

function sum(a,b,c){
}
sum.length

is 3.

This is the number of parameters specified in the declaration not the number of arguments in the use of the function.

Notice that using the function length and arguments length properties we can easily work out how many more or fewer arguments have been supplied.

For example:

function sum(a,b,c){
 var total=a+b+c;
 for(var i=sum.length;i<arguments.length;i++){
   total+=arguments[i];
 }

 return total;
}

This will add the first three arguments using the parameters a,b and c and if there are any more it adds them from the arguments object.

To make this sort of thing even easier ES2015 added the rest parameter. If the last parameter of a function is prefixed with … then any additional arguments provided are stored in the final parameter as an Array.

So the previous function could be written:

function sum(a,b,c,...rest){
  var total=a+b+c;
  for(var i=0;i<rest.length;i++){
    total+=rest[i];
  }
 return total;
}

Notice that you don’t have to call the final parameter rest only the three dots matter. You don’t need the rest feature but it is slightly easier.

Default Parameters (ES2015)

JavaScript is so flexible that often we allow optional parameters that are set to a default if the user doesn’t make use of them. Obviously as JavaScript’s parameters are positional any optional parameters have to be last in the parameters list.

The traditional way of dealing with optional parameters is to test for undefined values. For example:

function add(a, b) {
  b = (typeof b !== 'undefined') ? b : 1;
  return a + b;
}

If you don’t supply a value for b then it is set to 1.

ES2015 introduced default parameter values which work in much the same way. For example:

function add(a, b=1) {
  return a + b;
}

sets b to 1 if it isn’t provided.

Notice that ES2015 default parameters are compiled to exactly the code given earlier. That is if you pass in undefined then the default value will still be used but any other value including null etc, will not be replaced by the default. Also notice that the default value can be any valid expression including function calls and this is evaluated each time the function is called. These default expression are evaluated in order of the parameters and earlier defaults can be used in later parameter defaults. For example:

function add(a=1,b=a+1){

b is set to a+1 if it isn’t supplied.

Destructuring (ES2015)

Although destructuring is a general facility it has some particularly important used in connection with functions and it can be seen as a generalization of the way the arguments object is unpacked or destructured into the parameter variables.

The basic idea of destructuring is that it will unpack the values in an array or the properties in an object into individual variables. The syntax is simply to assign to a structure of the same type but with variables rather than values.

For example:

var a,b;
[a,b]=[1,2]

or

var [a,b]=[1,2];

assigns 1 to a and 2 to b. Notice that [1,2] is an array literal but the destructuring works with a general Array object.

Destructuring an object is very similar:

var {x:a,y:b}={x:1,y:2};

This assigns 1 to a and 2 to b. Notice that you have to use the property names to determine which property maps to which variable. For example:

var {y:a,x:b}={x:1,y:2};

assigns 2 to a and 1 to b.

As a shorthand you can destructure to variables with the same name as the properties. For example

var {x,y}={x:1,y:2};

which is a short form of

var {x:x,y:y}={x:1,y:2};

You should be able to see that Array destructuring is a lot like the way arguments is unpacked into the parameter variables and the similarity is more than skin deep.

For example, you don’t have to unpack all of the elements of an Array, you can use the rest notation to set an Array to take any part of the source Array that isn’t used and finally you can set default values.

For example:

var [a,b,c=3,...d]=[1,2];

assigns 1 to a, 2 to b, 3 to c and d is an Array of length 0 and

var [a,b,c=3,...d]=[0,1,2,3,4,5];

assigns 0 to a, 1 to b, 2 to c and d is [3,4,5].. Notice that the default value is only used if the source element is undefined. Also keep in mind that default values can be arbitrary expressions that evaluate to objects.

So to summarize:

  • You don't have to define any parameter when you create a function.
  • Any arguments that you specify when you call the function are packed into arguments an Array like object.
  • If you want to pass an array of values to become the arguments object you can use the ES2015 spread operator ...
  • You can set a final parameter to accept the part of the arguments object that wasn't unpacked using the rest operator ...
  • If you do define parameters in the function declaration then the arguments object is destructured into them.
  • You can use destructuring on other arrays and objects.
  • ES205 adds default values to parameters which is exactly like the way you would have done it in ES5.

 

 

This is an extract from the book Just JavaScript by Ian Elliot.

Buy Now: from your local Amazon

Just JavaScript 
An Idiomatic Approach

JustJavaScriptSmall

A Radical Look At JavaScript

 

Most books on JavaScript either compare it to the better known class based languages such as Java or C++ and even go on to show you how to make it look like the one of these.

Just JavaScript is an experiment in telling JavaScript's story "just as it is" without trying to apologise for its lack of class or some other feature. The broad features of the story are very clear but some of the small details may need working out along the way - hence the use of the term "experiment". Read on, but don't assume that you are just reading an account of Java, C++ or C# translated to JavaScript - you need to think about things in a new way. 

Just JavaScript is a radical look at the language without apologies.

Contents

  1. JavaScript – Essentially Different
  2. In The Beginning Was The Object
  3. Real World Objects 
  4. The Function Object
          Extract - The Function Object
          Extract - Function Object Self Reference
  5. The Object Expression
  6. Function Scope, Lifetime & Closure
    Extract Scope, Lifetime & Closure
    Extract Execution Context ***NEW!
  7. Parameters, Returns and Destructuring
         Extract - Parameters, and Destructuring
  8. How Functions Become Methods
  9. Object Construction
         Extract: - Object Factories
  10. The Prototype
         Extract - ES2015 Class and Extends
  11. Inheritance and Type
  12. The Search For Type
  13. Property Checking

Buy Now: from your local Amazon

Also by Ian Elliot 
JavaScript Async: Events, Callbacks, Promises and Async Await
Just jQuery: The Core UI 
Just jQuery: Events, Async & AJAX  

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

espbook

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Monday, 05 March 2018 )