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 nowvar now = new ();// Milliseconds since Jan 1, 1970console.log(Date.());// Arrays are zero-indexedvar points = [40, 100, 1, 5];console.log(points); // 40// Add to the end of an arraypoints.(7);