Declaring an object in JavaScript for later use - null or {}? - javascript

Simple question, What is the best practise, should I declare JavaScript objects, that will not be initialized until some later stage, with null or {}?

I think it really depends. If you just want to declare it early because you know it is "hoisted" to the beginning of the function anyway, and will initialize a few lines down below, then just use
var foo;
which makes foo undefined. Otherwise, if you need to do anything with foo being an object before your initialization, then it will be better to use
var foo = {};

Use the object literal {}. That way, you can immediately start using it as an object, when you have to, instead of having to initialize it again as an object, later on.
So:
var myObj = {};
// loads of code
myObj.someProperty = 'foobar';
Instead of:
var myObj; // undefined, or:
var myObj = null; // null
// loads of code
var myObj = {};
myObj.someProperty = 'foobar';
Makes sense, doesn't it?

You can use {}; as it makes your code more compact, and more readable. You may try it like this:
var x = {};
By this way you can start using x as an object without initializing it again.
Also to add
var x= {} //This is an object literal
var y= new Object() //This is the object constructor
Also {} syntax is shorter, neater,readable, and allows you to instantly populate the object inline

Related

Javascript - Getting and setting properties on primitives implicitly creates object wrappers

I was reading a book called Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript, Point 4 Prefer Primitives to Object Wrappers and came across this sentence.
Getting and setting properties on primitives implicitly creates object
wrappers
Does this create an object wrapper?
"hello".someProperty = 17;
EDIT
If the above statement create an object then please explain this behaviour.
var test = "foo";
test.bar = "new prop";
test.bar //this prints undefined.
"hello".someProperty = 17;
The above statement does create an object wrapper, but it is disposed of as soon as its task is done.
var hello = 'Hello';
hello.someProperty = 17;
console.log(hello.someProperty);
This explains why trying to assign properties to a primitive doesn't work, but also doesn't throw an error. Assigning the property succeeds, but the property is set on a wrapper object which is immediately destroyed. So when you go to look up the property later, there is nothing there anymore.
Internally, this of primitive type is object.
String.prototype.thisType = function () {
return typeof this;
};
var hello = "hello";
console.log(typeof hello);
console.log(hello.thisType());
Read more Here
Yes, it creates an intermediate object, which is discarded after use. So the statement
"hello".someProperty = 17;
will internally be executed like this:
var temp = new String("hello"); // or any other variable name
temp.someProperty = 17;
So, now temp (or whatever named variable is created by JavaScript) will not be accessible because it is created and discarded immediately.
you have to create String Object by new Keyword.
var str = new String("My String");
//Here str is looks like
//String {"My String"}
str .xyz=5
str
//now String {"My String", xyz: 5}

What is the functional difference between these two different Module pattern syntaxes

I see this syntax everywhere:
var mod = (function(){
var pvtvar;
var pvtfunc = function(){};
//return an object literal
return {
pubvar : 'whatever',
pubfunc : function(){}
};
}());
I recently came across this syntax:
//first create empty object
var mod = {};
(function(mod){
var pvtvar;
var pvtfunc = function(){};
//modify the mod object argument
mod.pubvar = 'whatever';
mod.pubfunc = function(){};
}(mod)); //pass object to IIFE
I know that they both work, and I think I understand completely why, I just want to make sure I'm not missing anything...Given identical members you end up with identical objects, it's just that in the second example mod references an empty object within the global scope for a fraction of a second, while in the first example mod only ever references the complete object once its value is returned by the IIFE.
So, am I correct in thinking that the only difference is the (very small) amount of time that the second object lives as an empty object?
And, my follow up question: do you use the second syntax, and why?
You're right. In your example, the first syntax is cleaner and more readable.
You use the second syntax when you want to pass along something more than an empty object into the module and get an augmented object in return.

how to invoke a dynamically named object and its method in javascript?

I have a situation in which the name of my object will be dynamic..
i.e.
txtGrantAccess_5.GetValue();
i want to know how can I call this dynamically?
e.g.
var abcd = 'txtGrantAccess_5';
abcd.GetValue();
Please note that txtGrantAccess_5 already exists, please can you also avoid the usage of eval in your answer? I have tried understanding other questions almost similar to this but they are not the same thing...
You cannot get local variables dynamically. However, if it's a property of an object you can get it with the [] syntax.
var obj = {};
obj.foo = function() {};
obj.foo();
obj['foo'](); // same as above.
But in this case a local variable cannot be fetched dynamically at all.
var fn = function() {
var foo = '123';
// no way to get foo dynamically.
}
One exception is global variables. In the global scope, local variables are created as properties of the window object:
// global scope, outside of any function.
var foo = function() {};
window.foo();
window['foo'](); // same as above
Just keep in mind that lots of global variables are usually frowned upon, espcially if there is enough that you need to find dynamically like this. You probably just want a container object to keep these values in, like the first example I posted.
Try this snippet
var abcd = 'txtGrantAccess_5';
this[abcd].GetValue();
but be careful with value of "this". If it's in a browser maybe this will help
var abcd = 'txtGrantAccess_5';
window[abcd].GetValue();
How about:
var container = {};
var name = 'dynamicName';
container[name] = new MyObject();
container[name].getValue()

Why declare a variable as a new Object?

As a beginner, working with existing code, I've come across the following:
var foo = {};
which I believe is equivalent to:
var foo = new Object();
I was under the impression that any variable was automatically an Object, so what would be the purpose of specifically coding that, rather than just declaring an empty variable:
var foo;
I was under the impression that any variable was automatically an Object
That is a mistaken impression. If you declare a variable and do not assign it a value, it is initialised to undefined (as mention in the spec and described in detail), which is not an object (it's a primitive value):
var foo;
console.log(foo); // undefined
If you were to attempt to set a property of an undefined variable you would receive a TypeError:
var foo;
foo.example = "hello"; // TypeError: Cannot set property 'example' of undefined
However, if you assign an empty object to that variable, the above code will succeed:
var foo = {}; // Now refers to an empty object (equivalent to `new Object()`)
foo.example = "hello";
console.log(foo); // '{example:"hello"}'
I believe your understanding probably stems from the common misunderstanding that "everything in JavaScript is an object". This is not true. Many things in JavaScript are objects, but primitive values are not. For example:
var a = "hello"; // String primitive, not an object
var b = new String("hello"); // String instance, object
var c = 10; // Number primitive, not an object
var d = true; // Boolean primitive, not an object
var e; // Undefined value, not an object
var f = null; // Null value, not an object
James's answer is correct. In case he's throwing too much info too quickly (refer back to it later, if so), here's a quick summary.
You are correct in this: var foo = {} and var foo = new Object() are not only equivalent, the results are identical. Only use object literals. (ignore new Object(), new Array(), etc).
var foo; does nothing other than declare a variable. It is 'undefined' by default.
var foo = new Object() also gives the new object a prototype property which can be used to manipulate object inheritance and call standard object functions defined by javascript
see here for details on how you can manipulate the object.protype:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/prototype

creating an object and initializing an object - Difference

////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; does not create an object, it declares a variable.
Obj = {}; assigns an empty object to the variable named Obj. If Obj was not previously declared, this implicitly declares the variable in the global scope, since the var keyword is missing (don't do this).
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 = {};
Maybe I'm not totally understanding your question, but...
var Obj= {};
Is totally fine.
The first allocates the slot for the variable Obj but leaves it undefined. The second binds a newly created object to the name Obj.
You can do it in one line: var Obj = {};. Doing it in two steps has no real advantages, only risks.
var Obj;
this is not creating an object. it defines a variable;
object is first created and than initialized so this are two key processes that are both necessary to have an object.
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.
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.

Categories