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

Dates & Arrays

4 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 5 deck

Dates & Arrays
Fullscreen for presentation · Print / PDF for a handout
1 / 4
Lesson

Dates & Arrays

Working with date/time values and ordered collections.

Dates & Arrays

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!

Dates & Arrays

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
Dates & Arrays

Activity — complete the code

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);