This may be completely stupid but given I type this into my browser console:
var arr = [];
arr.item = 'val';
console.log( arr );
arr;
What is the arr;
syntax doing behind the scenes? I'm assuming console.log( arr );
is iterating all the properties of the arr
object but what is arr;
doing? Also does []
tell me I'm dealing with an object of type array and {}
tells me I'm dealing with an object of type object literal? So [ item: 'val' ]
is an object with a prototype of array and { item: 'val' }
is an object of prototype object literal?
Edit: Another way to ask this might be why are console.log
and arr;
different?
In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.
An array is an object that can store multiple values at once. For example, const words = ['hello', 'world', 'welcome']; Here, words is an array.
Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.
Js array is divided into two types: One-dimensional arrays. Multi-dimensional arrays.
Sorry, started to type the comment and realized it was actually a full answer.console.log
yields an implementation dependent string representation of the argument. It does not iterate the properties of an object in most I've seen. String serializtions using the default toString
method look like [object Foo]
where 'Foo' is the internal class property of the object. You can see this for arrays by using Object.prototype.toString.call([]);
.
The last line on the other hand, is just the value. How that gets represented as an evaluated expression in your browser console is implementation-dependent, but for all intents and purposes it does nothing and there is no reason you would want to write that.
Note that adding a property to an array with the .
operator is almost never what you want: it does not add to the contents of the array but treats the array as an object. Iterating the indicies of the array will not yield that property, nor will its methods such as .map
include it. Use .push
. If you want string-keyed properties, use an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With