0

Very new to JS here. When I write PHP I have no problem assigning variables inside a function, but inside a JavaScript function it doesn't work. Why?

example:

function hello() {

var animal = 'Dog';
document.write(animal);

}
2
  • 6
    Why doesn't it work? ... What happens? Commented Aug 2, 2010 at 0:54
  • Define "doesn't work". The variable assignment should work fine. Commented Aug 2, 2010 at 0:55

2 Answers 2

7

Are you calling the hello() function anywhere? If not, you will not execute the contents of the function and thus, no write will happen.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried the same code on a new page and it worked fine, something on the other page must have been interfering.
1

put this snippet inside your function to check if your function is being called

alert('snippet');

If a message box appears, your code should work, but if it does not then the function is not being executed, post some html coding also.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.