Wrapping Up

JavaScript is a very powerful language with some unpleasant surprises. You learned to be careful about automatic insertion of ;, to use === instead of ==, and to declare variables before use. We also discussed a few ways to proactively deal with the gotchas—by using the ’use strict’; directive and lint tools. In the next chapter we will discuss how a very fundamental task of declaring variables has changed, for the better, in JavaScript.

Exercises

Take a break and practice, using these code exercises, to identify some potential errors in code and ways to improve writing JavaScript. You can find answers to these exerciseshere.

Exercise 1

What will be the result of each of the following return statements?

 return
  2 * 3;
 
 return 2
  * 3;
 
 return 2 * 3
  ;

Exercise 2

Is it better to use == or === in the following comparison?

 "2.0" / 2 * "2.0" == 2 / 2 * 2;

Exercise 3

Write a function named canVote() that takes age as a parameter and returns a string, as shown in the following example calls to the function:

 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

What is the output of the following code?

 var isPrime = function(n) {
  for(i = 2; i < n; i++) {
  if(n % i == 0) return false;
  }
 
  return n > 1;
 }
 
 var sumOfPrimes = function(n) {
  var sum = 0;
  for(i = 1; i <= n; i++) {
  if(isPrime(i)) sum += i;
  }
 
  return sum;
 }
 
 console.log(sumOfPrimes(10));

Fix the errors in code to get the desired result.

Exercise 5

The code in this exercise is intended to determine if a given number is a perfect number.[13]

Eyeball the following code to detect the errors and jot them down. Then run ESLint on the code to display the errors. Compare with what you jotted down to see if you caught them all. Then fix the errors until ESLint is quiet.

 var​ isPerfect = ​function​(number) {
 var​ sumOfFactors = 0;
 
 for​(index = 1; index <= number; index++) {
 if​(number % index == 0) {
  sumOfFactors += index;
  }
  }
 
 return​ sumOfFactors
  == number * 2;
 };
 
 for​(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