////Creating Object
var Obj;
// init Object
Obj= {};
- What's the difference between these two?
- Is it possible to make it into a single line?
- Any Advantages of using like this?
the first declares a variable in the current scope, it does not assign any value to it,thus it is not creating any object, while the second one creates an empty object literal to which you can refer through the global Obj variable.
There are 2 main differences : scoping variables and initializing vs declaring.
ex :
var Obj;
alert(typeof Obj);//='undefined'
//scoping :
function foo(){
obj1 = {};
var obj2 = {};
}
alert(typeof obj1);//='object'
alert(typeof obj2);//='undefined'
// obj2 is visible only in the foo function scope,while
// obj1 is being attached to the global scope, the window object
// you can access obj1 as window.obj1 too
var Obj; is not creating an object, it is declaring the variable Obj.
Obj = {}; is initializing the variable Obj with an empty object.
Of course you can combine it and do it in one go:
var Obj = {};
You basically just have to separate declaration and initialization, if you want to initialize the variable with different values, based on some condition or if the variable should be declared in another scope. For example:
var Obj;
if(something) {
Obj = 'me';
else {
Obj = 'you';
}
var Obj;
only declares the Obj variable, whereas
var Obj = {};
declares and initializes the Obj variable as an empty object.
Make sure you understand the use of the var keyword here as well. It can be used in declaring and/or initializing variables. The difference between
Obj = {};
and
var Obj = {};
is that the var-less code initializes Obj in the global namespace (often considered a bad practice).
tl;dr: In most cases, it is best to initialize and declare at the same time in the local scope, using the var keyword:
var Obj = {};
This line does not actually create an object. Rather it creates a variable (or a place that could hold an object if you put one in there).
var Obj;
This line, does create an object, and places it into the variable.
Obj = {};
This line "initializes" the object by creating a property and setting it to something.
Obj.Something = null;
Note that by saying
var Obj;
you are not creating the object, merely defining a (in scope of a function local) variable initially set to null
Other than that there's no difference whether you merge it into one statement or not.
null but undefined.If that's all the code you've got, there is absolutely NO difference between this:
var Obj;
Obj = {};
and this:
var Obj = {};
IF that's all the code you've got, with nothing in between modifying the Obj variable. In fact, I'd argue that the second way of doing it would be faster than the two lines above.
Obj is set to undefined for ONE LINE where nothing happens after it except it being set to {}.