# Strings, Numbers, and Dates

Salesforce Certified JavaScript Developer I · lesson 2

Six rules decide almost every string, number, and date question.

Video: https://www.youtube.com/watch?v=f1m1NsAPQ1w
Page: https://shipitcertified.com/learn/salesforce-javascript-developer/strings-numbers-and-dates/
Free slide PDF (free account): https://shipitcertified.com/learn/salesforce-javascript-developer/strings-numbers-and-dates/

## Chapters

- 0:00 [Strings, Numbers, and Dates](https://www.youtube.com/watch?v=f1m1NsAPQ1w)
- 0:31 [Quick recap: three keywords, three rules](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=31s)
- 1:03 [Six rules decide almost every string, number, and date question](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=63s)
- 1:47 [One table holds the whole lesson](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=107s)
- 2:43 [Template literals use backticks and ${ }](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=163s)
- 3:45 [Strings never change in place](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=225s)
- 4:32 [indexOf returns 0 for a match at the start](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=272s)
- 5:23 [slice excludes the end and accepts negatives](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=323s)
- 6:10 [Other methods, and how strings compare](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=370s)
- 7:10 [Every number is a 64-bit double](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=430s)
- 8:11 [toFixed returns a string, not a number](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=491s)
- 9:11 [Number() is strict, parseInt() reads a prefix](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=551s)
- 10:19 [NaN never equals itself](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=619s)
- 11:10 [A Date counts milliseconds; months start at zero](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=670s)
- 12:29 [Date-only strings are UTC, date-times are local](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=749s)
- 13:20 [Subtracting dates gives milliseconds](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=800s)
- 14:27 [Getters come in local and UTC versions](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=867s)
- 15:24 [Seven terms to say in your own words](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=924s)
- 16:05 [Write your prediction first](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=965s)
- 17:25 [Eight questions, closed book](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=1045s)
- 18:35 [A developer runs the following code. What is logged?](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=1115s)
- 19:16 [NaN 100 0](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=1156s)
- 20:10 [Three values, three rules](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=1210s)
- 20:49 [Now test it, then move to coercion](https://www.youtube.com/watch?v=f1m1NsAPQ1w&t=1249s)

## Transcript

### Strings, Numbers, and Dates (0:00)

Welcome to module one, lesson two: strings, numbers, and dates. This module is called Variables, Types, and Collections, and it carries twenty three percent of the exam. In this lesson we look at three kinds of values: string, number, and Date. Each one has a famous trap, and the exam asks about all three. By the end, you will be able to read string, number, and date code, predict what it returns, and spot the trap before you run it.

### Quick recap: three keywords, three rules (0:31)

Before we start, a quick recap from lesson one. First, const blocks reassignment, but not mutation. Second, var is function scoped, and it is hoisted as undefined. Third, let and const are block scoped, and reading them too early throws a Reference Error. And fourth, our rhythm in every lesson is rule, trace, trap, proof. Today we move from how a variable is declared to the values it holds: strings, numbers, and dates.

### Six rules decide almost every string, number, and date question (1:03)

Here is what you will learn. Six rules decide almost every string, number, and date question on the exam. This domain is twenty three percent of the exam, which works out to about fourteen questions. And this lesson boils down to six rules. The six rules are these. First, strings are immutable. Second, searching and slicing, including the famous "index of" trap. Third, floating point numbers. Fourth, the difference between Number and "parse int". Fifth, zero based months and U T C. And sixth, date subtraction. We will also cover template literals, NaN, "to fixed", and the date getters.

### One table holds the whole lesson (1:47)

This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one cell of this table, with an example, so pause here and read each row aloud. String. The everyday tools are slice, includes, and "replace all". The trap is that "index of" can return zero. And a failed search gives minus one. Number. The everyday tools are "to fixed", Number, and "parse int". The trap is that zero point one plus zero point two is not zero point three. And a failed conversion gives NaN. Date. The everyday tools are "get time" and Date dot now. The trap is that months start at zero. And a bad date gives Invalid Date. One practical rule to carry with you: strings never change, numbers are approximate, and dates count milliseconds.

### Template literals use backticks and ${ } (2:43)

Let's start with strings. A string can use single quotes, double quotes, or backticks. Backticks make a template literal, which allows dollar brace expressions and multiple lines. Look at the code. We declare const name as the string Ann. The template literal starts with Hi, then dollar brace name, which inserts Ann. On the next line, one plus two is calculated inside the braces. So the result reads Hi, Ann, and then one plus two equals three. Next, a primitive string has type of string. But new String of foo creates a wrapper object, and its type of is object. Two details about reading a string. The length is a property, not a method, so there are no parentheses. And to read one character, "at" of minus one reads the last character, while square bracket minus one gives undefined. Only "at" accepts negative positions. Finally, remember that M D N says you should rarely use String as a constructor.

### Strings never change in place (3:45)

Now our first string trap. Strings never change in place. The wrong shortcut says, "to upper case" changes the string. The correct exam test asks, did I keep the value it returned? Look at the code. We declare const s as the string salesforce. Then s dot "to upper case" is called, but the result is thrown away, because we did not store it. So console dot log of s still prints salesforce, in lowercase. The original never changed. To keep the new string, assign it. Const t equals s dot "to upper case" gives you the uppercase version. The practical rule: every string method, slice, "to upper case", and "replace all", returns a new string and leaves the original unchanged.

### indexOf returns 0 for a match at the start (4:32)

Second string trap: "index of" returns zero for a match at the start. Look at the code. Widget, "index of" W, returns zero, because the match is at the very start. "Index of" i d returns one. And "index of" z returns minus one, because there is no match. So "index of" gives the index of the match, or minus one, and it is case sensitive. Now the trap. Look at the if statement. Zero is falsy, so the condition is false, and the block is skipped, even though the letter was found. The fix is to compare with minus one. If the result is not minus one, the text was found. Or use the methods that return booleans: includes, "starts with", and "ends with". The practical rule: test "index of" against minus one, or use includes.

### slice excludes the end and accepts negatives (5:23)

Next, extracting part of a string. Three methods look similar, so here are the rules. The slice method takes a start and an end. It excludes the end position, and it accepts negative positions, which count back from the end. The substring method is different. If the start is greater than the end, it swaps the arguments. And it treats negative values as zero. And "sub stir" is legacy. Avoid it in new code. Here is the example. Stringify, slice of minus four to minus one, gives gif. Minus four is the g, and the end, minus one, is excluded, so the last character is not included. Exam point: slice of minus four, minus one, counts from the end and stops before the last character.

### Other methods, and how strings compare (6:10)

A few more everyday methods. Look at the code. Seven, "pad start" of three and zero, gives zero zero seven. It pads the string until it is three characters long. And a-b-c, "replace all" dash with underscore, gives a underscore b underscore c. The everyday methods to know are "split", "trim", "pad start", "replace all", "to upper case", and "to lower case". Now, comparing strings. The less than and greater than operators compare by U T F sixteen code, not by dictionary order. So the letter a is greater than capital Z, which is true. For language aware ordering, use "locale compare". One more detail. Strings are sequences of U T F sixteen code units. So splitting with an empty string breaks an emoji into two halves. Remember: comparison with less than and greater than is by code, not by dictionary order.

### Every number is a 64-bit double (7:10)

Now numbers. Every Number in JavaScript is a sixty four bit double, and that sets up our next exam trap. Look at the code. Zero point one plus zero point two does not give zero point three. It gives zero point three, followed by fifteen zeros, and then a four. So zero point one plus zero point two, triple equals zero point three, is false. There is no separate integer type. For larger integers, there is "big int". And the largest safe integer is two to the power fifty three, minus one, which is about nine quadrillion. Beyond it, integers may be inexact. Why does zero point one plus zero point two go wrong? Decimals like zero point one cannot be stored exactly, so the stored number is a close approximation. To compare approximately, Number dot epsilon is the smallest gap between two representable numbers. The practical rule: never use exact equality on decimal fractions.

### toFixed returns a string, not a number (8:11)

Next, rounding. Look at the code. Const t equals twelve point three four, "to fixed" of one. That rounds to one decimal and gives the string twelve point three. Type of t is string, not number. Now a surprise. Two point five five, "to fixed" of one, gives two point five, not two point six. Decimals cannot be stored exactly, and the nearest stored value to two point five five is slightly lower. That is M D N's own example, so rounding with decimals can surprise you. The Math methods return numbers. Math dot floor, ceil, round, and trunc all do. Math dot floor of minus one point one is minus two, because floor always rounds down. And to round to two decimals as a number, Math dot round of one point two three four five six times one hundred, divided by one hundred, gives one point two three. The exam point: "to fixed" returns a string.

### Number() is strict, parseInt() reads a prefix (9:11)

Now an exam favorite: converting strings to numbers. Number and "parse int" look similar, but they follow different rules. Here is the comparison table. First input, the string one hundred a. Number of it is NaN, because Number checks the whole string. "Parse int" of it is one hundred, because "parse int" reads from the start and stops at the first invalid character. Second input, one hundred p x. The same rule. Number gives NaN, and "parse int" gives one hundred. Third input, the empty string. Number of the empty string is zero. But "parse int" finds no digits, so it returns NaN. A few more rules. Number of x converts the whole value, and the unary plus operator behaves the same way. Number of null is zero, and Number of undefined is NaN. And "parse int" stops at the first invalid character. It also takes an optional base. The exam point: Number of one hundred a is NaN, "parse int" of one hundred a is one hundred, and Number of the empty string is zero.

### NaN never equals itself (10:19)

Next, NaN. NaN means not a number. It is the result of a failed conversion or failed arithmetic. Look at the code. The first rule: NaN never equals itself. NaN triple equals NaN is false. Next, the global "is nan" function coerces its argument first. So "is nan" of the string str converts it to a number, gets NaN, and returns true. Number dot "is nan" does not coerce. So Number dot "is nan" of the string str returns false, because a string is not the value NaN. Finally, overflow. Number dot "max value" times two is too big to represent, and gives Infinity. The practical rule: use Number dot "is nan" when a string should not count as NaN.

### A Date counts milliseconds; months start at zero (11:10)

Now dates. A Date object stores one number: the milliseconds since the first of January, nineteen seventy, U T C. That moment is called the epoch. Look at the code. New Date of nineteen ninety five, eleven, seventeen, is December seventeenth, nineteen ninety five, in local time. Why December, when the month says eleven? Because months are zero based. Zero is January, and eleven is December. So "get month" on that date returns eleven, not twelve. Same idea here. New Date of twenty twenty four, one, one, is February first, not January first. Another exam trap. And new Date of zero, "to I S O string", gives nineteen seventy, January first, at midnight, ending in Z for U T C. A few rules to know. The forms of the constructor are: new Date with nothing, for right now; a date string; year, month, and day in local time; or a number of milliseconds. Months run zero to eleven, and the day of the month runs one to thirty one. "Get day" returns zero to six, and Sunday is zero. Exam point: new Date of twenty twenty four, one, one, is February first, not January first.

### Date-only strings are UTC, date-times are local (12:29)

Another date trap, and it is about parsing strings. A date only string, like twenty eleven, ten, ten, is parsed as U T C. But a date and time string with no offset, like twenty eleven, ten, ten, T, fourteen forty eight, is parsed as local time. Look at the code. The first line, date only, is U T C. The second line, with a time and no offset, is local time. And "to I S O string" always returns U T C, ending in Z. Two more details. Free form date strings are discouraged, because behavior varies between environments. And "to I S O string" returns U T C with a Z suffix, and "to json" calls it. The practical rule: local time results depend on the time zone, so run the example in your own environment.

### Subtracting dates gives milliseconds (13:20)

Now date arithmetic. Subtracting two dates gives milliseconds. Look at the code. Const milliseconds per day is twenty four times sixty times sixty times one thousand. That is the number of milliseconds in one day. Now const days equals the difference of two dates. The first is new Date of twenty twenty five, twelve, twenty five. From it, we subtract new Date of twenty twenty five, twelve, zero one. Then divide by milliseconds per day, and the result is twenty four. The minus operator turns both dates into timestamps, so the result is milliseconds. But the plus operator does not work this way. With plus, a Date becomes a string. So new Date of zero plus one gives a string that ends in one. For measuring intervals, use Date dot now, or "get time", which give the timestamp as a number. One caution. Across daylight saving changes, units larger than hours need careful handling. Exam point: date B minus date A is milliseconds. But date A plus one is a string.

### Getters come in local and UTC versions (14:27)

Last on dates: the getters. Look at the code. Const d is new Date of twenty twenty four, zero, thirty one. That is January thirty first. "Get full year" returns twenty twenty four. And "get U T C hours" is the U T C version of "get hours". Every getter has a local version and a U T C version. Out of range values roll over. New Date of twenty twenty four, one, zero uses day zero of February, which is the last day of the previous month: January thirty first. And type of Date, called without new, is string. One more limit. A Date can hold at most one hundred million days either side of the epoch. Beyond that, it holds NaN, and it is called an Invalid Date. And note that local getters depend on the time zone, so results can differ between machines. Exam point: Date called without new returns a string, not a Date object.

### Seven terms to say in your own words (15:24)

Seven key terms to say in your own words. A template literal is a backtick string with dollar brace expressions and multiple lines. Immutable means a string's characters cannot change in place. NaN is the result of a failed number conversion. Number dot epsilon is the smallest gap between two doubles. "Max safe integer" is two to the power fifty three, minus one, the largest exact integer. The epoch is the first of January, nineteen seventy, at midnight U T C. And an Invalid Date is a Date holding a NaN timestamp. Pause the video now. Cover each card and explain the term aloud.

### Write your prediction first (16:05)

Now the proof stage, starting with a lab. Write your prediction first. You have six snippets on screen. For each one, decide what it logs, and write it down before checking. Snippets four and five are the lab from the curriculum: format a price string, and compute the days between two dates. Take three minutes on your own, and write down your predictions before checking. Now the answers, one snippet at a time. Snippet one prints abc. The "to upper case" result was thrown away, so the original string is unchanged. Snippet two prints no. "Index of" W returns zero, which is falsy, so the condition is false. Snippet three prints false. Zero point one plus zero point two is not exactly zero point three. Snippet four gives the string dollar nineteen point five zero. "To fixed" of two pads to two decimals, and it returns a string. Snippet five prints twenty four. Subtracting the dates gives milliseconds, and dividing by eighty six million four hundred thousand gives days. Snippet six prints NaN, then one hundred. Number checks the whole string, and "parse int" reads the prefix. A wrong prediction is the lesson. Go back to the slide that explains it.

### Eight questions, closed book (17:25)

Self check: eight questions, closed book. Answer out loud, then I will reveal each one. One. Can a string change one character in place? No. You have to build a new string. Two. What does stringify, slice of minus four to minus one, return? Gif. Three. What does seven, "pad start" of three and zero, return? Zero zero seven. Four. Is zero point one plus zero point two equal to zero point three? False. Five. What is the type of twelve point three four, "to fixed" of one? String. Six. Which month is new Date of twenty twenty four, one, one? February, because months start at zero. Seven. What do the global "is nan" and Number dot "is nan" return for the string str? True for the global one, and false for Number dot "is nan". And eight. What is the type of Date called without new? String. How many did you get? Anything you missed, go back to its slide.

### A developer runs the following code. What is logged? (18:35)

Time for a practice question, taken from the question bank. This is a predict question. Pause the video and trace each call before you read the options. A developer runs the code shown. What is logged? Option A: one hundred, one hundred, zero. Option B: NaN, one hundred, NaN. Option C: NaN, NaN, zero. Option D: NaN, one hundred, zero. This question combines the two conversion rules from this lesson. Number reads the whole value, and "parse int" reads a prefix. Pause now, and I will give you the answer on the next slide.

### NaN 100 0 (19:16)

The answer is D. NaN, one hundred, zero. Here is why. Number of one hundred a is NaN, because Number checks the whole string. "Parse int" of one hundred a is one hundred, because it reads the leading digits and stops at the a. And Number of the empty string is zero. Now the wrong options. A says one hundred, one hundred, zero. That treats Number like "parse int". But Number checks the whole string, so one hundred a is NaN. B says NaN, one hundred, NaN. That forgets that the empty string converts to zero, not NaN. C says NaN, NaN, zero. That forgets that "parse int" reads the prefix, so it finds the one hundred. The takeaway: Number checks the whole string, "parse int" reads a prefix, and an empty string is zero.

### Three values, three rules (20:10)

Let's consolidate. Three values, three rules. A string is immutable. Its methods return new strings, and "index of" can return zero, so compare with minus one. A number is a sixty four bit double. "To fixed" returns a string. Number checks the whole value, and "parse int" reads a prefix. And a Date counts milliseconds since nineteen seventy, U T C. Months start at zero, and subtracting dates gives milliseconds. Remember: if output depends on local time, run it in your own environment. If you can say these three cards from memory, you've got the lesson.

### Now test it, then move to coercion (20:49)

That completes lesson two. Now test it, then move on to coercion. The flow is: read it, predict it, test it. Your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Type Coercion and Its Effects, we look at what JavaScript does when it mixes these types. See you there.
