I’m new to the Javascript world and trying to figure out this assignment my teacher assigned. Here is his description of what is expected:
-
Build a function that will start the program. Please call it start()
-
From the start() function, call a function called getValue()
-
The getValue() function will get a number from the user that will be squared.
-
Also from the start function, call a function called makeSquare()
-
The makeSquare() function will square the number that was received by the user in the getValue() function.
-
Make sure that you display the results of squaring the number inside of the makeSquare() function.
Here is what I have so far:
function start() {
getValue();
getSquare();
}
function getValue() {
var a = prompt("Number please")
}
function getSquare() {
var b = Math.pow(a)
document.write(b)
}
start()
This assignment doesn’t have to be working with any HTML tags. I’ve only got the prompt box to work, nothing else does though. Am I using variables in a way that can’t be used?
You were close. But it seems that you don’t understand scoping and how exactly to use the
powfunction.Math.pow:
Math.powtakes two parameters, the base and the exponent. In your example, you only provide the base. That will cause problems as the function will return the valueundefinedand set it tob. This is how it should have looked (if you wanted to square it):Scoping:
Every function has it’s own scope. You can access other variables and functions created outside the function from within the function. But you cannot access functions and variables created inside another function. Take the following example:
We could say that a function is private. The only exception is that we can return a value from a function. We return values using the
returnkeyword. The expression next to it is the return-value of the function:foo()not only calls the function, but returns its return-value. A function with no return-value specified has a return value ofundefined. Anyway, in your example you do this:and access it like this:
Do you see the error now?
ais defined in the function, so it can’t be accessed outside of it.This should be the revised code (Note: always use semicolons. I included them in for you where necessary):