Javascript functions arguments default value

JavaScript Function Parameters

A JavaScript function does not perform any checking on parameter values (arguments).

Function Parameters and Arguments

Earlier in this tutorial, you learned that functions can have parameters:

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.

Parameter Rules

JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received.

Default Parameters

If a function is called with missing arguments (less than declared), the missing values are set to undefined .

Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

Example

Default Parameter Values

ES6 allows function parameters to have default values.

Example

If y is not passed or undefined, then y = 10.

Function Rest Parameter

The rest parameter (. ) allows a function to treat an indefinite number of arguments as an array:

Example

function sum(. args) <
let sum = 0;
for (let arg of args) sum += arg;
return sum;
>

let x = sum(4, 9, 16, 25, 29, 100, 66, 77);

The Arguments Object

JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the function was called (invoked).

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Example

x = findMax(1, 123, 500, 115, 44, 88);

function findMax() let max = -Infinity;
for (let i = 0; i < arguments.length; i++) if (arguments[i] > max) max = arguments[i];
>
>
return max;
>

Читайте также:  Ajax + PHP: пример | sitear.ru

Or create a function to sum all input values:

Example

x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() let sum = 0;
for (let i = 0; i < arguments.length; i++) sum += arguments[i];
>
return sum;
>

If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object.

Arguments are Passed by Value

The parameters, in a function call, are the function’s arguments.

JavaScript arguments are passed by value: The function only gets to know the values, not the argument’s locations.

If a function changes an argument’s value, it does not change the parameter’s original value.

Changes to arguments are not visible (reflected) outside the function.

Objects are Passed by Reference

In JavaScript, object references are values.

Because of this, objects will behave like they are passed by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the function.

Источник

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 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

Источник

Оцените статью