0

I am trying this to get input as an argument with some objects,

function write(param) {

 var str = param.str;
 var elem = param.elem; 
 document.getElementById(elem).innerHTML= str;
}

and I'm passing this as an argument,

write({
   elem:"op",
   str:"Hello"
});

The thing I have to do is that I am having font tag with id 'op',

<font id="op"></font>

and when I run this I wont print Hello, as I have given Hello as an object parameter with op element for output.

1
  • 2
    Works for me. Maybe don't use font, it's deprecated. Commented Feb 28, 2017 at 10:14

2 Answers 2

1

I'm not sure where exactly your code has gone wrong. Here you can see that both the javascript and the html you produced should work together just fine.

function write(param) {

  var str = param.str;
  var elem = param.elem;
  document.getElementById(elem).innerHTML = str;
}

write({
  elem: 'op',
  str: 'Hello'
})
<font id="op"></font>

Sign up to request clarification or add additional context in comments.

1 Comment

There is a close reason for non-reproducible.
0

As far as I'm seeing it, your code works as intended.

Answer for using an options object on a function:

In ES6 default parameters can prevent values to be undefined, however it does not actually compensate for the case that you're passing an object with missing parameters.

In this case I would suggest using Object.assign():

function write(options){
   options = Object.assign({}, {
       myDefaultParam: 'Hello',
       elem: null,
       str: ''
   }, options);

   if(options.elem) document.getElementById(options.elem).innerHTML = options.str;
}

What Object.assign() does is to merge a object of default options with the provided functions, allowing you to set default parameters that you can rely on. In this case write({}) would result in options being this object:

{
   myDefaultParam: 'Hello',
   elem: null,
   str: ''    
}

If this is overkill for you, I would suggest to simply check wether the keys are defined on your param object like this:

function write(param){
   if(!param || !param.elem || !param.str) return false;
   return document.getElementById(param.elem).innerHTML = param.str;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.