Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Array() > Creating Arrays

Creating Arrays

Like most of the objects in JavaScript, an array object can be created using the new operator in conjunction with the Array() constructor, or by using the literal syntax.

Below, I create the myArray1 array with predefined values using the Array() constructor, and then myArray2 using literal notation.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

// Array() constructor
var myArray1 = new Array('blue', 'green', 'orange', 'red');

console.log(myArray1); // logs ["blue", "green", "orange", "red"]

// array literal notation
var myArray2 = ['blue', 'green', 'orange', 'red'];

console.log(myArray2); // logs ["blue", "green", "orange", "red"]

</script></body></html>

It is more common to see an array defined using the literal syntax, but one should be aware that this shortcut is merely concealing the use of the Array() constructor.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint