Why do you need + between variables in javascript?

Why does this line work

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

but not this

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

or this

$('#body-image').css("background-image", 'url(backgroundimage)');
+3
source share
5 answers

backgroundimageis a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string along with a variable, you do 'some string ' + someVariable. Without the “+”, JavaScript would not know what to do with your variable (and in your third example, you wouldn't even know that it is a variable).

+7
source

You need to combine the string with a variable backgroundimage. Thus, you use "+" for this.

That is why it does not work.

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

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

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

. , backgroundimage :

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

:

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

. , backgroundimage is foo.jpg,

'url('+backgroundimage+')'  =  'url(foo.jpg)'
0

JavaScript (.. " - " ) String (, , : . MDC - ). :

var letters = "ABC", numbers = "123";
var letters = new String("ABC"), numbers = new String("123");

+, String.concat, 2 . , "ABC123", :

"ABC" + "123"
"ABC" + numbers
letters + "123"
letters + numbers
"ABC".concat("123")
"ABC".concat(numbers)
letters.concat("123")
letters.concat(numbers)

:

letters"123"
"ABC"numbers
lettersnumbers
"lettersnumbers"

, , , .

0

Source: https://habr.com/ru/post/1764966/


All Articles