Chapter 1
Here are the solutions to the Exercises, for the Chapter 1, JavaScript Gotchas chapter.
Exercise 1
| return |
| 2 * 3; |
| |
| return 2 |
| * 3; |
| |
| return 2 * 3 |
| ; |
Exercise 2
| |
| "2.0" / 2 * "2.0" === 2 / 2 * 2; |
Exercise 3
| 'use strict'; |
| |
| const canVote = function(age) { |
| if(age === 18) { |
| return 'yay, start voting'; |
| } |
| |
| if(age > 17) { |
| return "please vote"; |
| } |
| |
| return "no, can't vote"; |
| }; |
| console.log(canVote(12)); |
| console.log(canVote("12")); |
| console.log(canVote(17)); |
| console.log(canVote('@18')); |
| console.log(canVote(18)); |
| console.log(canVote(28)); |
Exercise 4
| |
| |
| |
| 'use strict'; |
| |
| const isPrime = function(n) { |
| for(let i = 2; i <= Math.sqrt(n); i++) { |
| if(n % i === 0) return false; |
| } |
| |
| return n > 1; |
| }; |
| |
| const sumOfPrimes = function(n) { |
| let sum = 0; |
| for(let i = 1; i <= n; i++) { |
| if(isPrime(i)) sum += i; |
| } |
| |
| return sum; |
| }; |
| |
| console.log(sumOfPrimes(10)); |
Exercise 5
ESLint reported the following errors for the given code:
| 1:1 error Use the global form of 'use strict' strict |
| 1:1 error Unexpected var, use let or const instead no-var |
| 2:3 error Unexpected var, use let or const instead no-var |
| 4:7 error 'index' is not defined no-undef |
| 4:18 error 'index' is not defined no-undef |
| 4:35 error 'index' is not defined no-undef |
| 5:17 error 'index' is not defined no-undef |
| 5:23 error Expected '===' and instead saw '==' eqeqeq |
| 6:23 error 'index' is not defined no-undef |
| 11:5 error Expected '===' and instead saw '==' eqeqeq |
| 14:5 error 'i' is not defined no-undef |
| 14:12 error 'i' is not defined no-undef |
| 14:21 error 'i' is not defined no-undef |
| 15:23 error 'i' is not defined no-undef |
| 15:53 error 'i' is not defined no-undef |
| |
| ✖ 15 problems (15 errors, 0 warnings) |
| 2 errors, 0 warnings potentially fixable with the `--fix` option. |
Here’s the code after removing the errors—using const where possible and let instead of var:
| 'use strict'; |
| |
| const isPerfect = function(number) { |
| let sumOfFactors = 0; |
| |
| for(let index = 1; index <= number; index++) { |
| if(number % index === 0) { |
| sumOfFactors += index; |
| } |
| } |
| |
| return sumOfFactors === number * 2; |
| }; |
| |
| for(let i = 1; i <= 10; i++) { |
| console.log('is ' + i + ' perfect?: ' + isPerfect(i)); |
| } |
..................Content has been hidden....................
You can't read the all page of ebook, please click
here login for view all page.