Javascript empty object - javascript

This is an example of code, from a book called JavaScript: The Definitive Guide, 6th Edition, that I do not understand.
He is talking about Objects.
var book ={
topic: "javascript",
fat: true
};
book.topic => "javascript"
book.["fat"] => True
book.author="flanagan"; // creates new property
book.contents= {}; // empty object*
So what I don't understand is the last part. Is he adding in a new property called "contents" that is empty? Because he is calling it an object and it's confusing me.

Yes {} is an empty object in javascript which is being assigned to the contents property of the book object.
Here you can see that we can use functions defined globaly on object such as toString()

Take a look at the way the book variable is defined. It is an Object declaration.
In the last line, we add a property named contents and assign it an object declared exactly the same way as book except that this one has no property and therefore is an empty object : {}

The curly bracket { } notation denotes an object literal.
The fact that there is nothing between them means that a new object reference pointing to a blank object (inheriting from the base object) is stored in the book.contents property.

{} create an empty object. Means now this object can have new property same as defined by book.author="flanagan";
// Both are same
book.contents = new Object();
book.contents = { } ;

In JavaScript you can create an object with {} notation, called object literal and you can add what ever you want to this object in future by dot even a function , in your example in first step:
var book ={topic: "javascript",fat: true};
book object is created with two property topic and fat and then this object is extended with author as String and contents as an inner object, as I said you can use it for creation empty objects (var t={} //example);
and if you use
typeof book.contents // returns "object"

It's creating a new property of the original book object, and setting the value of that property to a new empty object.

He's adding a new property called contents of the object book which itself is an empty object.
Here is a structure of what it would look like when he's made his changes to help you visualise it.
var book = {
topic: "javascript",
fat: true,
author : "flanagan",
contents : {}
};

<script type="text/javascript">
var book ={
topic: "javascript",
fat: true
};
book.topic = "javascript";
book.fat = true;
book.author = "flanagan"; // creates new property
book.contents = {}; // empty object*
//The curly bracket { } denotes here an object.
//will add a property contents and will contain an empty object
alert(book.contents); //it will display [object Object]
book.contents.name = 'Success Stories';
//adding propertis to the object contents
alert(book.contents.name);
/*
you can consider it as object inside object
objectOuter {
property1: value1
property2: value2
property3: objectInner {
property1: value1
property2: value2
}
}
*/
</script>

Related

Object keys - Javascript: why doesn't work to create object inside object?

I don't know if I am mind-collapsed or just need to work harder with objects, but I don't get why this doesn't work:
const obj = {};
const obj['pagination']['searchword'] = searchWord;
It says:
Cannot set property 'searchWord' of undefined
It looks like I can't create that kink of object:
console.log(obj)
{
pagination:{searchWord:valueOfSearchWordVariable}
}
I tried to with const obj.pagination['searchword'] = searchWord;
If you want to create an object inside an object, you have to define the object explicitly somewhere. If you try to access a property of an object as if it was a nested object, one won't automatically be created.
For your case, it would be easier to define the object all at once, in one statement, not two:
const obj = {
pagination: {
searchword: searchWord
}
};
If you have to assign after object initialization, then you'd do:
obj.pagination = {
searchword: searchWord
};
If you change the searchWord variable name so it matches the lower-case property name, you can use shorthand notation:
obj.pagination = {
searchword
};
You have to define obj['pagination'] first. Now you are assigning to an undefined.
obj is an empty object. But what is obj['pagination']? it is not set yet. And while obj['pagination'] is not set you are trying to assign a property to it.
you also can assign an empty object.
obj['pagination'] = {};
and then you can do this.
obj['pagination']['searchword'] = searchWord;
Another way to do this
Object.defineProperty(obj, 'pagination', {
searchword: searchWord
});

how to turn a string into a variable

Im trying to use a command for a chat program and i want to edit a variable with a command like !editvar variablehere value
so if it variablehere = '123' i want to turn '123' into just 123 or something like 'hello' into hello, in simple words im trying to make a string from a chat message into a variable name
ive tried parsing and string.raw and none worked
if(message.startsWith('keyeditvar')) {
console.log(message)
var bananasplit = message.split(' ');
var bananasplitted = json.parse(bananasplit)
console.log(bananasplitted[0].keyeditvar)
var variable = bananasplit[1]
console.log(variable)
var value = bananasplit[2]
console.log(value)
var variable2 = String.raw(variable)
console.log(variable2)
var value2 = String.raw(value)
console.log(value2)
}
i expected it to work ig
im trying to turn a string into a variable name
In Javascript, you don't usually dynamically define new variables with custom names in the current scope. While you can do it at the global scope, you cannot easily do it in the function or block scope without using tools that are generally not recommended (like eval()).
Instead, you use an object and you create properties on that object. You can use either a regular object and regular properties or you can use a Map object with some additional features.
For a regular object, you can do thing like this:
// define base object
let base = {};
// define two variables that contain variable name and value
let someName = "greeting";
let someValue = "hello";
// store those as a property on our base object
base[someName] = someValue;
console.log(base); // {greeting: "hello"}
Then, you can change the value:
someValue = "goodbye";
base[someName] = someValue;
console.log(base); // {greeting: "goodbye"}
Or, you can add another one:
let someOtherName = "salutation";
let someOtherValue = "Dear Mr. Green";
base[someOtherName] = someOtherValue;
console.log(base); // {greeting: "goodbye", salutation: "Dear Mr. Green"}
console.log(base.greeting) // "goodbye"
console.log(base[someName]); // "goodbye"
console.log(base.salutation) // "Dear Mr. Green"
console.log(Object.keys(base)) // ["greeting", "salutation"]
You can think of the Javascript object as a set of key/value pairs. The "key" is the property name and the value is the value. You can get an array of the keys with:
Object.keys(obj)
You set a key/value pair with:
obj[key] = value;
You get the value for a key with:
console.log(obj[key]);
You remove a key/value pair with:
delete obj[key]
With a plain Javascript object like this, the keys must all be strings (or easily converted to a string).
If you have non-string keys, you can use a Map object as it will take any object or primitive value as a key, but it uses get() and set() methods to set and get key/values rather than the assignment scheme of a plain object.
Please, next time put a clean code...
To convert a string to a number. You can use the function : Number(object)
So for example :
Number('123')
will return 123.
If the object value is not a correct number, it will return NaN.
So for example :
Number('hello')
will return NaN.

Assign new property to empty object which has frozen prototype

Why can't I assign new properties to non-frozen object, which has frozen prototype:
Working without Object.freeze:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
Above code works as expected, but I want to make sure that defaults won't be accidentally changed. So I want to freeze my defaults object:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//!!!!!!!!!!!!
Object.freeze(defaults);
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
//TypeError: Cannot assign to read only property 'sections' of #<Object>
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
What I don't get is why can't I assign to specificObject if its prototype is frozen?
//EDIT:
Notice that specific object is not frozen:
'use strict'
//This object will be prototype of next objects
var protoObj = {a: 1, o: {}};
Object.freeze(protoObj);
console.log(Object.isFrozen(protoObj)); //true
var n = Object.create(protoObj);
console.log(Object.isFrozen(n)); //false
What I don't get is why can't I assign to specificObject if its prototype is frozen?
Because property attributes are inherited. Yes, it's odd.
If you freeze an object, it will set the [[writable]] attribute of all data properties to false.
If you assign to an object property, but that property does not exist on the object, it will go and look it up on the prototype - it might be defined as setter there. When this lookup will return and say that there is a property of that name but it is non-writable, your assignment will fail (and throw in strict mode).
What can you do against this?
Use Object.defineProperty instead of assignment, it doesn't check the prototype
or similarly, use the second parameter of Object.create to create the own property
freeze the defaults only after you've assigned to specificObject.
my understanding is that specificObject.sections is pointing to its' prototype which is defaults and it is frozen object. You define a new object {} but you try to assign it to defaults.sections. SpecificObject.sections is pointing exactly there.
If you create new ownProperty on specificObject it will work:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//!!!!!!!!!!!!
Object.freeze(defaults);
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
// this will create new property
Object.defineProperty(specificObject, 'sections',{
enumerable: true,
writable: true,
configurable: true,
value: {}
});
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
explanation:
if you try to access obj.prop = val then javascript looks into obj's own properties, if not found then it looks into obj's prototype own properties. if found there then it /tries to assign val to/ lookup that property. if not found there then it tries to look into obj's prototype's prototype and so on. If prop is not found in the prototype tree then it creates new own property on obj and assigns val.
Therefore if prop is find on prototype and it is frozen you will get type error. Hope it brings some light.:)
EDIT:
as correctly pointed out by #KubaWyrostek specificObj.sections = {} will create new own property of specific Object, does not assign new value to the prototype's property, but it probably does the lookup for the property to check the writability, in that case it will run into frozen object. I didn't know about this before.

create object within object Javascript

My Code :
for( var i in zones) {
var latlons1 = new google.maps.LatLng(zones[i].b.cen_x, zones[i].b.cen_y);
var latlons2 = new google.maps.LatLng(zones[i].b.max_x, zones[i].b.max_y);
var latlons3 = new google.maps.LatLng(zones[i].b.min_x, zones[i].b.min_y);
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} } //here object creation
console.log(obj1);
}
what i am doing wrong? consol log error shows at object create.
When creating an object literal in JavaScript the key and value are separated by a colon (:). Also note that if you want to use dynamic keys then you'll need to use the square bracket notation for setting and accessing those properties. So this:
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} }
should become:
obj1 = {};
obj1[zones[i].n] = {
1: latlons1,
2: latlons2,
3: latlons3
};
If you're confused as to why you have to do it this way it's because the keys aren't evaluated. While you meant that the key should be the value that's referenced by zones[i].n, JavaScript interprets it as the key should be the string literal "zones[i].n", which obviously isn't what you want.
To use an object within an object,
//An object within an object
var NestedObject=new Object();
NestedObject.one={
sad:{
d:"Add"
}
}
I solved this using experimental coding within Codecademy.com;
Thanks for letting me share my answer!

How to access the properties of a JavaScript object?

while review a javascript coding, i saw that
var detailInf = {
"hTitle":"Results",
"hMark":"98"
};
What's the concept behind this js coding. While give alert for the variable its shows as "[object Object]". So this is an object, then how can we access the variable and reveal the data from this object.
Try doing this:
alert(detailInf['hTitle']);
alert(detailInf.hTitle);
Both will alert "Results" - this is a Javascript object that can be used as a dictionary of sorts.
Required reading: Objects as associative arrays
As a footnote, you should really get Firebug when messing around with Javascript. You could then just console.log(detailInf); and you would get a nicely mapped out display of the object in the console.
That form of a JavaScript object is called an object literal, just like there are array literals. For example, the following two array declarations are identical:
var a = [1, 2, 3]; // array literal
var b = new Array(1, 2, 3); // using the Array constructor
Just as above, an object may be declared in multiple ways. One of them is object literal in which you declare the properties along with the object:
var o = {property: "value"}; // object literal
Is equivalent to:
var o = new Object; // using the Object constructor
o.property = "value";
Objects may also be created from constructor functions. Like so:
var Foo = function() {
this.property = "value";
};
var o = new Foo;
Adding methods
As I said in a comment a few moments ago, this form of declaring a JavaScript object is not a JSON format. JSON is a data format and does not allow functions as values. That means the following is a valid JavaScript object literal, but not a valid JSON format:
var user = {
age : 16,
// this is a method
isAdult : function() {
// the object is referenced by the special variable: this
return this.age >= 18;
}
};
Also, the name of the properties need not be enclosed inside quotes. This is however required in JSON. In JavaScript we enclose them in brackets where the property name is a reserved word, like class, while and others. So the following are also equivalent:
var o = {
property : "value",
};
var o = {
"property" : "value",
};
Further more, the keys may also be numbers:
var a = {
0 : "foo",
1 : "bar",
2 : "abz"
};
alert(a[1]); // bar
Array-like objects
Now, if the above object would have also a length property, it will be an array like object:
var arrayLike = {
0 : "foo",
1 : "bar",
2 : "baz",
length : 3
};
Array-like means it can be easily iterated with normal iteration constructs (for, while). However, you cannot apply array methods on it. Like array.slice(). But this is another topic.
Square Bracket Notation
As Paolo Bergantino already said, you may access an object's properties using both the dot notation, as well as the square bracket notation. For example:
var o = {
property : "value"
};
o.property;
o["property"];
When would you want to use one over the other? People use square bracket notation when the property names is dynamically determined, like so:
var getProperty = function(object, property) {
return object[property];
};
Or when the property name is a JavaScript reserved word, for example while.
object["while"];
object.while; // error
That's an object in JSON format. That's a javascript object literal. Basically, the bits to the left of the :'s are the property names, and the bits to the right are the property values. So, what you have there is a variable called detailInf, that has two properties, hTitle and hMark. hTitle's value is Results, hMark's value is 98.
var detailInf = { "hTitle":"Results", "hMark":"98"};
alert(detailInf.hTitle); //should alert "Results"
alert(detailInf.hMark); //should alert "98
Edit Paolo's answer is better :-)
As Dan F says, that is an object in JSON format. To loop through all the properties of an object you can do:
for (var i in foo) {
alert('foo[' + i + ']: ' + foo[i]);
}

Categories

Resources