0

Hi, I'm trying to find out why my code won't run. I passed my years variable to the function to multiplied by 365 and stored in my time variable which should be printed out. Should "toDays(21)" be declared in my function instead?

<!DOCTYPE html>
<html>
<head>
<script>
    var years; 
    toDays(21);

    function toDays(years)
    {
        var time;
        time = 365*years;
        return time;
    }      

    document.write("My age is " + time.value-0);
</script>
</head>
<body>

</body>
</html> 
4
Contributors
6
Replies
7
Views
5 Years
Discussion Span
Last Post by theHop
0
<script>
    var years;
    var time;
    toDays(21);
    function toDays(years) {
        time = 365 * years;
    }
    document.write("My age is " + time);
</script>
1

no global variables neccesary

<script>

    function toDays(years) {
       var time = 365 * years;
       return time;
    }
    document.write("My age is " + toDays(21));
</script>
Votes + Comments
Good example
1

You have a problem understanding scope of variables.

Line 6, you call the function (lines 8~13) to compute the value of time. The function return a proper value but you did not store the value in any variable. Then, line 15, you attempt to use variable time which is not declared anywhere but inside the function (so it could be seen only in the function). Even worse, you attempt to access value property from the non-declared variable. As a result, it won't work.

You could follow theHop method but you could simply do function toDays(years) { return (years*365); } if you are sure that the variable years will correctly be passed into the function (must only be a number or float, no string).

0

@Taywin I played with returning the raw output but decided to put it in a variable to make it easier to read for @izic. I think he maybe only just be learning javascript.

0

@theHop, less is more :) I just point out where the problems are. I gave a shorter version of yours and I believe it is more intuitive because the function does not really need a local variable but simply returns the result value. Nothing against your post. :)

0

@Taywin no worries...thats why I gave you an up vote. :). If it was for my own program I wouldn't have used a local variable either.

(I don't mind if you give me an up vote too :))

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.