[JavaScript] Initializers

For primitive types, you can use the literals (numbers or strings) to initialize variables. For objects and arrays, JavaScript provides initializers (also called “object literals” or “array literals“).

1. Array Initializer

You can create an array using the Array object constructor. But an array initializer is a way to do it when the value is initially known.

An array initializer is a comma-separated list of values contained within square brackets. The size will be automatically determined.

var arr1 = []; // empty
var arr2 = [1, 2, 3, 4];
alert(arr1.length); // 0
alert(arr2.length); // 4

 

2. Object Initializer

Objects consist of properties. An object initializer is also a comma-separated list within curly braces. Each item of the list is a pair of a property name and a value separated by a colon.

var point = { x: 5, y: 4 };
alert(JSON.stringify(point));
alert(point.x + ", " + point.y);

Object initializers are not restricted to properties. You can add methods to the object too.

var point = {
  x: 5,
  y: 4,
  size: function () { return this.x * this.y; }
};
alert(point.size()); // 20

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s