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> 
<script>
    var years;
    var time;
    toDays(21);
    function toDays(years) {
        time = 365 * years;
    }
    document.write("My age is " + time);
</script>

no global variables neccesary

<script>

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

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).

@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.

@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. :)

@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 :))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.