Javascript defaults for function parameters

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

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.

Источник

JavaScript Default Parameters

Summary: in this tutorial, you will learn how to handle JavaScript default parameters in ES6.

TL;DR

function say(message='Hi') < console.log(message); > say(); // 'Hi' say('Hello') // 'Hello'Code language: JavaScript (javascript)

The default value of the message paramater in the say() function is ‘Hi’ .

In JavaScript, default function parameters allow you to initialize named parameters with default values if no values or undefined are passed into the function.

Arguments vs. Parameters

Sometimes, you can use the terms argument and parameter interchangeably. However, by definition, parameters are what you specify in the function declaration whereas the arguments are what you pass into the function.

Consider the following add() function:

function add(x, y) < return x + y; > add(100,200);Code language: JavaScript (javascript)

In this example, the x and y are the parameters of the add() function, and the values passed to the add() function 100 and 200 are the arguments.

Setting JavaScript default parameters for a function

In JavaScript, a parameter has a default value of undefined. It means that if you don’t pass the arguments into the function, its parameters will have the default values of undefined .

See the following example:

function say(message) < console.log(message); > say(); // undefinedCode language: JavaScript (javascript)

The say() function takes the message parameter. Because we didn’t pass any argument into the say() function, the value of the message parameter is undefined .

Suppose that you want to give the message parameter a default value 10.

A typical way for achieving this is to test parameter value and assign a default value if it is undefined using a ternary operator:

function say(message) < message = typeof message !== 'undefined' ? message : 'Hi'; console.log(message); > say(); // 'Hi'Code language: JavaScript (javascript)

In this example, we didn’t pass any value into the say() function. Therefore, the default value of the message argument is undefined . Inside the function, we reassigned the message variable the Hi string.

ES6 provides you with an easier way to set the default values for the function parameters like this:

function fn(param1=default1, param2=default2. ) Code language: JavaScript (javascript)

In the syntax above, you use the assignment operator ( = ) and the default value after the parameter name to set a default value for that parameter. For example:

function say(message='Hi') < console.log(message); > say(); // 'Hi' say(undefined); // 'Hi' say('Hello'); // 'Hello'Code language: JavaScript (javascript)
  • In the first function call, we didn’t pass any argument into the say() function, therefore message parameter took the default value ‘Hi’ .
  • In the second function call, we passed the undefined into the say() function, hence the message parameter also took the default value ‘Hi’ .
  • In the third function call, we passed the ‘Hello’ string into the say() function, therefore message parameter took the string ‘Hello’ as the default value.

More JavaScript default parameter examples

Let’s look at some more examples to learn some available options for setting default values of the function parameters.

1) Passing undefined arguments

The following createDiv() function creates a new element in the document with a specific height, width, and border-style:

function createDiv(height = '100px', width = '100px', border = 'solid 1px red') < let div = document.createElement('div'); div.style.height = height; div.style.width = width; div.style.border = border; document.body.appendChild(div); return div; >Code language: JavaScript (javascript)

The following doesn’t pass any arguments to the function so the createDiv() function uses the default values for the parameters.

Suppose you want to use the default values for the height and width parameters and specific border style. In this case, you need to pass undefined values to the first two parameters as follows:

createDiv(undefined,undefined,'solid 5px blue');Code language: JavaScript (javascript)

2) Evaluating default parameters

JavaScript engine evaluates the default arguments at the time you call the function. See the following example:

function put(toy, toyBox = []) < toyBox.push(toy); return toyBox; > console.log(put('Toy Car')); // -> ['Toy Car'] console.log(put('Teddy Bear')); // -> ['Teddy Bear'], not ['Toy Car','Teddy Bear']Code language: JavaScript (javascript)

The parameter can take a default value which is a result of a function.

Consider the following example:

function date(d = today()) < console.log(d); > function today( ) < return (new Date()).toLocaleDateString("en-US"); > date();Code language: JavaScript (javascript)

The date() function takes one parameter whose default value is the returned value of the today() function. The today() function returns today’s date in a specified string format.

When we declared the date() function, the today() function has not yet evaluated until we called the date() function.

We can use this feature to make arguments mandatory. If the caller doesn’t pass any argument, we throw an error as follows:

function requiredArg( ) < throw new Error('The argument is required'); > function add(x = requiredArg(), y = requiredArg( ))< return x + y; > add(10); // error add(10,20); // OKCode language: JavaScript (javascript)

3) Using other parameters in default values

You can assign a parameter a default value that references other default parameters as shown in the following example:

function add(x = 1, y = x, z = x + y) < return x + y + z; > console.log(add()); // 4Code language: JavaScript (javascript)
  • The default value of the y is set to x parameter.
  • The default value of the z is the sum of x and y
  • The add() function returns the sum of x , y , and z .

The parameter list seems to have its own scope. If you reference the parameter that has not been initialized yet, you will get an error. For example:

function subtract( x = y, y = 1 ) < return x - y; > subtract(10);Code language: JavaScript (javascript)
Uncaught ReferenceError: Cannot access 'y' before initializationCode language: JavaScript (javascript)

Using functions

You can use a return value of a function as a default value for a parameter. For example:

let taxRate = () => 0.1; let getPrice = function( price, tax = price * taxRate() ) < return price + tax; > let fullPrice = getPrice(100); console.log(fullPrice); // 110Code language: JavaScript (javascript)

In the getPrice() function, we called the taxRate() function to get the tax rate and use this tax rate to calculate the tax amount from the price.

The arguments object

The value of the arguments object inside the function is the number of actual arguments that you pass to the function. For example:

function add(x, y = 1, z = 2) < console.log( arguments.length ); return x + y + z; > add(10); // 1 add(10, 20); // 2 add(10, 20, 30); // 3Code language: JavaScript (javascript)

Now, you should understand the JavaScript default function parameters and how to use them effectively.

Источник

Читайте также:  Input в python код
Оцените статью