Chapter 1

Here are the solutions to the Exercises, for the Chapter 1, JavaScript Gotchas chapter.

Exercise 1

 return​ ​//undefined
  2 * 3;
 
 return​ 2 ​//6
  * 3;
 
 return​ 2 * 3 ​//6
  ;

Exercise 2

 //That's one strange comparison, but given the choices, choose ===
 "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)); ​//no, can't vote
 console.log(canVote(​"12"​)); ​//no, can't vote
 console.log(canVote(17)); ​//no, can't vote
 console.log(canVote(​'@18'​)); ​//no, can't vote
 console.log(canVote(18)); ​//yay, start voting
 console.log(canVote(28)); ​//please vote

Exercise 4

 //The code as given in the exercise will not terminate.
 
 //Here's the fix: use option strict and declare i before use in the two loops
 'use strict'​;
 
 const​ isPrime = ​function​(n) {
 for​(​let​ i = 2; i <= Math.sqrt(n); i++) {​//or < n instead of <= Math.sqrt(n)
 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.
Reset