JavaScript array and object in single variable? [duplicate] - javascript

This question already has answers here:
Add a property to a JavaScript array
(5 answers)
Closed 7 years ago.
I recently came across some code which I am a little confused about. Below is similar code, have a look:
var x = [];
console.log(x); // prints [] (no surprise)
x[0] = "abc";
console.log(x); // prints ["abc"] (no surprise)
x["test"] = "testing"
console.log(x); // prints ["abc"]
console.log(x.test); // prints "testing"
so in this case.. the same variable, x, is both array and an object. How is this possible? If it acts as both, then console.log(x) should print something like ["abc",test:"testing"] but that syntax is wrong.
So whats happening in this case?

All Arrays are Objects, (not only them, everything in JavaScript is an Object (except the primitives though))
console.log([] instanceof Object);
// true
just that they are special kind of objects which process integer keys differently.
So, you can expect them to act like normal JavaScript Objects. You can add arbitrary properties to them.
About the console.log result,
[ 'abc', test: 'testing' ]
is just a representation given by the implementation. If the representation has a key : value format, then it is a normal property associated with that array. That's all.

Related

Why can we use the .length property in string types? [duplicate]

This question already has answers here:
How does primitive types in Javascript have methods and Properties? [duplicate]
(2 answers)
Closed last year.
Hello I'm new to JS and object-oriented programming in general.
I have two questions considering this
let arr = [1,2,3]
let a = 'hi'
When I run typeof(), arr is 'object' and a is 'string' right?
So my question is ,
When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?
Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.
When you declare [1,2,...] you are declaring an object of class Array, which, in it's prototype, has a "length" property. Think of it as a variable that gets updated when you add or remove elements from the array.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Strings are also objects in Javascript, and a string is also considered an array of characters, thus having the "length" property as well.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

Setting JSON key with indexed array value [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 years ago.
I am trying to populate a JSON object by automatically setting the keys for an JSON object based on the string value of another array. For example,
var test = ["a","b"]
{test[0]:"A"}
However, I get a Syntax error when I do this, if I manually set the value as the string as shown in the third line {"a":"A"} this issue does not happen. I've checked that test[0] does indeed print out "a" and its datatype is a string. Is there any reason why this might be happening?
Try the following:
var test = ["a","b"]
var obj = {
[test[0]]:"A"
};
console.log(obj);

Comparison of strict equality of objects in JS [duplicate]

This question already has answers here:
How variables are allocated memory in Javascript?
(2 answers)
Closed 4 years ago.
I am looking at the spec:
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6
http://www.ecma-international.org/ecma-262/5.1/#sec-9.12
I have seen JS code do this:
var a = function(){}
var b = function(){}
var c = a;
console.log(a === b);
console.log(a === c);
the code works as expected, it seems to use strict equality - it doesn't convert the functions to strings and then compare strings - that would be crazy - it uses memory address or something like with Java, right?
How does it actually work? Does anyone know? The spec doesn't seem to mention function comparison, or objects for that matter.
it uses memory address or something like with Java, right?
Pretty much. A variable referencing an object is essentially a reference to a memory location - objects (and functions) are only equal if they reference the same location in memory. Thus, { foo: 'bar' } !== { foo: 'bar' } because each object was created separately.
All non-objects (primitives) can be considered to compare by value, though.

Javascript Object context change and eval [duplicate]

This question already has answers here:
calling eval() in particular context
(18 answers)
Closed 7 years ago.
I have some trouble using the Object properties. I want to evaluate an expression within the myObject context to avoid using the myObject.property.
My final goal is to evaluate a more complex expression like 'property1+property2' instead of 'myObject.property1+myObject.property2'.
I have tried the call method to change the context but, it doesn't seem to see the Object properties in the passed context(i.e. the Object containing the properties)(see the last line of the code below generating the error).
var myObject = {
property1: 20,
property2: 5000
};
print(myObject.property1); // return 20
print(eval.call(myObject,property1)); // ReferenceError: property1 is not defined
Is there any way to use the Object properties without the usage of this. or myObject. prefix?
Well, there's with statement which is deprecated and you probably shouldn't use it too much, but in this case maybe it wouldn't be considered harmful:
with(myObject){
console.log( property1 ); // 20
console.log( eval('property1') ); //20
console.log( eval('property1+property2') ); // 5020
}
http://jsfiddle.net/f7d1b79b/1/

Javascript's objects added to array is pass by value or reference? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript a pass-by-reference or pass-by-value language?
In this file I have an object this.objectA and this.allAs;
this.objectA contains a few attributes.
Everytime I got a new this.objectA, I add it to the array this.allAs.
I always reassign this.objectA when I get a new one.
Later I check my array this.allAs, I found that it correctly stores different this.objectA.
How come this.objectA gets overwritten, the objects inside this.allAs didn't get overwritten? (I expect all those stored objects to to pointing to the same this.objectA, but it didn't) Javascript is pass by value for objects???
You've got to get a lot more specific about what you're doing.
JavaScript passes by reference, but if you're saving local copies anywhere, and copying those values from return statements, then you're not working from reference anymore -- they're no longer pointers to the exact same object, necessarily.
Here's something to demonstrate passing references:
Bob = { name : "Bob", age : 32 };
function giveBobTo (obj, bobject) { obj.bob = bobject; }
Billy = {};
Jim = {};
giveBobTo(Billy, Bob);
giveBobTo(Jim, Bob);
Jim.bob.cars_on_lawn = 8;
Billy.bob.cars_on_lawn; // 8;
Bob.cars_on_lawn; // 8;
console.log( "Billy-Bob equals Jim-Bob equals Bob:",
Billy.bob === Jim.bob === Bob); // true

Categories

Resources