1

I have simple one line function. Function received argument as an object and I am assigning a value to that object but it is alerting undefined. What is wrong with the code.

Fiddle

function custom(obj){
    obj.name="johnson";
}


var j= new custom(new Object());

alert(j.name)

2 Answers 2

4

That's because you're not returning the object:

function custom(obj){
    obj.name="johnson";
    return obj;
}

Fiddle

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

2 Comments

why we need to return obj. When we define function with this.name and use new operator then its work fine.
@amit Because var j= new custom(new Object());. The = there is expecting an object to be returned from the function. Otherwise, it returns nothing and j is assigned nothing.
1

You have 2 errors in your code:
1. custom function should return obj;
2. there's no reason to have new custom in var j = new custom(new Object());

This is the working version of your code:

  function custom(obj) {
    obj.name = "johnson";
    return obj;
  }

  var j = custom(new Object());

  console.log(j.name)

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.