Tips for setting default values for named parameters in JavaScript

In my TypeScript method, I am using named parameters like this

public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}

The parameters m and n will be provided from another object like

const defaults = { m : 'M', n :10, o:6 }

Now, I want to call the foo function like below and automatically add default parameters without explicitly passing them

  foo({x:'x', y: 5, z: 0})

My question is how can I apply the defaults within the body of foo, or somehow intercept the function before calling it and apply the defaults

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // How can I apply defaults here?

}

Just for simplicity, I have reduced the number of parameters

I am aware of the following solutions already, but I'm looking for something with less boilerplate code

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = defaults.m;
   }
   if (!n) {
     n = defaults.n;
   }

}

or

foo({...defaults, x:'x', y: 5, z: 0 });

Answer №1

When merging objects, it is important to use destructuring along with the merge process. Default assignment may not function as expected in this scenario. Default assignment only comes into play when dealing with undefined objects being passed as values. To properly merge default values with passed values, utilize the de-structuring technique.

Be sure to review the comments within the code for further clarification.

interface Foo {
  x: string;
  y: number;
  z: number;
  m?: string;
  n?: number;
  o?: number;
}
const defaultValue = { m: "M", n: 10, o: 6 } as Foo;
class A {
  public foo(props: Foo) {
    const { x, y, z, m, n } = { ...defaultValue, ...props };
    console.log(x, y, z, m, n);
  }
  public foo2({ x, y, z, m = defaultValue.m, n = defaultValue.n }: Foo) {
    // although functional, this method can be verbose
    console.log(x, y, z, m, n);
  }
  public foo1({ x, y, z, m, n }: Foo = defaultValue) {
    // this method will only work if foo1 is called without any arguments
    console.log(x, y, z, m, n);
  }
  public print() {
    this.foo({ x: "x", y: 5, z: 0 }); // outputs: x 5 0 M 10
    this.foo1(); // outputs: undefined undefined undefined 'M' 10
    this.foo1({ x: "x", y: 5, z: 0 }); // outputs: x 5 0 undefined undefined
    this.foo2({ x: "x", y: 5, z: 0 }); // outputs: x 5 0 M 10
  }
}
const a = new A();
a.print();

The functions foo and foo2 are effective methods for merging objects. However, when working with numerous arguments, foo2 can become cumbersome. Consider using Object.assign() or spread syntax ({...}) for a more efficient way of merging values.

Answer №2

To simplify the parameter setup, you can include default values directly in the parameter declaration like this:

public foo({x, y, z , m = 'a' , n = 10} = {x:string, y: number, z: number, m?:string, n?:number}) {
}

If you provide a value when calling the method, it will replace the default value. This approach eliminates the need for an if statement to check for the presence of a value.

You can still invoke the method using the following syntax:

foo({...default, x:'x', y: 5, z: 0 });

Answer №3

Is it possible to combine and destructure objects within a function?

type someType = {x:string, y: number, z: number, m?:string, n?:number};
const initialValues = { m : 'M', n :10, o:6 }

function foo(obj: someType) {
  const {x, y, z , m , n} = {
    ...initialValues,
    ...obj
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

JavaScript method to prevent users from entering numbers as the first two characters, with all subsequent characters being numbers only

I need a specific requirement for my form. The textbox field in my form is labeled "DEA License number", and I want it to only allow the user to enter alphabetic characters for the first two characters, followed by numbers afterward. I am looking to impl ...

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

Activate radio button exclusively for admin user

My current application includes an admin panel with functions to manage users. I use a while loop in the form creation to display 3 user types: Admin, Manager, and User, which are pulled from a database. Admin Manager User This is how my HTML Form look ...

What is the best way to display an entire string in a DataGridPro cell without truncating it with an ellipsis?

After reviewing all of the available DataGrid documentation, I am still unable to find a solution for displaying strings in multiple lines within a cell without ellipses. The current behavior is as follows: https://i.stack.imgur.com/TO8vB.png What I am a ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

Seeking help on modfiying div content with AJAX - any tips for showing navigation using hash or anchor?

Looking to create a dynamic page that updates content within a div asynchronously while also providing users with direct access to specific content within the div by using anchors (e.g. www.website.co.uk/#page1). I've successfully implemented the upd ...

Discover a non-null string within a deeply nested data structure

Within the 'task' object, the value of the 'door' property can vary each time it is accessed: var task = {}; task["123"] = [{"door":""}, {"door":""}, {"door":""}, {"door":""}]; task["456"] = [{"door":""}, {"door":"close"}, {"door":"" ...

What issue is being encountered with this JavaScript generated by PHP?

PHP on the host generates JavaScript code that results in an error stating: missing ; before statement The generated JavaScript code looks like this: try{ obj = document.getElementById('subcat'); }catch(e){} try{ obj.innerHTML = ...

Generating a Personalized XML Format Using Information from a Single MySQL Table Row by Row

If anyone can assist with this, I would greatly appreciate it: <warehouse> <frontbay> </frontbay> <bayrow> <bay> </bay> <bay> ...

Display the source code of an HTML element when clicked

Is there a way to show the source code of an element on a webpage in a text box when that specific element is clicked? I am wondering if it is feasible to retrieve the source code of an element upon clicking (utilizing the onClick property), and subseque ...

The issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

Unexpected TypeError occurred when trying to Fetch data from an Express Server hosted on Window object

Error Message : Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name Feeling stuck as I looked around, unsure of what's causing this issue. My goal is to develop a website that can eventually make a ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

Javascript problem: Trouble with event.clientX position

I found a great resource on learning javascript at this website, I'm having trouble understanding the code snippets in function XY(e, v), specifically these two lines: event.clientX + document.documentElement.scrollLeft and event.clientY + document ...

Guide on adding data from Express.js and Node.js to a database

I'm dealing with a code that involves image uploads and handling input text. I am facing an issue in inserting these values into the mysql database. The problem arises when trying to insert multiple values into the database; however, I can successfull ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...