Why can't we directly set array values in javascript? - javascript

I have an empty object myscroll defined as var myscroll = {}. Now I want to add an array property to it. I did it as follows:
var myscroll = {}
myscroll.point[0] = getScrollpos("home");
myscroll.point[1] = getScrollpos("artists");
myscroll.point[2] = getScrollpos("songs");
myscroll.point[3] = getScrollpos("beats");
myscroll.point[4] = getScrollpos("contact");
I get the error myscroll.point is not defined. Then I first defined it as myscroll.point = [];, then the code worked.
So, Why can't we directly set array values and add that property to an object in javascript? Why do we have to define it first independently?

When you are dealing with object properties, by default you can access any object property and value of that property would be undefined if it wasn't set before. So, by accessing not defined property with index (myscroll.point[0]) you are trying to access property 0 of undefined, which is primitive value in javascript and has no properties, so you are getting TypeError.
As result you can set primitive values to not defined object property, but cannot dial with not defined prop as with object.
Also wanna to point you and explain situation with a little bit similar from first view situations in code below:
var obj = []
obj[0] = 10
notDefinedObj[0] = 10 // cause ReferenceError
Array is object. In JS you can't modify/add/delete object properties without initialising object before.
That's caused because objects are stored in memory and you can access them by reference. When you attempt to add new property to it, for instance add new element to list, you are trying to attach property to variable which has no Reference, that's why you are getting ReferenceError.
Good Luck!

With myscroll.point you're trying to access a point property on the myscroll object. But there is no such property on that object. That's why you're getting a undefined is not an object error message (or something similar - depending on your browser).
If you're coming from PHP, this might be strange but actually it's much more explicit than the magic involved in the following php snippet for example:
$myscroll = [];
$myscroll['point'][0] = getScrollpos("home");
// ...
PHP automagically created sub arrays for keys that do not exist.
Update after comment
There is a significant difference between myscroll.mypoint = 5; and myscroll.point[0] = getScrollpos("home");.
In the first case your setting the point property on myscroll to 5 explicitly. But in the second case you're trying to access the [] operator (which is an array operator) on a non-existing property point. Theoretically Javascript could do the same magic as PHP and create the array automagically on the fly, but it doesn't. That's why your getting an error.
It's the same as trying to access a fictitious property myproperty on myscroll.mypoint like myscroll.mypoint.myproperty. This will not work as well, because you're trying to access myproperty on mypoint which is undefined on myscroll.

Because myscroll.point[0] = getScrollpos("home"); can be understood as Get the first element of the point array inside of myscroll and set it to... You can't access the first element of an non-existing array.

Simply check typeof of myscroll array variable and then check the typeof of myscroll.point. You have tried to assign properties of an array, outside of an array. It is empty or undefined.

You are trying to access the point property of myscroll which is not defined (because myscroll = {}).
If you will look at the console with myscroll.point, it will return you undefined. Here you were trying to put something in undefined so you got TypeError: myscroll.point is undefined.
If you define myscroll like this:
var myscroll = {
point : []
}
Then your code will work and you won't need to define myscroll.point = [].

if you have an an empty object and you want to set a new property that holds an array you should do this.
var obj = {};
obj['propertyName'] = [];
this will put a property with corresponding propertyName that holds an array that you can later populate.
if your getScrolloops() returns an array you can do this
obj['propertyName'] = getScrolloops();
Idealy in your case you can do this:
obj['propertyName'] = [getScrollpos("home"),
getScrollpos("atrist"),
getScrollpos("songs"),
getScrollpos("beats"),
getScrollpos("contact")
];
EDIT: Explanation: Why is your code not working?
As explained here:
You can define a property by assigning it a value.
What you do is trying to define a property by assigning a value to an index of that property. This will not work because you are not assigning a value to the property it's self but to index of a property that dose not exist.
Also i need to mention that you can use both property accessors to achieve that. This could be a helpful link.

Related

JavaScript Conceptual Issue with a code. Please give an explanation for the output i am getting

I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on
var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets
}
console.log(ob);
OUTPUT IS
name:'at'
That is just the syntax for accessing or assigning properties of an object dynamically in javascript.
You can think of it as though you are doing: ob.name = 'at'.
There are two ways to access object properties in JavaScript
var person = {
name: 'Jane'
}
person.name
// or
person['name']
// both return jane
in your case, that iterates through members of the array called ob2
first and only element of that array is a string name and it's given to that object as a prop, which becomes like following
ob['name'] = 'at';
// or
ob.name = 'at';
When to use brackets([]) over dot(.)
If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets
Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.
The loop is getting each index value, and for each assign/create a new property using that index value.
That approach is a dynamically way of creating property-names in an object.
ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate
Read a little the docs here -> JavaScript object basics - Learn web development | MDN

Why is `s.len` undefined (and not 4) while `s` has the value `test`? - JavaScript

I am puzzled with this one. I have the following code.
var s = "test";
s.len = 4;
var t = s.len;
The question is why the variable t has a value of undefined.
If you check the s.len after that code it is undefined.
If you check s the value is test. Not sure what is going on here. I am sure there is an explanation, but can't get my head around that and don't know how to search that.
For those who consider to vote down. This is a question we got in a course, and we are expected to prepare for the next session with this riddle.
I am not new to programming, but I fail to research how JavaScripts treats this code. It is valid code really, execute it in your Dev Tools and you will see.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
but I fail to research how JavaScripts treats this code.
That is easy: strings are primitive types in JS, which means they don't have properties by themselves.
For . operator to work with them (e.g. for .length call) javascript defines such a thing called "wrapper objects".
So when you try to access a property of a primitive object - a temporary wrapper object is created that does behave as an object, hence you can access and assign properties to it.
The problem is that the wrapper object is temporary, so after it's used to access a property the object is discarded with all its state.
That's why when you assign a .len property you cannot access it on the next line: it's lost.
So a pseudo code for what actually happens behind the scenes for your code is
var s = "test";
(new String(s)).len = 4; // here you add an attribute for a new object
// and `s` is left untouched
var t = s.len;
The question is why the variable t has a value of undefined.
Because you have defined s as a string not as an object. so s.len should be undefined!
I am not sure what are you trying to do. But if you want to get the length of s then t = s.length will simply work.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
You can find the answer from this question
run :
var s1 = "test";
console.log(typeof s1)//string
var s2 = {}
console.log(typeof s2)//object
s1.len = 4;
s2.len = 4;
console.log(s1.len);//undefine
console.log(s2.len);//4

Cannot define property '_getObservable': object is not extensible

I'm facing an issue and I'm not sure why. I'm setting a StorageFile as a property of a javascript object:
var myFile = MethodThatReturnsAFile();
var obj = { file: myFile };
The problem comes when I need to 'clone' that object. Based on a lot of SO answers on the matter I've come to use this method for cloning my objects:
for (var pty in obj)
if (obj.hasOwnProperty(pty) && target[pty] !== obj[pty])
target[pty] = obj[pty];
Where obj is my current object and target is the object I want to create, in my case var target = {}.
It works fine 'almost' everytime, expect when obj has a StorageFile in one of its properties. (I get the message from the subject)
I unserstand Storagefile is sealed and can't be extended, but why is who (WinJS?) trying to extend it? Should I change my clone method or should I not have StorageFile as property values?
JavaScript object properties may be not enumerable and hidden from 'for' or 'Object.keys'
Look defineProperty method https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

How to access this, is this an object literal or?

My javascript looks like:
[{"user":{"property1":8,"property2":"asdfasdf"}}];
I tried:
alert(user.property1);
But nothing rendered, what am I missing here?
Your javascript is an array, I assume it's assigned to a variable?
var myArray = [{"user":{"property1":8,"property2":"asdfasdf"}}];
alert(myArray[0].user.property1);
You don't seem to assign the object literal to a variable. You must do that in order to be able to reference it the way you seem to want. Note that [] indicates an array.
So you're almost there:
var myObj = [{"user":{"property1":8,"property2":"asdfasdf"}}];
alert(myObj[0].user.property1);
Your object literal creates an array, with an object that has a property named user. This user property itself is set to an object which has two properties - property1 and property2.

Question about Javascript pointer to an object property

I wanted to set a variable to point to property in an newly created object to save a "lookup" as shown in the example below. Basically, I thought the variable is a reference to the object's property. This is not the case; it looks like the variable holds the value. The first console.log is 1 (which is the value I want to assign to photoGalleryMod.slide) but when looking at photoGalleryMod.slide, it's still 0.
Is there a way to do this? Thanks.
(function() {
var instance;
PhotoGalleryModule = function PhotoGalleryModule() {
if (instance) {
return instance;
}
instance = this;
/* Properties */
this.slide = 0;
};
}());
window.photoGalleryMod = new PhotoGalleryModule();
/* Tried to set a variable so I could use test, instead of writing photoGalleryMod.slide all the time plus it saves a lookup */
var test = photoGalleryMod.slide;
test = test + 1;
console.log(test);
console.log(photoGalleryMod.slide);
Yes, you're making a copy of the value, because "slide" is set to a primitive type. Try this:
this.slide = [0];
and then
var test = photoGalleryMod.slide;
test[0] = test[0] + 1;
then change the logging:
console.log(test[0]);
console.log(photoGalleryMod.slide[0]);
In that case you'll see that you do have a reference to the same object. Unlike some other languages (C++) there's no way to say, "Please give me an alias for this variable" in JavaScript.
it looks like the variable holds the value
That's correct. Since you're using number primitives, variables contain the value rather than pointing to it. Variables only contain references when they're referring to objects.
The way to do it is to use an object property and to point to the object — which is exactly what you have with photoGalleryMod and its slide property.

Categories

Resources