Get Programming with JavaScript - Listing 5.05
Listing 5.05 - Using the square function
JS Bin
var square;
square = function (numberToSquare) {
var result;
result = numberToSquare * numberToSquare;
console.log(numberToSquare + " * " + numberToSquare + " = " + result);
};
square(10);
square(-2);
square(1111);
square(0.5);
Further Adventures
Listing 5.05 - Using the square function - Tasks 1 & 2
- Define a cube function that cubes any number passed in as an argument.
- Call your cube function four times with different arguments to test it.
var square;
var cube; // Declare a variable
square = function (numberToSquare) {
var result;
result = numberToSquare * numberToSquare;
console.log(numberToSquare + " * " + numberToSquare + " = " + result);
};
// Define a new function
// Assign it to the cube variable
cube = function (numberToCube) {
var result;
result = numberToCube * numberToCube * numberToCube;
console.log(numberToCube + " cubed = " + result);
};
square(10);
square(-2);
square(1111);
square(0.5);
// Call the function
cube(2);
cube(-2);
cube(10);
cube(0.5);
Listing 5.05 - Using the square function - Task 3
- Define and test a squareRoot function to find square roots and display them on the console.
var square;
var cube;
var squareRoot; // Declare a variable
square = function (numberToSquare) {
var result;
result = numberToSquare * numberToSquare;
console.log(numberToSquare + " * " + numberToSquare + " = " + result);
};
cube = function (numberToCube) {
var result;
result = numberToCube * numberToCube * numberToCube;
console.log(numberToCube + " cubed = " + result);
};
// Define and assign a function
squareRoot = function (numberToRoot) {
var result;
result = Math.sqrt(numberToRoot);
console.log("The square root of " + numberToRoot + " is " + result);
};
square(10);
square(-2);
square(1111);
square(0.5);
cube(2);
cube(-2);
cube(10);
cube(0.5);
// Test the function
squareRoot(9);
squareRoot(100);
squareRoot(2);
squareRoot(0.25);