Javascript function parameter defaults

Default argument values in JavaScript functions [duplicate]

In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

and then you can call it like func(); to use default parameters.

function func(a, b) < if (typeof(a)==='undefined') a = 10; if (typeof(b)==='undefined') b = 20; alert("A: "+a+"\nB: "+b); >//testing func(); func(80); func(100,200); 

@Aftershock the == has some known issues, so it’s best practices to use === unless == is necessary. See stackoverflow.com/questions/359494/…

Strangely, I feel like firefox was letting me define default parameters. or at least, it certainly didn’t throw a syntax error. Chrome did: thanks chrome! And you you @Ravan

@Ziggy: As of FF 15.0, FF does indeed support default parameters. It is currently the only browser to do so but this feature is proposed for ECMAScript 6 — developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@Magnus, no, because the presence of the variable in the parameter list means it’s defined locally. Even if the caller omits the argument, it is defined locally as a variable of type undefined .

ES2015 onwards:

From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

If you’re going to handle values which are NOT Numbers, Strings, Boolean, NaN , or null you can simply use

(So, for Objects, Arrays and Functions that you plan never to send null , you can use)

Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because || operates on all falsy values ( «» , null , NaN , false , 0 ) too — which makes this method impossible to assign a param the falsy value passed as the argument.

So, in order to handle only undefined values explicitly, the preferred approach would be,

Источник

Default parameters

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Try it

Syntax

function fnName(param1 = defaultValue1, /* … ,*/ paramN = defaultValueN)  // … > 

Description

In JavaScript, function parameters default to undefined . However, it’s often useful to set a different default value. This is where default parameters can help.

In the following example, if no value is provided for b when multiply is called, b ‘s value would be undefined when evaluating a * b and multiply would return NaN .

function multiply(a, b)  return a * b; > multiply(5, 2); // 10 multiply(5); // NaN ! 

In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined . In the following example, b is set to 1 if multiply is called with only one argument:

function multiply(a, b)  b = typeof b !== "undefined" ? b : 1; return a * b; > multiply(5, 2); // 10 multiply(5); // 5 

With default parameters, checks in the function body are no longer necessary. Now, you can assign 1 as the default value for b in the function head:

function multiply(a, b = 1)  return a * b; > multiply(5, 2); // 10 multiply(5); // 5 multiply(5, undefined); // 5 

Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

function f(x = 1, y)  return [x, y]; > f(); // [1, undefined] f(2); // [2, undefined] 

Note: The first default parameter and all parameters after it will not contribute to the function’s length .

The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.

This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time ReferenceError . This also includes var -declared variables in the function body.

For example, the following function will throw a ReferenceError when invoked, because the default parameter value does not have access to the child scope of the function body:

function f(a = go())  function go()  return ":P"; > > f(); // ReferenceError: go is not defined 

This function will print the value of the parameter a , because the variable var a is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to b .

function f(a, b = () => console.log(a))  var a = 1; b(); > f(); // undefined f(5); // 5 

Examples

Passing undefined vs. other falsy values

In the second call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default.

function test(num = 1)  console.log(typeof num); > test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: test(""); // 'string' (num is set to '') test(null); // 'object' (num is set to null) 

Evaluated at call time

The default argument is evaluated at call time. Unlike with Python (for example), a new object is created each time the function is called.

function append(value, array = [])  array.push(value); return array; > append(1); // [1] append(2); // [2], not [1, 2] 

This even applies to functions and variables:

function callSomething(thing = something())  return thing; > let numberOfTimesCalled = 0; function something()  numberOfTimesCalled += 1; return numberOfTimesCalled; > callSomething(); // 1 callSomething(); // 2 

Earlier parameters are available to later default parameters

Parameters defined earlier (to the left) are available to later default parameters:

function greet(name, greeting, message = `$greeting> $name>`)  return [name, greeting, message]; > greet("David", "Hi"); // ["David", "Hi", "Hi David"] greet("David", "Hi", "Happy Birthday!"); // ["David", "Hi", "Happy Birthday!"] 

This functionality can be approximated like this, which demonstrates how many edge cases are handled:

function go()  return ":P"; > function withDefaults( a, b = 5, c = b, d = go(), e = this, f = arguments, g = this.value, )  return [a, b, c, d, e, f, g]; > function withoutDefaults(a, b, c, d, e, f, g)  switch (arguments.length)  case 1: b = 5; case 2: c = b; case 3: d = go(); case 4: e = this; case 5: f = arguments; case 6: g = this.value; > return [a, b, c, d, e, f, g]; > withDefaults.call( value: "=^_^ token punctuation">>); // [undefined, 5, 5, ":P", , arguments, "=^_^ token function">withoutDefaults.call( value: "=^_^ token punctuation">>); // [undefined, 5, 5, ":P", , arguments, "=^_^ destructured_parameter_with_default_value_assignment">

Destructured parameter with default value assignment

You can use default value assignment with the destructuring assignment syntax.

A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: [x = 1, y = 2] = []. This makes it possible to pass nothing to the function and still have those values prefilled:

js

function preFilledArray([x = 1, y = 2] = [])  return x + y; > preFilledArray(); // 3 preFilledArray([]); // 3 preFilledArray([2]); // 4 preFilledArray([2, 3]); // 5 // Works the same for objects: function preFilledObject( z = 3 > = >)  return z; > preFilledObject(); // 3 preFilledObject(>); // 3 preFilledObject( z: 2 >); // 2 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

JS: functions arguments default values

In JavaScript, anything that isn't set is given the value undefined . This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:

function Foo(arg1, arg2) < if (typeof(arg1) === "undefined") < arg1 = 50; >if (typeof(arg2) === "undefined") < arg2 = "default"; >> 

You can take a bit of a short cut if you know roughly what those values will be:

However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null , undefined , false or 0 it'll be changed to 50, so be careful if you chose to use it

I prefer the == null check instead of typeof(arg1) === undefined (as the jQuery library does internally: http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint). Not only is it more concise, it also handles both null and undefined, so that client code can pass in null and get the default applied.

It is also possible to wrap the function in another function that supplies defaults. The prototypejs library has a function that supplies the argumentNames() (or if you don't want to use prototype, you can just borrow the implementation -- it's just a regex applied against the results of the function's toString() ).

So you could do something like this:

var Foo = defaults(Foo, < arg1: 50, arg2: 'default' >); function Foo(arg1, arg2) < //. >

And the implementation of defaults() would look something like this:

function defaults(fn, def) < return function() < var arg_names = fn.argumentNames(); var nArgs = args.length; for (var nArg = 0; nArg < nArgs; ++nArg) < if (arguments[nArg] == null && arg_names[nArg] in def) arguments[nArg] = def[arg_names[nArg]]; >fn.apply(this, arguments); > > 

Of course, that's untested code and the way it's written, it requires the Prototype library. But all that said, the == null approach inside the function is more natural to Javascript, is easier to debug (you don't have another function layer to step through), and I find it easier to read:

Источник

Читайте также:  Php all form fields are
Оцените статью