6

In Javascript,

hello += ' world'
// is shorthand for
hello = hello + ' world'

Is there a shorthand operator for the opposite direction?

hello = ' world' + hello

I tried hello =+ ' world' but it did not work: it just typecast ' world' into NaN and then assigned it to hello.

2
  • 4
    No, there's no shorthand for that. Commented Feb 18, 2016 at 19:19
  • " world" += hello;, works but you need to capture the output. Commented Feb 18, 2016 at 20:16

4 Answers 4

3

Is there a shorthand operator for the opposite direction?

No, all JavaScript compound assignment operators take the target as the left-hand operand.

Just use the hello = ' world' + hello; statement that you had. If you're doing this repetively, consider using an array as a buffer to which you can prepend by the unshift method.

Sign up to request clarification or add additional context in comments.

Comments

2

There is not really a shorthand for what you are describing.

An alternative approach would be to use String's concat function:

var hello = 'hello';
var reverse = 'world '.concat(hello);

1 Comment

In Java it's look like this: String title = title.concat("-"+title); Thank you.
1

Javascript doesn't have 'reverse' operator for strings, but there is Array.reverse() function which can help you in such cases:

var hello = "hello";

hello = (hello + ",world, beautiful").split(",").reverse().join(' ');

console.log(hello);  // beautiful world hello

Comments

0

Concat returns the array without modifying existing arrays so where as you have

a= a.concat(b) // to put b at the end of a

You could just as easily do a = b.concat(a)? // put b followed by a. IE b at the beginning of the list a

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.