Add nullish coalescing to multiple articles, refactor operators, renumber the chapter

This commit is contained in:
Ilya Kantor 2020-05-02 17:37:12 +03:00
parent 175aefa0b8
commit 8a13c992d6
54 changed files with 386 additions and 183 deletions

View file

@ -0,0 +1,32 @@
The reason is that prompt returns user input as a string.
So variables have values `"1"` and `"2"` respectively.
```js run
let a = "1"; // prompt("First number?", 1);
let b = "2"; // prompt("Second number?", 2);
alert(a + b); // 12
```
What we should to is to convert strings to numbers before `+`. For example, using `Number()` or prepending them with `+`.
For example, right before `prompt`:
```js run
let a = +prompt("First number?", 1);
let b = +prompt("Second number?", 2);
alert(a + b); // 3
```
Or in the `alert`:
```js run
let a = prompt("First number?", 1);
let b = prompt("Second number?", 2);
alert(+a + +b); // 3
```
Using both unary and binary `+` in the latest code. Looks funny, doesn't it?

View file

@ -0,0 +1,18 @@
importance: 5
---
# Fix the addition
Here's a code that asks the user for two numbers and shows their sum.
It works incorrectly. The output in the example below is `12` (for default prompt values).
Why? Fix it. The result should be `3`.
```js run
let a = prompt("First number?", 1);
let b = prompt("Second number?", 2);
alert(a + b); // 12
```