Forum Moderators: open

Message Too Old, No Replies

is there a difference between " and '

is there a difference between " and '

         

ltoso

6:29 am on Nov 4, 2009 (gmt 0)

10+ Year Member



Hi,
i am new to Java script, i want to know is there a difference between using ' and " when the javascript code gets executed as there is a difference betweeb ' and " in php.

Please help

Ltoso

Fotiman

2:04 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld! No, there is no difference, the opening and closing marks have to match though.
These are functionally identical:
var x = 'hello';
var x = "hello";

rocknbil

6:24 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you're coming to JS from PHP, the interpolation of variables is not the same.

$test = 'hello';

echo "$test"; // will echo hello
echo '$test'; // will echo $test

in Javascript,

var test = 'hello';
alert(test); // will alert hello
alert('test'); // will alert test
alert("test"); // will alert test

To include variables in strings, you must concatenate, with the + being the equivalent of PHP/Perl's . (dot) concatenation operator.

alert('The variable test is ' + test);
alert("The variable test is " + test);

When to use which is a matter of style, but it helps to reduce "toothpick syndrome" so you don't have to escape as much.

alert('Johnny\'s car ain\'t too fast, shouldn\'t it be faster?'); // can make more difficult to debug

alert("Johnny's car ain't too fast, shouldn't it be faster?");

When putting Javascript in PHP, beware of similar language escapes, particularly newlines, \n. These are the same in both languages. But if you do

echo "alert('Here we go \n');"; }

Your newlines will be escaped by PHP and your actual output will be

alert('Here we go
');

\n doesn't interpolate in PHP with single quotes, but the PHP statement is in double quotes, so the nested single-quote Javascript alert is just another character, allowing the \n to be interpolated by PHP. Confused yet? :-)

To maintain newlines in Javascript when generating it from PHP, escape the escape. :-)

echo "alert('Here we go \\n');"; }

[edited by: rocknbil at 6:35 pm (utc) on Nov. 4, 2009]

whoisgregg

6:33 pm on Nov 4, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Because I also work PHP and JavaScript constantly and often include html snippets in my javascript, I standardize on ' because you'll tend to have to escape your quotes less often:

var html = '<a href="#link"><img src="path" alt="alt" /></a>';

is less typing and cleaner than:

var html = "<a href=\"#link\"><img src=\"path\" alt=\"alt\" /></a>";

ltoso

12:52 pm on Nov 5, 2009 (gmt 0)

10+ Year Member



Hi,
i really liked this forum, never in any other forum i have got so much detailed responses and in so less a time.

Thanx Guys
Ltoso