Practice Set - Basic Math and String Operations
by DustyWhite
HTML
<h3>Basic Math and String Operations</h3>
<b>From Larry: SOLUTION SET, Practice Set 3.1</b>
<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
// Could assign two numbers to variables and then
// add them in the console.log statement
var a = 5;
var b = 6;
console.log(a+b); // 11
// or add them and then output them
var c = a + b;
console.log(c); // 11
// Also could do this
console.log(5 + 6); // 11
//***********************************************
// Insert your code for #2 here
// Increment in the output statement
var num = prompt("Enter a number!");
console.log(++num); // num + 1
/* Note that the increment operator can go before or after the variable (num++ or ++num), but only the 'before' option will get us the desired result here. The difference is that if you put it before the variable name it's a PRE-increment. That is, the increment will happen before the rest of the line of code is executed. If you put it after the variable name, it's a POST-increment, and the increment happens AFTER the line of code is executed. So if you used num++, the console would output the original number, but if you checked it again on the NEXT line, the number would have incremented.
*/
// Insert your code for #3 here
console.log("To square the number 8, we use Math.pow(8, 2) and get "+ Math.pow(8,2)); // 64
// Insert your code for #4 here
var input = prompt("Enter a string and I'll tell you how long it is");
console.log("The string's length is "+input.length);