JavaScript AJAX Basics (retiring) AJAX and APIs Displaying the Photos

What did we do here?

photoHTML += '<a href = "' + photo.link +'" class = "image">';

I don't understand why we needed to concatenate (I don't even see the concatenation there, I'm just repeating what Dave said in the video).

It's really starting to annoy me that these kind of details are not been explained.

1 Answer

Steven Parker
Steven Parker
182,492 Points

When used with strings, the "+" symbol is the concatenation operator. So that explains where the concatenation is occurring in the example.

The reason for concatenation is to combine all those parts into a single string, which is then added onto the current contents of "photoHTML".

I know that. What I'm trying to say is:

1- There's nothing before "photo.link" nor after it. What is it concatenating then? The href attribute is expecting a link, which is contained in the photo.link object property. Why couldn't we just write: "<a href = photo.link> </a>" ?

2- Why did we need to add an apostrophe before and after the photo.link object property? Instead of typing "<a href = photo.link> </a>" we typed "<a href = " ' + photo.link + ' "> </a>"

Steven Parker
Steven Parker
182,492 Points
  1. If you use <a href=photo.link> then the HTML link will point to a file named "photo.link" which most likely does not exist. You want to the link to point to the URL that is contained in the "link" property of the "photo" object.
  2. The apostrophes are enclosing strings that have double quotes inside of them. It might be easier to see in formatted code with syntax coloring:
photoHTML += '<a href="' + photo.link + '" class="image">';

So we basically need to enclose the object's property between the apostrophes in order for the attribute to read it as an external URL instead of an internal URL. The only thing that I still don't understand is the alleged concatenation. Thank you for the awesome help!

Steven Parker
Steven Parker
182,492 Points

Concatenation is just sticking things together. That's what the + symbol does.

So "Happy " + "coding!" would be: "Happy coding!".

And with var item = "car'; then "My " + item + " is blue." would be: "My car is blue."