阿里云主机折上折
  • 微信号
Current Site:Index > Default value setting

Default value setting

Author:Chuan Chen 阅读数:54419人阅读 分类: JavaScript

Basic Usage of Default Parameters

ES6 allows setting default values for parameters when defining functions. When a function is called without providing the corresponding parameter or when the parameter value is undefined, the default value is used. This syntax is more intuitive and reliable than the ES5 approach of setting default values using the logical OR operator.

// ES5 way
function multiply(a, b) {
  b = b || 1;
  return a * b;
}

// ES6 way
function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10

Combining Default Parameters with Destructuring Assignment

Default parameters can be combined with destructuring assignment to provide default values for destructured variables. This approach is particularly useful when dealing with complex object parameters.

// Object destructuring with default values
function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) {
  console.log(size, coords, radius);
}

drawChart({
  coords: {x: 18, y: 30},
  radius: 30
});
// Output: big {x: 18, y: 30} 30

// Array destructuring with default values
function createMenu([starter = 'salad', main = 'pasta', dessert = 'cake'] = []) {
  return {starter, main, dessert};
}

console.log(createMenu(['soup']));
// Output: {starter: "soup", main: "pasta", dessert: "cake"}

Evaluation Timing of Default Parameters

Default parameters are not evaluated at function definition but at function invocation. This means that each time the function is called without providing a parameter, the default value is recalculated.

let count = 0;

function getValue() {
  return count++;
}

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

console.log(add(1)); // 1 (count=0)
console.log(add(1)); // 2 (count=1)
console.log(add(1, 1)); // 2 (count=1)

Scope of Default Parameters

Default parameters create a separate scope, which is established before the function body scope. This means variables defined in default parameters cannot be accessed within the function body.

function outer(x = 1) {
  function inner(y = 2) {
    console.log(x + y); // Can access x
  }
  inner();
}

outer(); // 3

function example(a = b, b = 2) {
  console.log(a, b);
}

example(); // Error, b is not defined

Default Parameters and the arguments Object

When using default parameters, the behavior of the arguments object differs from when default parameters are not used. In strict mode, the arguments object does not reflect parameter changes.

function foo(a, b = 2) {
  console.log(arguments.length);
  console.log(a === arguments[0]);
  console.log(b === arguments[1]);
  a = 10;
  b = 20;
  console.log(a === arguments[0]);
  console.log(b === arguments[1]);
}

foo(1);
// Output:
// 1
// true
// false
// false
// false

Practical Applications of Default Parameters

Default parameters have various practical applications in real-world development. Here are some common use cases:

  1. Handling Configuration Objects:
function createElement(tag, {className = '', id = '', textContent = ''} = {}) {
  const el = document.createElement(tag);
  el.className = className;
  el.id = id;
  el.textContent = textContent;
  return el;
}

const div = createElement('div', {className: 'box', id: 'main'});
  1. API Request Defaults:
async function fetchData(url, {method = 'GET', headers = {}, body = null} = {}) {
  const response = await fetch(url, {
    method,
    headers: new Headers(headers),
    body: body ? JSON.stringify(body) : null
  });
  return response.json();
}

fetchData('/api/users', {method: 'POST', body: {name: 'John'}});
  1. Mathematical Calculation Functions:
function calculateTotal(price, taxRate = 0.1, discount = 0) {
  return price * (1 + taxRate) * (1 - discount);
}

console.log(calculateTotal(100)); // 110
console.log(calculateTotal(100, 0.2)); // 120
console.log(calculateTotal(100, 0.2, 0.1)); // 108

Notes on Using Default Parameters

When using default parameters, keep the following points in mind:

  1. Default Parameters Do Not Skip Parameter Positions:
function f(a = 1, b = 2, c = 3) {
  console.log(a, b, c);
}

f(undefined, null, 4); // 1 null 4
  1. Default Parameters Can Be Function Calls:
function getDefaultValue() {
  return 42;
}

function fn(value = getDefaultValue()) {
  console.log(value);
}

fn(); // 42
  1. Default Parameters Can Reference Earlier Parameters:
function createUser(name, nickname = name) {
  return {name, nickname};
}

console.log(createUser('Alice')); // {name: "Alice", nickname: "Alice"}
  1. Default Parameters Cannot Access Variables Declared in the Function Body:
function example(a = b) {
  let b = 2;
  console.log(a);
}

example(); // Error, b is not defined

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.