-2

why doesn't document.write(added); work?

function first(){
    var now = new Date();
    var first=Math.round(now.getMilliseconds()/20);
    var second=Math.round(now.getMilliseconds()/30);
    var added=first+second;
    return added;
}
first();
document.write(added);
Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54
manticore46
  • 35
  • 1
  • 3

3 Answers3

0

because added is not a global variable, hence it is out of scope when you call document.write.

You need to save the returned value in a variable in the same scope in which you call document.write, i.e. global scope in this case. Correct code would be :

function first(){
var now = new Date();
var first=Math.round(now.getMilliseconds()/20);
var second=Math.round(now.getMilliseconds()/30);
var added=first+second;
return added;
}
var returnValue = first(); // store returned 'added' in returnValue
document.write(returnValue);
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0

Javascript has function scoping, which means that any variables declared in a function can't be accessed outside of that function. return added returns the value of added, not the variable added itself. If you want to use that value, you need to put it in a variable that was declared outside the function:

function first(){
    var now = new Date();
    var first=Math.round(now.getMilliseconds()/20);
    var second=Math.round(now.getMilliseconds()/30);
    var added=first+second;
    return added;
}
var firstResult = first();
document.write(firstResult);

More advanced, but related: Types of Javascript Variable Scope

Community
  • 1
  • 1
Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
0

Since the scope issue has already been pointed, I'm just gonna add another way to get result printed

document.write(first());
hex494D49
  • 9,109
  • 3
  • 38
  • 47