0

Ruby has the << concatenation operator. It can be used to push an item to an array (.push() can also be used in Ruby, but it is longer). It is used like this:

array = [1, 2]
array << 3
return array    # Will return [1, 2, 3]

Is there a similar Javascript operator to do that, or do I have to use .push()?


Solved: There is no Javascript operator similar to <<. You have to use push (Or create a function with a short name like a and push the only argument it takes)


2
  • If you want to use Ruby to write JavaScript, I'd suggest you have a look at Opal: github.com/opal/opal Commented Feb 1, 2016 at 11:23
  • I was not looking to use Ruby to write Javascript, only if Javascript has as a similar operator to <<. Thanks for the link anyway! Commented Feb 1, 2016 at 14:17

2 Answers 2

3

JavaScript does not support operator overloading and it is language with syntax characteristics quite different from Ruby.

For instance, in Ruby, you can omit parenthesis around parameters while making a function call.

arr << 4

is equivalent to

arr.<<(4)

JavaScript does not allow such flexibility, and hence, what you are asking may not be possible

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

1 Comment

So there is no Javascript operator? Thanks!
0

This is the shortest way I can think of that doesn't use push()

var arr = [1, 2, 3];
arr[arr.length] = 4;

It's also open to being wrong if the length property of arr has been externally manipulated.

arr.length = 100;

For instance. I like the best way would be to use push() but this is an alternative if you'd really like to use it. I'm not sure that a shorter way to push to arrays exists in JS.

3 Comments

This is longer than arr.push(4)
You misunderstood my question, I don't mind using .push(), but << is 5 digits shorter. I wanted to find out if a Javascript operator exists. But thanks for the answer anyway!
Yeah, I tried messing around with adding Array.prototype["<<"] = Array.prototype.push; just to see what might be posisble, but I couldn't get it working and adding things to the prorotype probably isn't a great idea anyway.

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.