creating an object and initializing an object - Difference - javascript

////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.

Related

Why is my constant not pointing to new value

If i am not wrong, the pointer that the variable name is using cannot change in memory, but the thing the variable points to might change.
let name = "google";
const foo = name;
console.log(foo); //prints google
name = "yahoo";
console.log(foo); //prints google again instead of yahoo
Should it not print yahoo, as the variable name's value has been changed.. Can anyone explain me this.
Another example, where its changes...
const foo = [];
foo.push("test");
console.log(foo); // outputs ["test"]
I am getting confused here, can anyone explain me this.
Your first example uses an immutable string and the second uses a mutable object.
JS strings are immutable after being declared or created, so foo is not a reference to name's value, it points to the string. You're not changing the strings, you're pointing to a different one.
The array variable points to the object and continues pointing to the same object after it's been mutated. You're still pointing to the same object, however, since const is not deep.
This also highlights a common misunderstanding with JS' const, which functions more like Java's final than C++'s const. You are declaring a variable as const, not an instance of the object, so it only prevents you from reassigning to the variable, it does not prevent you from mutating the underlying object.
From MDN:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
This means that you can change the value assigned to a const, say by changing array or object, but cannot assign a new value to the const variable. E.g.:
Valid:
const a = [];
a.push(5);
console.log(a);
const b = {};
b['foo'] = 'bar';
console.log(b);
Invalid: This will throw error
const a = [];
a = [5];
console.log(a);
const b = {};
b = {'foo': 'bar'};
console.log(b);

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

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

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 can't I use var when declaring sub name spaces?

Why does the following work
var NameSpace = NameSpace || {};
NameSpace.Foo = 2;
But this does not?
var NameSpace = NameSpace || {};
var NameSpace.Foo = 2;
Any insight into the inner workings of the variable deceleration in regards to namespaces would be appreciated.
JavaScript does not have namespaces. Your first line of code is declaring a variable whose name is Namespace, and whose value is an object:
var NameSpace = NameSpace || {};
Then you create a property Foo on the object, and assign a value to it:
NameSpace.Foo = 2;
Bottom line: variables and object properties are different things (among other differences, variables have scope, while properties don't). The var statement is only for declaring variables.
var foo = foo;
works because ECMAscript will decouple this line in away like
var foo;
foo = foo;
under the hood. This concept is commonly called hoisting.
Your second snippet can't work, since we are assigning an object property. The var keyword always implies, that we want to create a variable, a symbol so to speak, within the current Execution Context.
What you could do of course, is
var Foo = NameSpace.Foo = 2;
This would
create the variable Foo in the current context
assign the object property Foo on the NameSpace object
assign both the value of 2
var is reserved for declaring new variables, not modifying existing ones.
Additionally . is an invalid character for a variable name.

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

Categories