0

I have this function code that I am using to create a code snippet in javascript. I want to know if I can make it look better since I think this code I did is not looking professionally well.

I would like to know if there is any better way of passing multiple parameters to a function in javascript sending the arguments as an object literal?

Many thanks.

let headings = document.getElementById('headlines');

function create(listLi, txt, p) {
  let li = document.createElement(listLi)
  li.innerHTML = txt;
  p.appendChild(li);
  return li;
}

let ul = create('ul', null, document.body);

1
  • A fixed number of three arguments is going to be more efficient to pass as three separate arguments like you are already doing. Passing as an object is appropriate for many more arguments/options or a number of optional arguments/options.
    – jfriend00
    Apr 22, 2020 at 23:27

1 Answer 1

2

You can use destructuring.

function create({listLi, txt, p}) {
  let li = document.createElement(listLi)
  li.innerHTML = txt;
  p.appendChild(li);
  return li;
}

let ul = create({
  listLi: 'ul',
  txt: null,
  p: document.body
});

4
  • when I replace with this destructuring I get an error -- lmanha_jv_t1.js:15 Uncaught TypeError: Cannot read property 'appendChild' of undefined Apr 22, 2020 at 23:20
  • I would like to share the full code with you. link - jsfiddle.net/lmanhaes/yqoxcLfb/32 Apr 22, 2020 at 23:21
  • Don't worry my friend. I actually fixed the issue making the create function a constant variable for the function. Thank you for your help. Apr 23, 2020 at 0:01
  • @barmar this an elegant solution - many thanks for sharing it. Jul 25, 2020 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.