How can a space be added with string concatenation?

Hi, how can we add space between words? This is my code:

let favoriteAnimal= ‘hummingbird’;
console.log(‘My favorite animal’ + favoriteAnimal + ‘.’);

This is what the console displays:
My favorite animalhummingbird.

The code seems to be right but ‘animal’ and ‘hummingbird’ are together as one word.

1 Like

The same way you inserted the full stop at the end.

+ " " +
13 Likes

Hello, one other way that you can add a space is by adding a space in between animal and '. For example:
let favoriteAnimal = ‘hummingbird’;
console.log('My favorite animal ’ + favoriteAnimal + ‘.’

3 Likes

Do you want to ask a question? Roy is always there for us. Thanks Roy!

5 Likes

Add a space after the word ‘animal’ . It will be like this 'animal '.

3 Likes

Here are 2 common ways:

1)let favoriteAnimal= ‘hummingbird’; console.log(‘My favorite animal ’ + favoriteAnimal + ‘.’);

2)let favoriteAnimal= ‘hummingbird’; console.log(‘My favorite animal’ + ' ' + favoriteAnimal + ‘.’);

Note that you can also use string interpolation:

let favoriteAnimal= ‘hummingbird’; console.log(My favorite animal is ${favoriteAnimal} .);

You can use string interpolation by using template literals; replace the quotes with backticks(`)(https://www.computerhope.com/jargon/b/backquot.htm).

Hope this helped you on your coding journey! :grin:

I am not sure why they are teaching this method, but you can just add a space between the quotation marks.

let favoriteAnimal = ‘Dog’;
console.log('My favorite animal: ’ + favoriteAnimal);

A better method for writing this, which uses more modern JavaScript is like this.

let favoriteAnimal = ‘Dog’;
console.log(My favorite animal: ${favoriteAnimal}.);

This method works using back ticks and allows you to skip the ‘+’ signs. Its much faster and feels more natural.

They are going to teach String Interpolation with template literals later in the course. Also, you can write formatted code like this.

let favoriteAnimal = "Dog";
console.log("My favorite animal: " + favoriteAnimal);

Just enter 3 backticks on a separate line before and after the code you want to format. Also, if you want to enter one line code keywords, just put a single backtick before and after the keyword, like this: String Interpolation with templateLiterals is better than String Concatenation, although some browsers don’t suppport templateLiterals, as it is new ES6 syntax.

2 Likes

Hey thanks,

Yeah I actually moved on to the next step and discovered the Interpolation segment of the course.

FTR

Concatenation and template literal are both forms of string interpolation.