Modaresi
Modaresi

Reputation: 233

document.write & return function

I know HTML fairly well but when it gets to JavaScript I am a complete newbie. Anyway, below is a function that I have created and works just fine.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    function myFunction(yourName) {
        document.write ("Hello" + " " + yourName + " " + "Welcome aboard");
    }
</script>
</head>
<body>
<script type="text/javascript">
    myFunction("David");
</script>
</body>
</html>

Now, how come when I change document.write to return it doesn't work? It says undefined. Let me show you what I mean.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    function myFunction(yourName) {
        return ("Hello" + " " + yourName + " " + "Welcome aboard");
    }
</script>
</head>
<body>
<script type="text/javascript">
    document.write(myFunction())
</script>
<script type="text/javascript">
    myFunction("David");
</script>
</body>
</html>

Also, I'd like to declare a variable named msg, that gets the return value of calling the function myFunction. How do I do that?

Upvotes: 0

Views: 3146

Answers (2)

suneetha
suneetha

Reputation: 827

First, it executes this

<script type="text/javascript">
  document.write(myFunction())
</script>

Here you are not passing any parameter.So, yourname is undefined.

In the next snippet:

 <script type="text/javascript">
   myFunction("David");
 </script>

you are passing the value, but you are not displaying it. So, again it is undefined.

code: http://jsfiddle.net/VvdWU/4/

Upvotes: 1

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

You forgot to pass a parameter, like:

document.write(myFunction("David"))

Working example: http://plnkr.co/edit/xsaNe00gGgG0Aa2tsM7a?p=preview

Upvotes: 1

Related Questions