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 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Dec 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Unhappy Problems with functions and variables

    Hey, I've just started coding and i need help. Can anyone tell me whats wrong with these lines of codes please?

    [CODE]
    var multiplied;

    var timesTwo = function(number) {

    var multiplied = number * 2;
    };

    timesTwo(4);

    console.log (multiplied);
    [CODE]

    It doesnt print out the value of multiplied, instead it says that it is undefined. What have i done wrong?

  • #2
    Regular Coder
    Join Date
    Jul 2012
    Location
    London
    Posts
    473
    Thanks
    4
    Thanked 86 Times in 86 Posts
    What do you want to do?

    Multiple two numbers?

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts

    Lightbulb

    Quote Originally Posted by jhispro97 View Post
    Hey, I've just started coding and i need help. Can anyone tell me whats wrong with these lines of codes please?

    Code:
    var multiplied;
    
    var timesTwo = function(number) {
        
        var multiplied = number * 2;
        };
    
    timesTwo(4);
    
    console.log (multiplied);
    It doesnt print out the value of multiplied, instead it says that it is undefined. What have i done wrong?
    You have two versions of the variable 'multiplied'.
    One is local and will work fine if displayed within the function.
    However, you are not doing that.

    The second version of 'multiplied' is a global varible and is unassigned.
    This is the one you are trying to display in the console log.

    BTW, you second [ code] tag should have a /code to display properly.

  • Users who have thanked jmrker for this post:

    jhispro97 (12-31-2012)

  • #4
    New to the CF scene
    Join Date
    Dec 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Smile

    Oh. I realized it now. Thanks for helping out btw. And sorry for the misusing of the [ code] tag.

  • #5
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts
    You're most welcome.
    Happy to help.
    Good luck!


  •  

    Tags for this Thread

    Posting Permissions

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