what will be the output of the java script code? - javascript

var a = {};
b = {x:4};
c = {y: 2};
a[b] = 123;
a[c] = 456;
console.log(a[b]);
I was thinking, output should be 123 but not, I do not know..
what will be the output and explain with reason

The output will be 456
// It creates an empty object
var a = {};
b = {
x: 4
}; // b become a new object
c = {
y: 2
}; // c become a new object
/**Next line trying to create a key in object a which will look like {x:4}
which is invalid so it will look like {[object Object]} and its value will be 123**/
a[b] = 123;
/**Same operation with following line and its value will be 456.
In this case the previous[object Object] will be over written by
new one so both occupy the same key and hence 123 is overwritten 456**/
a[c] = 456;

Related

what's the best way to check if one object is a prototype of another?

I believe the best way would be something like:
var a = {a:1, b:2}
var b = Object.create(a);
b.a = 1
var c = Object.create(b);
c.c = 3;
var d = Object.create(c);
d.protoTree(); //returns: [c, b, a]
c.protoTree(); //returns: [b, a];
b.protoTree(); //returns: [a];
But is this possible? What's the best way assuming you only know the D object?
You can use isPrototypeOf() for this use case
Using Object.prototype.isPrototypeOf() is the way to do this
function Person() {}
function Child() {}
Child.prototype = Object.create(Person.prototype);
const child = new Child();
console.log(Person.prototype.isPrototypeOf(child));
console.log(Child.prototype.isPrototypeOf(child));
More about Object.prototype.isPrototypeOf() here
If wouldn't be good to have that as a member method, but it's easy to implement as a standalone (recursive) function:
function protoTree(obj){
if(obj === null) return []
return [obj, ...protoTree(Object.getPrototypeOf(obj))]
}
It works like this (note that it also returns Object.prototype, that a inherits from.
var a = {a:1, b:2}
var b = Object.create(a);
b.a = 1
var c = Object.create(b);
c.c = 3;
var d = Object.create(c);
//Note that `protoTree` returns the prototype objects themselves, not the variable names they are stored in
protoTree(d); //returns: [c, b, a, Object.prototype]
protoTree(c); //returns: [b, a, Object.prototype]
protoTree(b); //returns: [a, Object.prototype]
protoTree(a); //returns: [Object.prototype]

Javascript Closure code

I have a question about this fonction:
var MyObject3 = function (a, b) {
var obj = { myA : a, myB : b } ;
obj.foo = function () { return obj.myA + obj.myB ; } ;
obj.bar = function (c) { return obj.myA + c ; } ;
return obj ;
} ;
obj.foo and obj.bar are closures(what i understand). I write first:
obj3 = MyObject3(1, 2) ;
and the result is: {"myA" :1,"myB" :2}. This is OK. I try to change the value of obj3.myA : > obj3.myA = 4 ; obj3 ; and the result is : {"myA" :4,"myB" :2} . What I don't understand is: why > obj3.foo() ; returns 6? obj3.foo() gives 6 as a result ? obj3.foo() is supposed to be a closure isn'it ? its result should be;3 ?
Function MyObject3 defines a variable in its scope, which refers to a newly created object:
var obj = { myA : a, myB : b } ;
All references to obj inside of that function's scope refer to that object. Than the object is returned by the function and saved to the variable obj3. obj inside of the MyObject3 scope and obj3 in the global scope thus refer to the same object.
In javascript, primitives (e.g. numbers, booleans, strings) are passed by value, whereas objects are passed by reference. Which means that:
var val1 = 1;
var val2 = val1;
val1 = 4;
console.log(val2); // will log 1
// but:
var obj1 = {foo: 'bar'};
var obj2 = obj1;
obj1.foo = 'baz';
console.log(obj2.foo); // will log 'baz'

Javascript dynamic nested objects

I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.
I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?
here is the code:
var s = "key1.key2.key3.key4";
var a = s.split('.');
var obj = {};
var temp = obj;
for (var k =0; k < a.length; k++) {
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
why is there a var temp = obj?
what does this line do?:
temp = temp[a[k]] = {};
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Thanks for the feedback!
why is there a var temp = obj?
obj is a variable to hold the completed object. temp is a variable to hold each intermediate step of the object being built. temp starts out with the same value as obj so that the first iteration of the loop adds on to obj.
what does this line do?:
temp = temp[a[k]] = {};
Assign an empty object to a property in temp with the name a[k], where a[k] is one of the values in a.
Assign that new empty object to temp.
This could be written separately as two lines:
temp[a[k]] = {};
temp = temp[a[k]];
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Because the previous line assigns an empty object to temp.
Your question boils down to this (comments inline)
var x = {};
var y = x;
y[ "a" ] = {}; //reference to x stays so x also becomes { "a": {} }
y = y["a"]; //now y effectively becomes {} but has the same reference to y["a"] as assignment works right to left hence property `a` is becomes non-enumerable and hence shadowed.
console.log( "First Run" );
console.log( y ); //prints {}
console.log( x ); //prints { "a": {} }
y[ "a" ] = {}; //y still has a non-enumerable property `a`
y = y["a"]; //same as above y = y["a"], y again becomes {}
console.log( "Second Run" );
console.log( y ); //prints {} again
console.log( x ); //prints { "a": { "a": {} } }
Outputs
First Run
{}
{ "a": {} }
Second Run
{}
{ "a": {
"a": {} } }
Have added comments in code, hope it will be useful
var s = "key1.key2.key3.key4";
//split the string by dot(.) and create an array
var a = s.split('.');
//Creating an empty object
var obj = {};
var temp = obj;
//looping over the array
for (var k = 0; k < a.length; k++) {
//a[k] will be key1,key2,key3....
// temp is an object,square bracket is use to create a object key
// using a variable name
// variable name here is key1,key2....
//temp[a[k]] will initialize an empty object
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
It seems where you are iterating the array, in that temp object is newly creating and assigning key to obj.
temp = temp[a[k]] = {};
above line simply assigns a[index] value as a key to the new object and as a reference to obj the nested object is created.
for your question,
why is there a var temp = obj?
it copies obj object into temp variable
also, the console.log(temp) inside the loop always logs an empty object {}, why?
since you are recreating an empty object (or reassigning).

Updating object property, initially set to an undefined array element

var A = [];
var obj = {
x: A[1],
y: 'hello'
};
A[1] = 1;
console.log(JSON.stringify(obj)); // {"y":"hello"}
By the time I'm using obj in console.log(), A[1] has already been defined.
How can I get the "latest" obj, with all its properties updated ? Such that we get {"x":1,"y":"hello"} when we do console.log() ?
You are getting the latest object. If you want the x property to update as its assigned value changes throughout the runtime of the code you need to use an object, since it will just store a reference to it and as the place in memory changes you will see those changes everywhere you assigned it. Arrays are considered objects so you could just assign A to x.
var A = [];
var obj = {
x: A,
y: 'hello'
};
A[1] = 1;
alert(JSON.stringify(obj));
Another example using an object as value:
var A = [];
var B = {};
A[1] = B;
var obj = {
x: A[1],
y: 'hello'
};
B.z = 1;
alert(JSON.stringify(obj));
A[1] = 1; is actually defined when obj was already constructed. So obj.x is always undefined.
var A = [];
A[1] = 1;
var obj = {
x: A[1],
y: 'hello'
};
document.body.textContent = JSON.stringify(obj);
Assuming you want the value of obj.x as a primitive :
It's not possible to assign the reference of a var to obj.x.You can make obj.x as a function that'll get the latest value of that variable
var variable= 2
var obj = {
x: function() {
return variable;
},
y: 'hello'
};
variable = 5;
console.log(obj.x()); //prints 5
Javascript objects are not reinitialised by reference.
You need to do obj.x = 1 to update the object.

javascript array index problem!

var a = new array();
a[1] = 'A';
b[10] = 'B';
console.log(a);
/[undefined, "A", undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, "B"]/
I want to remove undefined element
but what is the process??
First of all, jQuery has nothing to do with this.
Second, arrays are "autofilled". If you define index 10, all indexes 0 - 9 will be occupied automatically, that's just the way Javascript arrays work.
What you're looking for is probably an object:
var a = {};
a[1] = 'A';
a[10] = 'B';
or
var a = {
1 : 'A',
10 : 'B'
};
In this case you can use an Object instead of an Array like so:
var a = {}; // or var a = new Object();
a[1] = 'A';
a[10] = 'B';
a['foo'] = 'bar';
a.bar = 'foo'; // same as a['bar'] = 'foo';
console.log(a);
Arrays always start at 0 and then go up to the last filled index.
You could use an object to solve your problem:
var a = {};
a[1] = 'A';
a[10] = 'B';
well, to remove those undefined parts do
a[0] = 'A';
a[1] = 'B';
In your snippet, you fill the element with index 10 which forces the ECMAscript to create an array with 10 fields. There are no definitions for all that fields between 1 and 10, which means those are correctly undefined.
To remove that fields you either have to set a proper value or map the non-undefined values into a new array which would just be unnecesarry if you create a correct array in the first place.
Create an true object instead of an array (which actually also is an object) to have your desired behavior.
var a = {};
a[1] = 'A';
a[2] = 'B';
console.log(a);

Categories

Resources