1

The following code gives error.

var user;

user.load= function () {

//

}

It gives error Cannot read property 'load' of undefined

EDIT: Isn't everything an Object by default in Javascript?

11
  • 2
    The error message should be Cannot set a property ("load") on undefined Commented Aug 15, 2013 at 9:37
  • 3
    "Isn't everything an Object by default in Javascript?" No. Every value but a primitive value is an object. undefined (the default value of initialized variables) is a primitive value and doesn't have an object equivalent (like strings for example), so autoboxing doesn't take place. Commented Aug 15, 2013 at 9:38
  • 1
    @Swagg, everything is an object, but that variable doesn't hold anything. It's undefined. var user = 1; user.load = function(){} would work (you just wouldn't be able to access it later... it's complicated). Commented Aug 15, 2013 at 9:39
  • 3
    @FakeRainBrigand: Primitive values are not objects. Commented Aug 15, 2013 at 9:42
  • 1
    @FakeRainBrigand: Because the value is autoboxed. See also es5.github.io/#x8.7.1. If you have a property reference (which (1).load is), then the value is first converted to an object by calling ToObject before the reference is resolved. Commented Aug 15, 2013 at 10:03

5 Answers 5

8

The user variable needs to be an object in order for you to assign properties to it. Variables that have not been assigned a value are undefined, and you can't assign properties to undefined.

var user = {};
user.load = function () {
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, you could do var user = new Object();
2

try this:

var user = {};

user.load= function () {

//

}

Comments

0
var user = {};
user.load= function () {

//

} 

At the moment user is undefined, where it needs to be an object.

1 Comment

It is an object too. But its value is undefined. Which is why you can't tag properties to it.
0
var user = {
   load: function(){
        return 'hi';
   }
};
user.load();

or

var user = function(){
   this.load = function(){
      return 'Hi';
   }
}

1 Comment

For the second one to work, you have to create an instance of the constructor function.
0

Isn't everything an Object by default in Javascript?

No. Many things are objects, but the default value of a variable is undefined, and that is is a primitive which cannot be assigned properties.

You need to assign an object (a new empty object is fine) to the variable:

var user = {};

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.