Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2013
    Posts
    79
    Thanks
    45
    Thanked 0 Times in 0 Posts

    javascript adding two numbers problem

    please explain what i did wrong
    it doesn't seem to be working as expected
    http://jsfiddle.net/ACcGC/

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,479
    Thanks
    6
    Thanked 981 Times in 954 Posts
    I’m getting the message
    document.write is disallowed in JSFiddle envioriment and might break your fiddle.

  • #3
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    10,966
    Thanks
    0
    Thanked 236 Times in 233 Posts
    Why do you have a line after the return statement? When a return statement is executed, it will immediately exit the function and return the value to the caller.

    I think this is what you need:

    http://jsfiddle.net/ACcGC/3/

    The function can be improved such that you can pass any number of parameters to add.

    Code:
    function total(){
        var sum = 0;
        for (var i=0; i<arguments.length; i++) {
            sum += Number(arguments[i]); 
        }
        return sum || 0;
    }
    
    total(); //returns 0
    total(1); //returns 1
    total(1, 2); //returns 3
    total(1, 2, 3); //returns 6
    total(1, 2, 3, 4); //returns 10
    Btw, using prompt to accept user input is not the preferred way anymore. Use a regular form instead.

  • Users who have thanked glenngv for this post:

    h123er2 (10-01-2013)

  • #4
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    First, you're returning the function before it gets to display the value.

    Second, as stated above, you can't use document.write() in jsFiddle.

    Third, you're using global variables and that's messing up your function parameters with the same name. num1 and num2 are actually 'undefined' in your total() function.

    Fourth, you're not calling total() with any value. You need to pass the values into the function.

    Fifth (and final), you're not adding the numbers. prompt() returns a string, not a number. You're actually concatenating the input (making a string combining the 2 inputs, so if you enter 5 and 4, the result will be 54, not 9).

    Check this out: http://jsfiddle.net/ACcGC/4/

  • Users who have thanked joesimmons for this post:

    h123er2 (10-01-2013)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •