Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need the + between variables in javascript?

Why does this line work

$('#body-image').css("background-image", 'url('+ backgroundimage +')');

but not this one

$('#body-image').css("background-image", 'url('backgroundimage')');

or this one

$('#body-image').css("background-image", 'url(backgroundimage)');
like image 577
Chamilyan Avatar asked Aug 04 '26 06:08

Chamilyan


2 Answers

backgroundimage is a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string together with a variable, you do 'some string ' + someVariable. Without the +'s, JavaScript wouldn't know what to do with your variable (and in your third example, wouldn't even know that it was a variable).

like image 176
catgofire Avatar answered Aug 05 '26 20:08

catgofire


You need to concat the string with the variable backgroundimage. So you use "+" for this.

That's why this doesn't work.

$('#body-image').css("background-image", 'url('backgroundimage')');

And the secont doesn't work because there is no image called 'backgroundimage'.

$('#body-image').css("background-image", 'url(backgroundimage)');
like image 22
Topera Avatar answered Aug 05 '26 19:08

Topera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!