August 2, 2010

Why can't I assign a variable inside a function in Javascript?

Question by Clark

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

}

Answer by DVK

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

Answer by Starx

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!