Why would we use string concatenation?

I have worked past this part into more of the JS fundamentals, but I am still unsure as to why it would ever be necessary to use string concatenation. Why would one need to append one string to another instead of simply writing it as one string?

8 Likes

Whats the point of string concatenation? utilizing a strings natural white space is enough to produce the same result. Whats the point?

1 Like

We cannot expect the same behavior in the browser as we get in the console. They are two entirely different namespaces.

console.log('string', a_variable, 'more string', b_variable, 'more string.')

All the components in that argument list will display space separated on a single line. That is the behavior of the console. It is not the same when we are generating HTML and textContent for the browser. For this we need to construct the string into a single form (most likely) and give it to the DOM to insert.

The ES5 way of string interpolation has always been concatenation or array joining. It is good to understand both, even if the former is less used in ES6. Everything still works as expected.

ES6 gave us template literals that permit expression interpolation, multi-line strings, and textual and punctuation information all sewn into a single value.

 > {
   let str = `sentence`;
   let umpteen = 3;
   let values = true;
   let eg = `This ${str} contains ${umpteen} variables
   having ${values ? `some`: `no`} value worth noting.`
   console.log(eg);
   }
This sentence contains 3 variables 
having some value worth noting.
<- undefined
 > 
7 Likes

Notice the example console.log('I love to ’ + ‘code.’)
Why can’t I just use console.log(‘I love to code.’)
It’s a simplified code. Can’t the platform detect simple spaces between these 4 words? Why the need, in this instance, for the + sign?
Is Javascript that primitive that it can’t detect simple spaces between words? Even the most basic word processor can do this.

1 Like

For the purpose of demonstration. It shows how two string objects can be joined (concatenated). Clearly, we would not do this with literals in production code, but would use the technique when working with dynamic data (non-literal) that arises in the program.

first = prompt("First Name: ")
last = prompt("Last Name: ")
console.log("Hello, " + first + " " + last + ".")

JS is moving away from concatenation in favor of Template Literals that permit variable interpolation. Above is a form of interpolation but a technical pain in the butt.

console.log(`Hello, ${first} ${last}.`)

Note the use of the special character,

`

The back-tick is usually found at the far left end of the number key row on an American standard keyboard.

13 Likes

I still don’t understand why this is being used as an example in the tutorial. I can’t get past the lesson because I don’t understand how to write this stuff? Why can’t it just be one statemnt or whatever it’s called?

1 Like

We can very well write plain sentences (prose) but what if part of the sentence is meant to be user changeable? Anything our program gets from the user is going to be data that is referenced with a variable. This introduces a dynamic environment that our program has to deal with.

noun1 = 'sky'
noun2 = 'limit'
str = "The " + noun1 + " is the " + noun2 + "!"

We can write that into a re-usable block of code called a function, which will soon come up in the lessons. If you care to get a sneak peek, just ping this topic.

10 Likes

Thank you for the reply. When I try that code it says : Did you concatenate the strings 'Hello' and 'World' within a console.log() statement? I don’t understand what that means either.

what does this mean?
also what is a ping?

Okay, now I see… We are given two literal string primitives that we are asked to concatenate and log.

console.log("Hello" + "World")

which will log,

HelloWorld

I was able to run ````
console.log(“Hello” + “World”) ` But it just says the two words together… I don’t get it. How do I concatenate (i can’t pronounce that word) something? Is it like a terminal command ?

Anything we can program as a statement we can enter as a terminal command, but that’s not the connection we’re looking for here. It relates to a string operation.

kuh kah' teh NAY shun

where the apostrophe means, accent that syllable. We get a feel for the rhythm of the syllables when combined as a whole.

Notice what happened when we concatenated a space character between the two words?

Hello World

We literally inserted the space to separate the two words. We are attaching objects, and yielding a single string value. When the objects are dynamic (variables) this is called, string interpolation in its most primitive form. Other methods will emerge in due course.

I don’t know what a statement is but I’ve ruined at least one mac trying to learn the terminal command. Do I need to learn that for JavaScript? I was able to get a space between Hello World but I just followed the example until it worked. I just made a literal space between the ’ ’ quotes. Should I have attached an object?

1 Like

In the context or focus of computer programming a statement is a single line of code no matter it’s length. The word concatenate means to join things together in a chain or series ok. Don’t over think these lessons! the point of the lesson is to learn that you can join together 2 things whether it’s some text or numbers to create one thing that is the sum result of the 2 things. We need to add in a space for joining the 2 words “Hello” and “World” like "Hello “, “World” or “Hello”, " World” because the language(JavaScript)literally combines the contents of the 2 strings into a single string and adding in the space makes it conform to how we would normally read the 2 words written down on paper or typed to a screen. As an aside…I bet none of you(unless you took a computer programming course before) ever even used the word concatenate in your life. I first learned this word when I was a student at a school named “The Institute of Computer Science” back in 1986 and unless I am in a conversation with someone about computer coding the word has yet to come up outside of this subject.

4 Likes

Thank you for the reply. I know HTML and CSS but nothing about programming. It’s hard not to overthink a lot of this because I have no idea what this is trying to teach, it just seems like it makes everything simple more difficult.

That being the case, while you may not be aware of it, you have 2 out of three bases covered where the web page is concerned. We are versed in the DOM in our study of HTML and CSS. The document (HTML) is the basis for the Document Object Model, to begin with. It is a tree like structure that directly relates to every node (element) in our document and its placement. We can select any branch or branches of the tree with CSS and apply desired selector rules to that branch, or member of the branch.

Let’s give this ability to a scripting language that interacts with the DOM in the same way, by selecting branches or individual nodes. Only now we can build collections and interact with them in ways that are more than just visual, like CSS. It’s the interactivity that CSS cannot provide. That is what JavaScript is. What CSS is to styling and visual effects, JS is to interactive behavior. This reaches all the way to the server-side though XHR by which we can bring down new content from the server right in place on the screen without reloading the page. Behavior is the key word when we bring up interaction.

We don’t even have to think of it as programming. ‘Planned interaction’ is an apt term when it comes to web pages. The language is loose enough to permit a good amount of intuition and experimentation, and is not daunting when we focus our objective.

Stare at your web page for awhile. Think, what interaction does this page need, that could be logically justified for all users, including assistive technology? Then ask, can it be done with CSS, visually for sighted users and through other signals to screen readers? Then go with the CSS model that already meets the need.

When you find the need that CSS cannot meet, then turn to script to fill out the part that CSS is unable to. JS should not do what CSS can do, but what it cannot.

There is no point learning JS for the fun of it. Python is a lot more fun, and a heck of a lot more powerful. The only reason to learn JS is to make web pages (user interfaces) more capable of interacting with their users in responsive (not just visual) ways. Oh I can pile on a dozen more reasons such as the prerequisite to jQuery, Angular, React, Express, &c. all the way up to Node.js. But we’re not at that stage by a long shot.

Say we have a button in our page for which the text will change when the user interacts with it, and reverts back to its original state when no longer engaged. Can we do that with CSS? Long pause… No.

CSS can only apply rules to the DOM, it cannot modify the nodes. JS on the other hand is ruler supreme and it can do whatever it wants. That is the basis of jumping to this level of manipulation. We can do what CSS cannot.

Best to have a reason to involve scripting, or not have it all. It’s not a toy and offers no bells and whistles that a site needs. It is there as a means of fulfilling our interactivity objectuves. Nothing more.

Bottom line, treat JS the same way you treat HTML and CSS. You are the boss. It’s your document; you’ve structured it, you’ve styled it; now it’s your call what interactivity it will have. Study YOUR page and ask the questions from earlier. Then set out to learn how to achieve that behavior. Wonders never cease what we can do when we have a clear objective. Keep it simple, and keep notes of what you want to do, and what you have looked into in reaching that goal.

9 Likes

Thank you for breaking it down with the structures, that is helpful to see the bigger picture. That is what I’m having trouble with learning JS, I have no idea how I would use anything in these lessons. With as CSS, you change a color or font and you see it right away. I’m not sure if that’s why I enjoy learning CSS or why JavaScript is so difficult to understand.

Unfortunately, I’m also trying to get to a point to learn Node or Angular or whatever I have to for work but I do have learn JavaScript to start any of those.

1 Like

The pace and order of the lessons here can seem grueling. Fortunately there is no specific timeline so you can learn at your own pace, and review and redo over and over. In time you will feel empowered and able to govern your own curriculum while reaching out to other online reference and learning resources. We’re here on the forums to guide learners along their learning path so don’t be afraid to ask questions.

2 Likes

Best example given! :smiley:

thank you @mtf, this has been insightful

1 Like

index.html

   <input type="text" id="getUserName" value="John Doe" />
   <p id="userName"></p>

   <script>
        let getUserName = document.getElementById('getUserName').value;

        let printUserName = document.getElementById('userName');

        printUserName.innerHTML = `Welcome : ${getUserName}`;

        // <p id="userName">Welcome : John Doe</p>
   </script>