CHAPTER 11 · 3 lessons · 39 exercises
The data toolbox
Hand data off with JSON, work with dates using Date, and check the shape of text with a regular expression. Three tools you reach for every day on the job.
You now know how to create values, work with them, and prepare for failure. This chapter turns to something else: three tools that always come up once you start talking to the outside world.
First, JSON. An object stays fine as long as it lives in memory, but to save it to a file or send it to another computer it has to become a plain string first. JSON.stringify converts a value into that string, and JSON.parse turns the string back into the original shape. This exchange becomes the foundation for the networking you will learn later in the course.
Second, Date. Questions like "what day is it today", "which of these two dates comes first", or "how many days are left" are awkward to answer with plain number arithmetic, because leap years and months of different lengths get in the way. You let a Date build the moment for you, then pull the year, month, and day back out of it, or compare two of them directly.
Third, regular expressions (RegExp). Questions like "does this look like a postal code" or "is this made only of digits" — checking whether a string follows a fixed shape — come up constantly. Instead of checking character by character with if, you write the pattern once and hand it to .test().
None of these three are "new syntax" the way earlier chapters were. This chapter is about getting comfortable with tools JavaScript already ships with — objects and their methods. That is exactly why there is so little to memorize, yet you will reach for them so often on the job.
Lessons in this chapter
Hand data off with JSON
- 91Converting to and from JSONTurn objects into strings with JSON.stringify, and restore them with JSON.parse.Go to the exercises
Work with dates and times
- 92Working with dates and timesUse the Date class to create timestamps, inspect years, months, and days, and compare dates.Go to the exercises
Check the shape of text
- 93Testing text patternsUse RegExp (regular expressions) to test if strings match specific patterns like digits and lengths.Go to the exercises