3

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:

  1. Build a function that will start the program. Please call it start()

  2. From the start() function, call a function called getValue()

  3. The getValue() function will get a number from the user that will be squared.

  4. Also from the start function, call a function called makeSquare()

  5. The makeSquare() function will square the number that was received by the user in the getValue() function.

  6. 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?

2
  • Accept an answer by clicking the check mark next to it. It helps a lot. Commented Oct 6, 2012 at 22:35
  • Math.pow() requires two parameters. Commented Oct 6, 2012 at 22:50

5 Answers 5

5

You were close. But it seems that you don't understand scoping and how exactly to use the pow function.

Math.pow:

Math.pow takes 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 value undefined and set it to b. This is how it should have looked (if you wanted to square it):

Math.pow(a, 2);

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:

var c = 5;

function foo() { // we have our own scope
   var a = c; // Okay
}

var b = a; // NOT okay. a is gone after the function exits.

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 return keyword. The expression next to it is the return-value of the function:

function foo() {
    return 5;
}

var a = foo(); // a === 5

foo() not only calls the function, but returns its return-value. A function with no return-value specified has a return value of undefined. Anyway, in your example you do this:

function getValue() {
    var a = prompt("Number please")
}

and access it like this:

// ...
var b = Math.pow(a)

Do you see the error now? a is 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):

function start() {
    getSquare();
}

function getValue() {

    var a = prompt("Number please");
    return a;
}

function getSquare() {

    var b = Math.pow(getValue(), 2); // getValue() -> a -> prompt(...)
    document.write(b);
}

start();
Sign up to request clarification or add additional context in comments.

3 Comments

Your revised code still isn't going to do much. The returned value isn't stored anywhere and you're still using locally scoped variables.
Mostly... now you're gonna prompt the user twice. :)
Thank you for the answer and everyone who helped David clean it up. Scoping was a unfamiliar reference to me. I also appreciate that being explained.
0

As this is an homerwork, I won't give you direct answer, but here's some clue.

In javascript variables are functions scoped. That mean that var a inside getValue is only available in there.

You can return a value from a function.

Functions are first class object in javascript, so you can pass them as parameter to other function and finally call them inside that function.

6 Comments

" That mean that var a inside getValue is only available in there." but only because the OP used the keyword var
"As this is an homerwork, I won't give you direct answer, but here's some clue." - I don't think "we" do this anymore after the deprecation of the homework tag. Just answer the question based on its merit. Besides, this question is asking for a conceptual explanation of what the problem is already, not merely the solution to the assignment, so you're being kind of deliberately obtuse.
"Functions are first class object in javascript" - this also has nothing to do with the subject of this question.
@millimoose The [homework] tag has nothing to do with it. It's not like without it someone has to give a full solution to a homework problem even if they would rather provide some hints instead.
@AnnaLear I understood the "spirit" of the rationale for the removal that there's no reason why homework questions should be treated any differently than any other question. While you're certainly free to give deliberately obtuse answers to questions for whichever reasons you choose, that will make them "bad" answers in my eyes. (They certainly would be for non-homework questions.) In this case, what specifically bugs me is the omission of example code merely because any example code would be a solution; even though the example code would illustrate the concepts involved.
|
0

Am I using variables in a way that can't be used?

Yes, that's where your problem lies. Variables in most programming languages have a scope that determines where they're available. In your case, a and b are local variables of the functions getValue() and makeSquare() respectively. This means they're not available outside the function they're declared in.

Generally speaking, this is a good thing. You should use restricted scopes for your variables to make the "flow" of data through your program clearer. Use return values and parameters to pass data between functions instead of making your variables global:

function start() {
    var a = getValue();
    makeSquare(a);
}

// Return a value entered by the user
function getValue() {
    return prompt("Number please")
}

// Write the square of the `a` parameter into the document
function makeSquare(a) {
    var b = Math.pow(a)
    document.write(b)
}

2 Comments

Although, this is not my favorite answer. This bit of code hits the assignment description dead on.
@user1725798 You can only accept one answer as the "best" one, but you can upvote as many as you wish if you found them useful. (Up to a certain daily vote limit.)
0
  1. Your getValue() needs to return the value, so that you then can pass it to the getSquare() function.

  2. In my opinion, you should always end each line with ;

  3. You will probably need to parse the user input into a number. For that you can use parseFloat(string).

  4. Math.pow takes two arguments, so to get the square, you would have to pass 2 as a second argument when calling it.

I edited your code with some clarifying comments:

function start() {
    // Catch the value returned by the function
    var value = getValue();
    // Pass the returned value to the square-function
    getSquare(value);
}

function getValue() {
    // Parse the user input into a number, and return it    
    return parseFloat(prompt("Number please"));
}

// Let the square-function take the user input as an argument
function getSquare(a) {  
    // Math.pow takes a second argument, which is a number that specifies a power
    var b = Math.pow(a, 2);
    document.write(b);
}

start();

Another, less good way

In JavaScript, variable-scoping is based on functions. If a variable is declared using the var keyword, it is only available to that function, and its child-functions. If it is declared without the var keyword, or declared outside any function, it becomes a global variable, which will be accessible by any code run on that page.

That said, you could get rid of the var keyword inside the getValue() function, which would make the variable a global. You could then access it from within getSquare() the way you tried in your example.

This is generally not a good idea though, since you would "pollute" the global namespace, and you would be running the risk that you accidentally have another script using a global variable with the same name, which would cause all kinds of trouble, when the scripts start to work with the same variable.

5 Comments

Many people would argue with you on 2. Semicolon insertion is an intentional feature of Javascript, there's not much reason to avoid it as a rule in unambiguous cases.
@millimoose It does say "you should", not "you must". I insert it anyways because of paranoia. I don't want future me yelling at past me after spending hours tracking down a bug, only to find out that past me thought it was clever to leave out a semicolon.
@millimoose I agree with NullUserException, better to be safe than sorry.
All I meant to point out is that this is a matter of opinion / convention. That is, the distinction between "must" and "should", which isn't necessarily obvious to people who don't speak fluent RFC2119.
@millimoose Change the wording somewhat, to make it a bit more clear.
0

You can try this.

<script type="type/javascript">
function start(){
makeSquare(getvalue());
}

function getvalue(){
return prompt("enter a number");
}

function makeSquare(a){
var result=Math.pow(a,2);
alert(result);
}
start();
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.