Skip to content

Instantly share code, notes, and snippets.

@orenaksakal
Last active May 20, 2018 14:30
Show Gist options
  • Save orenaksakal/db5241f0f17efd23fe99b6fb159b14b0 to your computer and use it in GitHub Desktop.
Save orenaksakal/db5241f0f17efd23fe99b6fb159b14b0 to your computer and use it in GitHub Desktop.

Default Parameters

WHAT IS A PARAMETER ?

Parameter is a variable found in the function definition.
In compilation phase when we are on the line of a function definition with a parameter 
that parameter is registered to function's lexical scope as a local variable.

PARAMETER === LOCAL VARIABLE

var foo = 'global.foo';
var baz = 'global.baz';

function bar(foo){
    console.log(foo);
    foo = 'bar.local.foo';
    console.log(foo);
    baz = 'bar.local.baz';
}

bar();
console.log(foo);
console.log(baz);

So now we know its true that paramaters are local variables and if we invoke a function without argument (undefined argument) our parameter will be initialized as undefined. This can cause problems if we are not careful enough.

ES5 VERSION OF DEF PARAM

function greet(title, name){
	title = title || 'default title';
name = name || 'default name';
    console.log('Hello %s %s', title, name);
}

greet('Mr', 'Potato');
greet();

ES6 VERSION OF DEF PARAMS

let greet = (title = 'default title', name = 'default name') => {
    console.log('Hello %s %s', title, name);
}

greet('Lord', 'Potato');

DEF PARAM IS ASSIGNED ONLY IF ARGUMENT IS UNDEFINED AND YOU CAN ASSIGN FUNCTION INVOCATIONS TO DEF PARAMS

function isRequired(field){
    throw new Error(field + ' is required');
}

function greet(title = isRequired('title'), name) {
    console.log('Hello %s %s', title, name);
}

greet();

DEF PARAMS ARE AVAILABLE TO LATER DEF PARAMS

let autoPluralize = (name, pluralName = name + 's') => {
    console.log('Hello %s', pluralName);
}

autoPluralize('phone');

WATCHOUT

// functions defined in function body will throw

//Referance Error
function foo(bar = baz()) {
    function baz() { return 'baz'; }
}
    
foo();

Deconstruction assignment is also possible to use while assigning def params

function foo([bar, baz] = [1, 2]) { 
  return bar + baz; 
}

foo();
foo([3,4]);

Thats it thank you for your time :)
05.03.2018 - Warsaw - Ören Aksakal

Sources you may find useful;

https://www.sitepoint.com/es6-default-parameters/
https://www.youtube.com/watch?v=0_5Nns9YgjQ
https://codeburst.io/parameters-arguments-in-javascript-eb1d8bd0ef04
https://medium.freecodecamp.org/learn-es6-the-dope-way-part-iv-default-parameters-destructuring-assignment-a-new-es6-method-44393190b8c9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment