JavaScript Puzzles

Welcome! These are some bonus puzzles to accompany 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: city or place, job title, home, and hobby.
  • Output your fortune to the screen like so: "You will be a _job_ living in a _home_ in _city or place_. For fun you will _hobby_."

var jobTitle = 'web developer';
var home = 'sprawling beachfront treehouse';
var place = 'Costa Rica';
var hobby = 'play Scrabble';

var future = 'You will be a ' + jobTitle + ' living in a ' + home + ' in ' + place + '. For fun you will ' + hobby + '.'
console.log(future);
                


Back to top

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);
                


Back to top

Challenge Questions: 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 string1.slice(0, 2) + string2.slice(2) + " " + string2.slice(0, 2) + string1.slice(2);
}
                

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'), '*');
}
                


Back to top

What number is bigger?

Write a function that compares two numbers and returns the larger one. Be sure to try it our 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');
        return num1;
    } 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'));
                


Back to top

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 cats'
            

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'));
                


Back to top

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');
    }
}
                


Back to top

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.


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

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

Class 2

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: 'The Design of EveryDay Things',
   author: 'Don Norman',
   alreadyRead: false
  },
  {title: 'The Most Human Human',
  author: 'Brian Christian',
  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);
  }
}
                


Back to top

  • 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)
  • Find the Google search button and store it in a variable.
  • Modify the text of the button so that it says "Yahooo!" instead.

var img = document.getElementById('hplogo');
img.width = 400;
img.src = 'http://www.logostage.com/logos/yahoo.GIF';
var button = document.getElementById('gbqfba');
button.innerHTML = 'Yahoooo!';
                


Back to top

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 JS 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: 'The Design of EveryDay Things',
   author: 'Don Norman',
   alreadyRead: false
  },
  {title: 'The Most Human Human',
   author: 'Brian Christian',
   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: 'The Design of EveryDay Things',
   img: 'http://ecx.images-amazon.com/images/I/41j2ODGkJDL._AA115_.jpg',
   author: 'Don Norman',
   alreadyRead: false
  },
  {title: 'The Most Human Human',
   img: 'http://ecx.images-amazon.com/images/I/41Z56GwEv9L._AA115_.jpg',
   author: 'Brian Christian',
   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>
                


Back to top

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.');
}
                


Back to top