How to set only a default parameter for a function?

Asked

Viewed 54 times

0

I came across a problem in javascript that in python would be simple to solve, just saying that the parameter refers to 'text'.

  • create_element (text = A média dos valores cadastrados é ${media_lista}.)

But in Javascript, it reads the text in the parameter as 'elem', because it is the first parameter requested and SIMPLY IGNORES 'text='.

I know one of the solutions is to put 'text' as the first parameter to be passed, but it is not the solution I seek.

function create_element(elem='p', text, parent='result_box') {
    let item = document.createElement(elem);
    item.text = text;
    parent.appendChild(item);
};

1 answer

1


Javascript does not have parameter passing by name. Usually when a function needs to receive multiple arguments, it is normal to send an object, with the properties representing the parameters.

With destructuring, you can achieve a similar result, although not as beautiful with the following syntax:

function create_element({elem='p', text, parent='result_box'} = {}) {
    let item = document.createElement(elem);
    item.text = text;
    parent.appendChild(item);
};

This way you can invoke the function without passing parameters:

create_element()

Or passing an object with the properties representing the parameters:

create_element({text: 'Olá Mundo'})         // apenas text
create_element({parent: 'root'})            // apenas parent
create_element({text: 'teste', elem: 'td'}) // a ordem não importa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.