How To Use Concatenation In Javascript

How To Use Concatenation In Javascript

“Dear John Doe, you have successfully registered for…..” Have you ever wonder how automated messages work in a way that they always get your name right? You know a human didn’t respond to your action that fast, even a human would have to take a bit of time to get your names correctly and type the mail yet a machine does it instantly. The magic is called “concatenation”.

When writing code that interacts with humans, we mostly have variables (which are containers used to store values). These variables are used to receive and hold your data in a way that is similar to a database and at the same time, not a database. The variables can be added or combined with texts or other things in order to create some operations or execute a set of instructions given to the machine by the software engineer.

Usually, one or more variable(s) are used to receive and hold these data while other variable(s) are used to combine or manipulate the first set of variables to generate a response or execute some sequence of activities. Eg. let firstName = "John";

let lastName = “Doe”;

let fullName = firstName + “ “ + lastName;

let age = 30;

let response = “Mr. ” + fullName + “ is ” + age + “ years old.”

Console.log(response);

I’ll explain the code now. The first line of code let firstName = “John”; is where I assigned the name “John” to the variable firstName. The second line is where I assigned the name “Doe” to the variable lastName. In the third line, I created yet another variable, this time, I concatenated two variables in order to create this variable. I added firstName and lastName together. Notice the “ “ which is more or less a quotation mark with a space in between them. If I didn’t add that space I would have the two variables appear as JohnDoe when the variable fullName is called.

I used other methods to add the empty space in the fifth variable. In the variable response, concatenated variables fullName and age, I also added some texts around them. Notice that I didn’t use any empty quotation marks like “ “, I simply added them to the texts. The same can be done for values. The result when variable response is logged into the console is Mr. John Doe is 30 years old. It can be neater with template literals though.