Siva Charan
Siva Charan

Reputation: 105

what is the difference between the following two in javascript?

I am assigning php values to javascript as following

var a = <?php echo 39; ?>

but javascript is throwing following error "Uncaught SyntaxError: Unexpected token ILLEGAL". When I am assigning php values in the following way then I am not getting any problem

var a = "<?php echo 39; ?>";

What I think is php code runs on server side first.So in the first case the php code is executed on server side first then that executed code is sent to the browser.So browser should see that code as(i think)

var a=39;

but instead of that it is throwing error.Why is it happening?

Upvotes: 1

Views: 74

Answers (2)

beingalex
beingalex

Reputation: 2476

First of all, it's best practice to always end your statements with a semicolon. But regardless of the discussion in the other answers about where and when you should have one, there is also another very important difference in the two examples you have provided.

Example 1:

var a = <?php echo 39; ?>

Variable a is now an integer (no quotes): http://en.wikipedia.org/wiki/Integer_%28computer_science%29

Example 2:

var a = "<?php echo 39; ?>";

Variable a is now a string (quotes): http://en.wikipedia.org/wiki/String_%28computer_science%29

I would say that the different between variable types is something you should be aware of. Especially in Javascript!

Upvotes: 0

Steve
Steve

Reputation: 20469

Your 1st example misses the semicolon off the end of the javascript variable assignment:

var a = <?php echo 39; ?>; //<-- missing semicolon

Upvotes: 3

Related Questions