0

I'm not sure i'm going bonkers or something. I just can't get my head around this. I'm currently studying Python, PHP and Javascript and I'm not sure if I mix the syntaxes or anything. Anyhow, I'm going to have a function that adds a string to a phrase. My string is 'grey' and the end result should be 'My favorite color is grey' So the code should be like 'My favorite color is' + 'grey'. The code I have so far is:

function stringPhrase(); {
document.write ("grey");
}
var result = ("My favorite color is" + stringPhrase());

Am I anyway near the correct syntax or am I heading in the wrong direction? Thanks a plenty. Regards, Thomas

1
  • 2
    You can't concatenate the result of a document.write() with something else. What's written, is already written. Commented Mar 10, 2015 at 10:32

4 Answers 4

3

You are heading in the wrong direction.. This is how you should use functions:

function stringPhrase() {
  return "grey";
}
var result = "My favorite color is " + stringPhrase();
Sign up to request clarification or add additional context in comments.

Comments

1

try

function stringPhrase() {
  return 'grey';
}
var result = 'My favorite color is'+stringPhrase();

Comments

0

The problem here is that your stringPhrase function is not doing what you expect. What you want that function to do is simply return the appropriate string: 'grey'.

So your function should look something like this:

function stringPhrase() {
  return "grey";
}

You can now use the same code you had before to call the function and get it's return value concatenated to another string:

var result = "My favorite color is" + stringPhrase();

The document.write function actually writes content to the page - this is not what you want as it can easily remove any other code (HTML or scripts) that you currently have on the page.

Comments

0

Your telling the document to write something in the function. Once it's written you can't append to it.

Use this;

function stringPhrase() {
   return 'grey'; 
}

var result = ("My favorite color is" + stringPhrase());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.