-4

I am trying to concatenate variables in inside a function and then return. In php we just put a period before the "=" but it is not working in javascript.

Can someone please help me figure this one out?

function NewMenuItem(){
    var output = "<input type='checkbox'> ";
    var output .= "<input type='text'> ";

    return output;
}
6
  • 2
    use the + operator: "some string" + "some other string", Expressions and Operators Commented Sep 12, 2014 at 19:23
  • . is the PHP concat operator. JS uses +. Commented Sep 12, 2014 at 19:23
  • 3
    google.com/search?q=javascript%20string%20concatenation Commented Sep 12, 2014 at 19:23
  • You can also do output += "some more stuff" Commented Sep 12, 2014 at 19:24
  • 2
    You'll benefit from giving the MDN introduction to JavaScript a read-through. Especially if you already know another language, read through it so you know the syntax differences. Commented Sep 12, 2014 at 19:24

3 Answers 3

3

The + operator will concatenate two strings, ie. "Hello" + " World" //> "Hello World". Using += is a short cut for assigning and concatenating a variable with its self.

ie. instead of:

var myVar = "somestring";
myVar = myVar + "another String";

you can just do:

var myVar = "somestring";
myVar += "another String";

For your problem:

function NewMenuItem() {
    //This is just a small example. The end result is more broader then this
    var output = "<input type='checkbox'> ";
    output += "<input type='text'> ";
    return output;
} //end of NewMenuItem(){
Sign up to request clarification or add additional context in comments.

3 Comments

@torazaburo true, I guess thats just out of habit from the days of arithmetic. Updated.
agconti. Thank for the reply My mistake was that i was doing var output = "<input type='checkbox'> "; var output += "<input type='text'> "; I put a var after the second variable. But your example worked. Thanks!
@eldan221 if I answered your question can you please accept my answer?
1

"+=" is the standard way to concatenate in javascript;

var a = "yourname";
var b = "yourlastname";
var name = a + b;
var complete_name = "my name is: ";
complete_name += name;

result : my name is: yourname yourlastname

2 Comments

You can't use += on a variable that is undefined. Your code doesn't even compile.
thanks i didnt see that basic error. Edited my answer.
0

With Concat function or with plus operator (+).

Check this link jsfiddle to see a working example.

1 Comment

concat function is deprecated/reccommnded against.

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.