Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript arrays?

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?

like image 605
JSP Avatar asked Dec 12 '15 01:12

JSP


People also ask

What are JavaScript arrays?

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.

What is array in JavaScript explain with example?

An array is an object that can store multiple values at once. For example, const words = ['hello', 'world', 'welcome']; Here, words is an array.

How do we write array in JavaScript?

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.

How many types of arrays are there in JavaScript?

Js array is divided into two types: One-dimensional arrays. Multi-dimensional arrays.


1 Answers

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.

like image 180
Jared Smith Avatar answered Sep 25 '22 21:09

Jared Smith