Skip to main content

Intro to JavaScript Homework

Welcome! These are some bonus puzzles to accompany the Intro to JavaScript class. Please take a look at the puzzles, and work on one that looks challenging but not completely overwhelming. You can always reference the slides if you get stuck. Commit to spend at least 20 minutes trying to figure out a problem before you look at the answers. It helps you learn!

Class 1

The Fortune Teller

Why pay a fortune teller when you can just program your fortune yourself?

  • Store the following into variables: number of children, partner's name, geographic location, job title.
  • Output your fortune to the screen like so: "You will be a X in Y, and married to Z with N kids."
var numKids  = 5;
var partner  = 'David Beckham';
var geolocation = 'Costa Rica';
var jobTitle = 'web developer';

var future = 'You will be a ' + jobTitle + ' in ' + geolocation + ', and married to ' +
partner + ' with ' + numKids + ' kids.';
console.log(future);

The Age Calculator

Forgot how old someone is? Calculate it!

  • Store the current year in a variable.
  • Store their birth year in a variable.
  • Calculate their 2 possible ages based on the stored values.
  • Output them to the screen like so: "They are either NN or NN", substituting the values.
var birthYear = 1984;
var currentYear  = 2016;
var age  = currentYear - birthYear;
console.log('They are either ' + age + ' or ' + (age - 1));

The Temperature Converter

Let's make a program to convert celsius tempatures to fahrenheit and vice versa, so we can complain about the weather with our friends oversees.

Reminder: To convert celsius to fahrenheit, multiply by 9, then divide by 5, then add 32. To convert fahrenheit to celsius, deduct 32, then multiply by 5, then divide by 9.

Unicode Characters: To print the degrees symbol in JavaScript, we need to use the write \u00B0 to represent the unicode character for the degress symbol.

  • Store a celsius temperature into a variable.
  • Convert it to fahrenheit and output "NN°C is NN°F".
  • Now store a fahrenheit temperature into a variable.
  • Convert it to celsius and output "NN°F is NN°C."
var inputCelsius  = 25;
var outputFahrenheit = (inputCelsius * 9)/5 + 32;
console.log(inputCelsius + '\u00B0 Celsious is ' + outputFahrenheit + '\u00B0 Fahrenheit');

var inputFahrenheit  = 73;
var outputCelsius = (inputFahrenheit - 32)/9 * 5;
console.log(inputFahrenheit + '\u00B0 Fahrenheit is ' + outputCelsius + '\u00B0 Celsious.');

Challenge Question: Using Math functions

JavaScript has a built-in tool that can generate a random number between 0 and 1. This tool is called a method. We'll talk about methods more later in the class. For now, know if you type Math.random(), you'll get a random number between 0 and 1.

Using this tool, update your fahrenheit to celsius tempature conversion program to do the following:

  • Instead of inputing a value for the Fahrenheit tempature, use Math.random() to generate a random tempature between 0 and 100
  • Have to program output: "It is NN°F today. That's NN°C."
var inputFahrenheit  = Math.random()*100;
var outputCelsius = (inputFahrenheit - 32)/9 * 5;
console.log('It is ' + inputFahrenheit + '\u00B0 Fahrenheit today. That\'s ' + outputCelsius + '\u00B0 Celsius.');

Class 2

The Fortune Teller: With Functions!

Let's turn one of the Class 1 Exercises into a function.

  • Write a function named tellFortune that:
    • takes 4 arguments: number of children, partner's name, geographic location, job title.
    • outputs your fortune to the screen like so: "You will be a X in Y, and married to Z with N kids."
  • Call that function 3 times with 3 different values for the arguments.
function tellFortune(jobTitle, geolocation, partner, numKids) {
  var future = 'You will be a ' + jobTitle + ' in ' + geolocation + ' and married to ' +
  partner + ' with ' + numKids + ' kids.';
  console.log(future);
}

tellFortune('astronaut', 'Spain', 'Shaq', 3);
tellFortune('stunt double', 'Japan', 'Bruce Wayne', 9);
tellFortune('Elvis impersonator', 'Russia', 'Elon Musk', 0);

What number is bigger?

Write a function that compares two numbers and returns the larger one. Be sure to try it out with some different numbers. Bonus: add error messages if the numbers are equal or cannot be compared.

Don't forget to test it!

function greaterNum(num1, num2) {
  if (num1 === num2) {
    console.log('Those numbers are equal');
  } else if (num1 > num2) {
    return num1;
  } else if (num2 > num1) {
    return num2;
  } else {
    console.log('Those are simply incomparable!');
    return undefined;
  }
}

console.log(greaterNum(3, 3));
console.log(greaterNum(7, -2));
console.log(greaterNum(5, 9));
console.log(greaterNum(5, 'dog'));

Pluralize

Write a function pluralize that takes in two arguments, a number and a word, and returns the plural. For example:

pluralize(5, 'cat'): '5 cats'
pluralize(7, 'turtle'): '7 turtles'

Bonus: Make it handle a few collective nouns like "sheep" and "geese".

function pluralize(number, noun) {
  if (number != 1 && noun != 'sheep' && noun != 'geese') {
    return number + ' ' + noun + 's';
  } else {
    return number + ' ' + noun;
  }
}
console.log('I have ' + pluralize(0, 'cat'));
console.log('I have ' + pluralize(1, 'cat'));
console.log('I have ' + pluralize(2, 'cat'));
console.log('I have ' + pluralize(3, 'geese'));

The Calculator

  • Write a function called squareNumber that will take one argument (a number), square that number, and return the result. It should also log a string like "The result of squaring the number 3 is 9."
  • Write a function called halfNumber that will take one argument (a number), divide it by 2, and return the result. It should also log a string like "Half of 5 is 2.5.".
  • Write a function called percentOf that will take two numbers, figure out what percent the first number represents of the second number, and return the result. It should also log a string like "2 is 50% of 4."
  • Write a function called areaOfCircle that will take one argument (the radius), calculate the area based on that, and return the result. It should also log a string like "The area for a circle with radius 2 is 12.566370614359172."
    • Bonus: Round the result so there are only two digits after the decimal.
  • Write a function that will take one argument (a number) and perform the following operations, using the functions you wrote earlier:
    1. Take half of the number and store the result.
    2. Square the result of #1 and store that result.
    3. Calculate the area of a circle with the result of #2 as the radius.
    4. Calculate what percentage that area is of the squared result (#3).
function squareNumber(num) {
  var squaredNumber = num * num;
  console.log('The result of squaring the number ' + num + ' is ' + squaredNumber);
  return squaredNumber;
}

squareNumber(3);

function halfOf(num) {
  var half = num / 2;
  console.log('Half of ' + num + ' is ' +  half);
  return half;
}

halfOf(5);

function percentOf(num1, num2) {
  var percent = (num1/num2) * 100;
  console.log(num1 + ' is ' + percent + '% of ' + num2);
  return percent;
}

percentOf(5, 10);

function areaOfCircle(radius) {
  var area = Math.PI * squareNumber(radius);
  console.log('The area of circle with radius ' + radius + ' is ' + area);
  return area;
}

areaOfCircle(2);

function doCrazyStuff(num) {
  var half    = halfOf(num);
  var squared = squareNumber(half);
  var area    = areaOfCircle(squared);
  var result  = percentOf(squared, area);
}

doCrazyStuff(5);

Challenge Question: String Manipulation

If you feel comfortable with the other exercises, it's time to expand your knowledge! These puzzles involve manipulating strings; to try them out, you'll need to use some of the built-in JavaScript methods for strings. Methods are pre-written functions that are built into the language.

These questions are not as straightforward as the others. They challenge you to really think like a programmer. Really try to solve them before you peek at the answer.

MixUp

Create a function called mixUp. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long. For example:

mixUp('mix', 'pod'): 'pox mid'
mixUp('dog', 'dinner'): 'dig donner'
//This function uses the slice() method. It extracts a part of a string and returns a new string
function mixUp(string1, string2) {
  return string2.slice(0, 2) + string1.slice(2) + " " + string1.slice(0, 2) + string2.slice(2);
}
console.log(mixUp('mix', 'pod'));
console.log(mixUp('dog', 'dinner'));

FixStart

Create a function called fixStart. It should take a single argument, a string, and return a version where all occurrences of its first character have been replaced with '*', except for the first character itself. You can assume that the string is at least one character long. For example:

fixStart('babble'): 'ba**le'
fixStart('turtle'): 'tur*le'
//This function uses a few new methods and regular expressions
function fixStart(inputString) {
  var firstChar = inputString.charAt(0);
  return firstChar + inputString.slice(1).replace(new RegExp(firstChar, 'g'), '*');
}
console.log(fixStart('babble'));
console.log(fixStart('turtle'));

Class 3

Even/Odd Counter

Write a for loop that will iterate from 0 to 20. For each iteration, it will check if the current number is even or odd, and report that to the screen (e.g. "2 is even")

for (var i = 0; i <= 20; i++) {
  if (i % 2 === 0) {
    console.log(i + ' is even');
  } else {
    console.log(i + ' is odd');
  }
}

Top Choice

Create an array to hold your top choices (colors, presidents, whatever). For each choice, log to the screen a string like: "My #1 choice is blue."

Bonus: Change it to log "My 1st choice, "My 2nd choice", "My 3rd choice", picking the right suffix for the number based on what it is. The method slice might be helpful here.

//Simple code
var choices = ['red', 'orange', 'pink', 'yellow'];
for (var i = 0; i < choices.length; i++) {
  console.log('My #' + (i + 1) + ' choice is ' + choices[i]);
}

//Bonus solution
var choices = ['red', 'orange', 'pink', 'yellow'];
function findLast (inputNum) {
  tmpSlice = String(inputNum);
  var lastDigit = (tmpSlice.slice(-1));
  return lastDigit;
}

for (var i = 0; i < choices.length; i++) {
  var choiceNum = i + 1;
  var choiceNumSuffix = 0;
  var choiceNumLast = findLast(choiceNum);
  if (choiceNumLast == 1) {
    choiceNumSuffix = 'st';
  } else if (choiceNumLast == 2) {
    choiceNumSuffix = 'nd';
  } else if (choiceNumLast == 3) {
    choiceNumSuffix = 'rd';
  } else {
    choiceNumSuffix = 'th';
  }
  console.log('My ' + choiceNum + choiceNumSuffix + ' choice is ' + choices[i]);
}

The Reading List

Keep track of which books you read and which books you want to read!

  • Create an array of objects, where each object describes a book and has properties for the title (a string), author (a string), and alreadyRead (a boolean indicating if you read it yet).
  • Iterate through the array of books. For each book, log the book title and book author like so: "The Hobbit by J.R.R. Tolkien".
  • Now use an if/else statement to change the output depending on whether you read it yet or not. If you read it, log a string like 'You already read "The Hobbit" by J.R.R. Tolkien', and if not, log a string like 'You still need to read "The Lord of the Rings" by J.R.R. Tolkien.'
var books = [
  {
    title: 'You Don'\t Know JS',
    author: 'Kyle Simpson',
    alreadyRead: false
  },
  {
    title: 'Eloquent JavaScript',
    author: 'Marijn Haverbeke',
    alreadyRead: true
  }
];

for (var i = 0; i < books.length; i++) {
  var book = books[i];
  var bookInfo = book.title + '" by ' + book.author;
  if (book.alreadyRead) {
    console.log('You already read "' + bookInfo);
  } else {
    console.log('You still need to read "' + bookInfo);
  }
}

Class 4

Logo Hijack

  • Open up www.google.com in Chrome or Firefox, and open up the console.
  • Find the Google logo and store it in a variable.
  • Modify the source of the logo IMG so that it's a Yahoo logo instead. (http://www.logostage.com/logos/yahoo.GIF)
var img = document.getElementById('hplogo');
img.width = 400;
img.src = 'http://www.logostage.com/logos/yahoo.GIF';

About Me

Start with this HTML and save it as "aboutme.html":

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <title>About Me</title>
</head>
<body>
  <h1>About Me</h1>

  <ul>
    <li>Nickname:
      <span id="nickname"></span>
    </li>
    <li>Favorites:
      <span id="favorites"></span>
    </li>
    <li>Hometown:
      <span id="hometown"></span>
    </li>
   </ul>

 </body>
</html>
  • Add a script tag to the bottom.
  • (In JavaScript) Change the body tag's style so it has a font-family of "Arial, sans-serif".
  • (In JavaScript) Replace the content of each of the spans (nickname, favorites, hometown) with your own information.
  • Iterate through each li and add a class of "listitem". Add a style tag that sets a rule for "listitem" to make the color red.
  • Create a new img element and set its src attribute to a picture of you. Append that element to the body.
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <title>About Me</title>
  <style>
    .listitem {
      color: red;
    }
  </style>
</head>
<body>
  <h1>About Me</h1>

  <ul>
    <li>Nickname:
      <span id="nickname"></span>
    </li>
    <li>Favorites:
      <span id="favorites"></span>
    </li>
    <li>Hometown:
      <span id="hometown"></span>
    </li>
   </ul>

  <script>
   document.body.style.fontFamily = 'Arial, sans-serif';
   document.getElementById('nickname').innerHTML = 'Ada Lovelace';
   document.getElementById('favorites').innerHTML = 'computers';
   document.getElementById('hometown').innerHTML = 'London, England';

   var items = document.getElementsByTagName('li');

   for (var i = 0; i < items.length; i++) {
      items[i].className = 'listitem';
   }

    var myPic = document.createElement('img');

    myPic.src = 'https://upload.wikimedia.org/wikipedia/commons/a/a4/Ada_Lovelace_portrait.jpg';

    document.body.appendChild(myPic);
  </script>
</body>
</html>

The Reading List Part II

  • Create a webpage with an h1 of "My Book List".
  • Add a script tag to the bottom of the page, where all your JavaScript will go.
  • Copy the array of books from the previous exercise.
  • Iterate through the array of books. For each book, create a p element with the book title and author and append it to the page.
  • Bonus: Use a ul and li to display the books.
  • Bonus: add a property to each book with the URL of the book cover, and add an img element for each book on the page.
  • Bonus: Change the style of the book depending on whether you have read it or not.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Book List</title>
  </head>
  <body>
    <h1>My Book List</h1>
    <script>
      var books = [
        {
          title: 'You Don'\t Know JS',
          author: 'Kyle Simpson',
          alreadyRead: false
        },
        {
          title: 'Eloquent JavaScript',
          author: 'Marijn Haverbeke',
          alreadyRead: true
        }
      ];

      for (var i = 0; i < books.length; i++) {
        var bookP = document.createElement('p');
        var bookDescription = document.createTextNode(books[i].title + ' by ' + books[i].author);

        bookP.appendChild(bookDescription);
        document.body.appendChild(bookP);
      }

      // Or, with the bonuses:
      var books = [
        {
          title: 'You Don'\t Know JS',
          author: 'Kyle Simpson',
          alreadyRead: false
        },
        {
          title: 'Eloquent JavaScript',
          author: 'Marijn Haverbeke',
          alreadyRead: true
        }
      ];

      var bookList = document.createElement('ul');

      for (var i = 0; i < books.length; i++) {
        var bookItem = document.createElement('li');
        var bookImg = document.createElement('img');

        bookImg.src = books[i].img;
        bookItem.appendChild(bookImg);

        var bookDescription = document.createTextNode(books[i].title + ' by ' + books[i].author);

        bookItem.appendChild(bookDescription);

        if (books[i].alreadyRead) {
          bookItem.style.color = 'grey';
        }

        bookList.appendChild(bookItem);
      }
      document.body.appendChild(bookList);
    </script>
  </body>
</html>

Challenge Question: The Counter

Write a function that takes a certain type of tag and counts the number of elements with that tag. The function should return "There a X tags of type y on the page. For example:

countTags('p'): 'There are 3 tags of type p on the page'
function countTags (tagType) {
  var tagArray = document.getElementsByTagName(tagType);

  console.log('There are ' + tagArray.length + ' tags of type ' + tagType + ' on the page.');
}