Practice Set - Basic Math and String Operations

by Ken Sprague

HTML

<h3>Basic Math and String Operations</h3>
<h4>4 Tasks for this Practice Set:</h4>
<ol>
    <li>
        Write a script to add two numbers and output the sum to the console</li><li>
    Write a script that prompts for input, adds one to whatever number was input and outputs the sum to the console. Use the increment operator.  Assume that the input will be a number (no type-checking is required for this exercise).
    </li><li>
    Look up the Math object, and use one of its methods to do <i>something</i> to a number and output the result to the console (you pick: square it, round a decimal number up or down, do a trig function...whatever) Make sure the you comment your code or use console output to describe what you’re doing.
</li><li>
    Prompt for input and assign the result to a variable. Then, look up the String object, and use one of its properties to output the length of the string variable to the console.
    </li>
</ol>

JavaScript

// Insert your code for #1 here
// declare and set my variables
var collectibleCost = 120;
var professionalCost = 27;
//do some addition and assign the result to a new variable
var totalCost = collectibleCost + professionalCost;
//output that result
console.log("The total cost of this collectible is $" + totalCost);


// Insert your code for #2 here
// this is my prompt
var cost = prompt("Enter today's value of the collectible:"); 
//make the variable into a number so we can do math on it
cost = parseInt(cost);
//cost with additional fee
cost = cost + 1;
//output that result
console.log("After fees it will worth $" + cost);


// Insert your code for #3 here
//finding the sq root of a given number
var x = Math.sqrt(16);
//output that result
console.log("The square root of 16 is " + x);


// Insert your code for #4 here
//this is my prompt
var favoriteHero = prompt("Who is your hero?");
//convert answer to string
favoriteHero = String(favoriteHero);
//assigning the result to a variable
favoriteHero = favoriteHero + ", but nobody has better tools than Batman.";
//output that result
console.log("Your hero might be " + favoriteHero);
console.log(favoriteHero.length);