Heidi Christensen
Heidi Christensen

Reputation: 11

Concatenating with variables in a string

I'm just beginning my learning process and am stuck now on this one string. I've searched MDN, Google and Bing and not found any help.

My code instructions tell me to assign a variable, which I did. Then it wants me to test in console.log. I've done so, and when I do with spaces and punctuation, it gives me an error saying that it expected an identifier and instead saw '+'.

If I take the punctuation out I don't have an error, but no punctuation. If I take out the extra spaces as well as punctuation, I get a strange run-on sentence but no errors. I'm working this problem in Udacity, it is quiz 24 of lesson 2.

My code is:

var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1. +  " James and Julia are so " +  adjective2. +  " I cannot wait to work through the rest of this " +  adjective3 +  " content!";
console.log(madLib); 

Upvotes: 1

Views: 249

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386520

You need to add the dots as strings as well.

var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1 + "."
        + " James and Julia are so " +  adjective2 + "."
        + " I cannot wait to work through the rest of this " +  adjective3 +  " content!";
    
console.log(madLib);

The dot . has a special meaning in Javascript. It works as accessor for properties of an object.

Math.floor(1.5); // return the integer value of the given number

Read more here about property accessor.

Upvotes: 2

Amit Kumar Singh
Amit Kumar Singh

Reputation: 4475

Add . (dot) inside the double quoted part of string, not next to the variable.

It is a part of string, not a in-memory variable. And you are calling no function after that.

Below snippet works properly.

var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1 +  ". James and Julia are so " +  adjective2 +  ". I cannot wait to work through the rest of this " +  adjective3 +  " content!";
console.log(madLib); 

Example of using dot to call a function. It is not required in this case since it is already a string.

var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " +  adjective1.toString() +  ". James and Julia are so " +  adjective2.toString() +  ". I cannot wait to work through the rest of this " +  adjective3 +  " content!";
console.log(madLib); 

Upvotes: 0

Related Questions