Is it possible to assign default values to optional properties in JavaScript?

Here is an example to consider:

interface Parameters {
    label: string;
    quantity?: number;
}

const defaultSettings = {
    label: 'Example',
    quantity: 10,
};

function setup({ label, quantity }: Parameters = { ...defaultSettings }) {
    console.log('setup, label:', label);
    console.log('setup, quantity:', quantity);
    return;
}

setup();

setup({ label: "Test"});

Playground Link: Provided

The output is as follows:

[LOG]: "setup, label:",  "Example"
[LOG]: "setup, quantity:",  10
[LOG]: "setup, label:",  "Test"
[LOG]: "setup, quantity:",  undefined

Is there a way to specify a default value for the quantity attribute if not provided?

Answer №1

To simplify the code by removing the outer Options and defaultOptions identifiers, you can consolidate all the logic within the argument list:

function revisedApproach({
    name = 'Alice',
    age = 21,
    fn = () => Promise.resolve()
}: {
    name?: string,
    age?: number,
    fn?: () => Promise<any>
} = {}) {
    console.log('revisedApproach, name:', name);
    console.log('revisedApproach, age:', age);
    console.log('revisedApproach, fn:', fn);
}

Answer №2

If, for any reason, you are unable to utilize @CertainPerformance's solution, an alternative approach is to destructure after merging with defaults:

function newApproach(options?: Partial<Options>) {
    const {name, age, fn}: Options = {...defaultOptions, ...options};
    console.log('newApproach, name:', name);
    console.log('newApproach, age:', age);
    console.log('newApproach, fn:', fn);
}

Playground link

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

MUI: The value you have chosen for the select component is outside the acceptable range - `[object Object]`

I'm currently in the process of developing a custom Select component that offers both single and multi-selection features. Below is how I initialize the components: const vendorList = [ { label: "John", value: "668", } ...

Creating methods that are shared, privileged, and publicly accessible: A guide

Currently, some methods in one of my classes are public but can access private variables due to being privileged. This is because they are generated in the class constructor, allowing their closure to have access to the object closure. However, I am conce ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

Contrasting VSCode Live Server and Node Live Server

Recently delving into the world of JS, I've come across the need to set up a live server using npm. One popular extension in VSCode known as Live Server by Ritwick Dey caught my attention. I'm curious about the distinctions between utilizing this ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Toggle the visibility of items based on the user's login status

Below is the code snippet for when the user is logged out: <div class="fusion-secondary-main-menu"> <div class="fusion-row"> <?php avada_main_menu(); ?> <?php avada_mobile_menu_search( ...

MUI Autocomplete fails to refresh the chosen value when its onChange function modifies the state

My React version 18.2.0 code structure is structured as follows: const [searchParams, setSearchParams] = useState({ shoes:false, hoodies:false }); const handleShoesDropDownChange = (e, v, setSearchParams) => { console.log(' ...

Mastering the art of redirection in Node.js

Encountering an issue with redirecting between directories - having trouble directing to another file in a different directory. Here is my directory structure: -views -add_user.jade -routes -index.js Attempting to redirect to add_user.jade from inde ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Obtaining a value from an input field in Vue.js

Just starting out with Vue and could use a hand extracting a value from an input field: Here's what I have in my form: <input type="hidden" id="groupId" value="1"> If I were using jQuery, I would do the following: ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...

Identifying the moment when attention shifts away from an element

Is it possible to detect when focus occurs outside an element without relying on global selectors like $(document), $(body), or $(window) for performance reasons? If achieving this without global selectors is not feasible, provide a provable reason expla ...

Reorganize array of objects in JavaScript

So I am working with an array of objects structured like this: const data= [ { id: '6397f6f46b18bc89cb37053c', cost_center: null, plant: null, material: null }, { id: '6397f7166b18bc89cb372ff7', cost_center: &apo ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

"Return to the top" feature that seamlessly integrates with jQuery's pop-up functionality

Currently, I am facing an issue with a jQuery selectmenu list that opens as a popup due to its length. My goal is to add a "back to top" button at the end of the list. While researching online, I came across this tutorial which seems promising, but unfor ...

The function you are trying to access does not exist in this.props

Trying to pass this.state.user to props using the isAuthed function is resulting in an error: this.props.isAuthed is not a function . The main objective is to send this.state.user as props to App.js in order to show or hide the Sign out button based on ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

What is the most efficient way to clear the input field in Angularjs when the backspace or delete keys are pressed?

Is there a way to reset an input field with AngularJS when the backspace or delete keys are pressed? I've implemented this fantastic directive, and it's been working great, except for when the user uses the backspace or delete key to clear the f ...