Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 5

Dates & Arrays

Working with date/time values and ordered collections.


JavaScript Date Object

The Date object lets you work with years, months, days, hours, minutes, seconds and milliseconds.

// Create a Date object for RIGHT NOW
var now = new Date();
console.log(now);              // e.g. "Fri Mar 18 2016 10:18:00"

// Dates as a number (milliseconds since Jan 1, 1970)
console.log(Date.now());       // e.g. 1458277734226

// Useful Date methods
var d = new Date();
d.getFullYear();   // 2024
d.getMonth();      // 0-11  (0 = January!)
d.getDate();       // day of month (1-31)
d.getHours();      // hour (0-23)
d.getMinutes();    // minutes (0-59)

Remember to add 1 to getMonth() when displaying the month to users!

JavaScript Arrays

An array is an ordered collection of values referenced by a single variable name. Arrays can hold mixed types.

// Two ways to create arrays
var points = new Array(40, 100, 1, 5);  // old way — avoid
var points = [40, 100, 1, 5];           // modern syntax

// Arrays can mix types
var faq = [];
faq[0] = "What are JavaScript arrays";
faq[1] = Date.now();
faq[2] = 5000;

// Accessing elements (zero-indexed!)
console.log(points[0]);   // 40
console.log(points[1]);   // 100

// Adding elements to an array
points.push(7);                 // push(): adds to the end
points[points.length] = 9;      // assigns at next index
points[10] = 3;                 // direct index: creates empty holes

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the Date and Array code.

// Create a Date object for right now
var now = new ();
 
// Milliseconds since Jan 1, 1970
console.log(Date.());
 
// Arrays are zero-indexed
var points = [40, 100, 1, 5];
console.log(points); // 40
 
// Add to the end of an array
points.(7);