Javascript Bytes (8): Number of seconds alive


This is a function to calculate the amount of seconds you are alive.

function secondsAlive(age) {
var secondsPerDay = 60 * 60 * 24;

var yearsAlive = age;

var secondsAlive = 365 * secondsPerDay * yearsAlive;

return secondsAlive;



Javascript Bytes (7): Number of seconds till midnight

We want to make a function that takes in two integers as arguments and returns the amount of seconds left in the day.


function secondsTillMidnight(hour, minute) {

var minToSec = minute * 60;
var hoursToSec = hour * 60 * 60;
var midnight = 60 * 60 * 24;

return midnight – (minToSec + hoursToSec);


secondsTillMidnight(9, 21);

Javascript Bytes (7): Max of three

Here we create a function that takes in three number arguments, and then we tell the function to return the biggest of the three numbers.


function maxOfThree(intOne, intTwo, intThree) {

if (intOne > intTwo && intOne > intThree) {
return intOne;
} else if (intTwo > intThree) {
return intTwo;
} else {
return intThree;



Javascript Bytes (7): Comparing last digits

We make a function to find the last digit of two non-negative integers, and compare to see if the last two digits match. If they do, the function returns true, else, the function returns false.

function lastDigit(intOne, intTwo) {

//we needed to convert to string in order to use the slice method
//to find the last substring of our number
var lastDigitOne = intOne.toString().slice(-1);
var lastDigitTwo = intTwo.toString().slice(-1);

if (lastDigitOne === lastDigitTwo) {
return true;
} else {
return false;

lastDigit(22, 32);

Javascript Bytes (6): Asking Politely

Create a function that checks to see if the argument string contains a question mark. If it does, make sure that the question ends with a “please?”. In all other scenarios, simply return the original argument.


function askPolitely(question) {

//find the last char of the string
var lastChar = question.slice(-1);

if (lastChar === “?”) {
if (question.indexOf(“please”) > -1) {
return question;

} else if (question.indexOf(“please”) === -1) {
return question.substring(0, question.length – 1) + ” please?”;

} else {
return question;


console.log(askPolitely(“May I ask a question?”));

Javascript Bytes (5): First letter of name

Let’s check to see if the first letter of the string is “S” or “s”, then control the flow of the function accordingly.


function doYouPlayTheTheremin(name) {
var nameArray = name.split(“”);

for (var i = 0; i < nameArray.length; i++) {
if (nameArray[i] === “S” || nameArray[i] === “s”) {

return name + ” plays the Theremin!”;

} else {

return name + ” does not play the Theremin!”;



return nameArray;



Javascript Bytes (4): A Vending Machine

//function for vending machine
var vendingMachine = (function() {
//make items inside the vending machine
//return this.label is telling js to return only the label property of the object instead
//of the entire thing
var items = [
{ id: ‘001’, label: “Snickers”, price: 1.00, toString: function() {return this.label } },
{ id: ‘002’, label: “M&Ms”, price: 1.50, toString: function() {return this.label } },
{ id: ‘003’, label: “Amstel Light”, price: 3.00, function() {return this.label} }


//return the float to a fixed decimal point
var toMoney = function(value) {
return ‘$’ + value.toFixed(2);


//a function to vend the item
var vend = function(money, id) {
//verify money is greater than or equal to the price of the cheapest item
//verify the item exists
var item = findItem(id);
var msg, item_or_refund;
//check docu for toFixed()
//function orientated programming
if (toMoney(money) >= toMoney(item.price)) {
msg = ‘Vended ‘ + item.label + ‘ for ‘ + toMoney(item.price).toString() + ‘.’;
item_or_refund = item;

} else {
msg = “Sorry, not enough funds!”;
item_or_refund = toMoney(money).toString();

return item_or_refund;

//takes an id and return the result of an item’s filter – go over each item, does your id match the one we want? toss it till we find a match

//function to find the right item
var findItem = function(id){
return items.filter(function(item) {
return id.toString() ===;



//shows all the items
var menu = function() {
items.forEach(function(item) {
console.log( + “: ” + item.label);


//exits main function, vends the item
//must return all the subfunctions
return {
vend: vend,
menu: menu,
toMoney: toMoney



Refactoring code in functions

Creating functions is similar to creating mini factories that are independent and self-sufficient. The good functions do not require global variables to use, and are extremely modular and easy to debug.

Let’s take the guessing numbers game that we made previously. If we had to turn the random number generator into a function, how would we do it?

If we wanted to write a function that could take in two numbers as parameters and return a random value between the two numbers, here’s how we would go about doing it:

function getRandomNumber (lower, upper) {

var randomNumber = Math.floor(Math.random() * (upper – lower + 1)) + lower;

return randomNumber;


In fact, we can make this code even more compact:

function getRandomNumber (lower, upper) {

return Math.floor(Math.random() * (upper – lower + 1)) + lower;


We can even put safeguards on this function so that it checks to see if the parameters are actually numbers. You wouldn’t want someone trying to put in strings or other characters.

function getRandomNumber (lower, upper) {

if (isNaN(lower) || isNaN(upper)) {

throw new Error(“Both arguments must be numbers!”);

} else {

return Math.floor(Math.random() * (upper – lower + 1)) + lower;



Now that we have this function, we can use it wherever in our code to calculate any form on random numbers by simply calling it:

randomNumber(1, 20);

To show the modular power of functions, we can create callbacks – or calling a function within a function. The logic is quite easy once we grasp it. What if we wanted to created a function that checks whether a random number is greater than or equal to a given number? We could reuse our getRandomNumber function above, and call it in our new function. Here’s how we would go about doing it:

function compareRandomNumberSizeTo (number) {

var randomNumber = randomNumber(1, 20);

if (randomNumber < number) {

return “The you chose is greater than the number generated”;

} else {

return “The number you chose is less than the number generated”;



Now, you can call this function in an alert.


Callbacks are a major part of most programming languages, and this is the reason why it is crucial to create clean, modular code using functional programming. Think of it as individual factories that churn out information to be used in other individual factories. If each factory is constructed with good code, and is independent of other factories, we can create modular pieces of code that are reusable and easier to debug.

Javascript Bytes (3): Capitalize Each String

A simple but effective coding challenge to practice Javascript syntax!

Problem: Write a function that will capitalize the first letter of each word in a sentence.

var string = “this is my sentence”;

First, we need to make an array out of this sentence in order to parse through it and find the beginning of each word (which is at index 0).

We use the split string method to separate each word in the array by the spaces in the original string.

var stringArray = string.split(” “);

Now, stringArray should look like this:

[“this”, “is”, “my”, “sentence”];

Sweet! We can now utilize the power of arrays to solve our problem! Now, to find the beginning letter of each word, we need to access each substring of the string. Once we have access to each substring, we need to split that word apart and change the correct letter to solve the problem. In our case, the problem is asking for the beginning letter of each word to be capitalized. Since we need to capitalize the first letter of each word, we will need to use a loop.

function capitalizeWord(string) {

var stringArray = string.split(” “);
//potential bug, create stringLength as a variable
var stringLong = stringArray.length;
//empty array
var array = [];

for (var i = 0; i < stringLong; i++) {

var newArray = stringArray[i];
var capitalizedLetter = newArray.substring(0, 1).toUpperCase() + newArray.substring(1);


//format the joined array into string
return array.join(” “);


capitalizeWord(“hello world, how are you today?”);

As we see above, before we return the modified array, we need to join it back into a string. So, we utilize the join method in order to achieve this.





JavaScript Bytes (2): Guess The Number!

Our last byte post was building a very, very basic number generator. However, there were a few problems with it. There were no conditionals to check if certain types of values could be entered or not. How can we make it so that the program deals with users who decide to input a letter instead of a number?

We can also extend our program to make it a little more responsive. We do this through the use of conditionals and booleans. These are powerful syntax that all programming languages share, and they allow the code to make decisions based on what the user has decided to input.

Let’s build another random number generator from scratch. This time around, we’re going to make a little numbers guessing game. The user guesses a random value between 1 and 6. If they is correct, they wins the game. If not, they gets one hint before losing on a third try.

First, every random number generator needs its engine. We also need a place for the little random number to be stored:

var randomNumber = Math.floor(Math.random() * 6 – 1) + 1;

Next, we need a prompt asking the user for their initial guess:

var guess = prompt(“I’m thinking of a random number between 1 and 6. What is it?”);

Now, we need to do something with the user’s answer! First, let’s create a boolean value that is initially set to false, but will change depending on the users answer:

var correctGuess = false;

Since the user may decide to play rough and enter a letter instead of a number, we need to safe guard against that. To do this, we need to use the equality operation to make sure that the input being passed in variable guess is of the same type and the same number:


if (parseInt(guess) === randomNumber ) {

     correctGuess = true;


So we’ve established the basic logic. If the user inputs the right number, the boolean value becomes true! Now we simply have to utilize this boolean logic within our conditionals and create a little game out of it!

if(parseInt(guess) === randomNumber ) {

     correctGuess = true;

} else if (parseInt(guess) < randomNumber) {

     var guessMore = prompt(“Try again. The number I am thinking of is more than ” + guess);

               if(parseInt(guessMore) === randomNumber) {

               correctGuess = true;


} else if (parseInt(guess) > randomNumber) {

     var guessLess = prompt(“Try again. The number I am thinking of is more than ” + guess);

               if(parseInt(guessLess) === randomNumber){

               correctGuess = true;



That was the meat of our code. The syntax is very friendly even to non programmers. We are basically setting a series of conditionals checking if the input number is greater than or less than the actual generated random number. If they are, we tell the user to guess again with a prompt. If the user guesses correctly, they win the game.

What happens if a user fails to guess two times? We need them to lose! Let’s implement this:

if ( correctGuess ) {

          document.write(‘<p>You guessed the number!</p>’);

} else {

          document.write(‘<p>Sorry! The random number was ‘ + randomNumber + ‘ .</p>’);


Self explanatory. If the user wins, we print that to the webpage. If they lose, we tell them what the actual number was.