Javascript Adding Objects with + [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Overloading Arithmetic Operators in JavaScript?
Is it possible to add Javascript Objects in a custom way? Javascript allows you to use the + symbol to merge Strings together as well as add Numbers together.
I am wondering if you could define new ways for things to be merged such as adding arrays.
What I'm looking for is something like this:
var output = [0,1,2] + [3,4,5];
console.log(output);
//I want this to log [3,5,7]
I know I could easily do this with some addArray() function but I was wondering if it can be done by using the + symbol.

No, Javascript does not support operator overloading and there is no built-in functionality to do this.

Is it possible to add Javascript Objects in a custom way?
Yes, you can write your own addObject function.
Javascript allows you to use the + symbol to [concatenate] Strings together as well as add Numbers together.
ECMA-262 defines whether the '+' punctuator is treated as a unary or addition operator in expressions. As Mat says, you can't overload it. Even if you could, it doesn't seem like a good idea to change its behaviour since it's already used for 3 different things and has a specified behaviour for "adding" arrays like [1,2] + [3,4].

Related

[].slice.call() pattern in javascript [duplicate]

This question already has answers here:
Explanation of [].slice.call in javascript?
(9 answers)
Closed 1 year ago.
Bootstrap 5 Javascript examples sometimes show code like:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
Why isn't this just:
var collapseElementList = document.querySelectorAll('.collapse')
What is [].slice.call() doing exactly? I don't understand why you'd slice on an empty array, and then I have no idea what call is doing there. What would be the problem with the obvious way to do this, the second way above?
querySelectorAll returns a NodeList, which is a collection, but not an array.
[].slice.call turns an array-like collection into an array proper. It will allow you to use array methodss on it, eg:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'));
const textsOfCollapsedElements = collapseElementList.map(elm => elm.textContent);
Otherwise, if you don't convert it to an array first, you won't be able to use array methods on it.
It's probably most important for forEach. Newer browsers support NodeList.prototype.forEach, but it hasn't been with us that long. In contrast, Array.prototype.forEach has existed forever. So turning the collection into an array allows for forEach to be called on it, even on obsolete browsers that don't support NodeList.prototype.forEach.
It's an idiom for turning anything array-ish (in this case a DOM NodeList) into a real Array by exploiting the fact that Array::slice can work on anything that's iterable and has a .length property.
The modern idiom is Array.from(...).

What's the difference between using Array.of() compared with brackets [ ]? [duplicate]

This question already has answers here:
Array.of vs "[ ]". When to use Array.of over "[ ]"?
(3 answers)
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 4 years ago.
For example,
let x = [1,2,3,5];
is equivalent to:
let x = Array.of(1,2,3,4,5);
(Unless I'm missing an important detail, which is why I'm asking the question)
You could also mix these with spread ... syntax and variables and thus other arrays. To me, it seems Array.of() has more overhead. Would Array.of() have to parse an arguments object into another array?
I know there's also new Array() as others have before questioned here, but that has a different semantic purpose, so I don't see this question as a duplicate to that.
As I see it now, Array.of() and [ ] seem redundant. The function's intent does seem more explicit on the former, but the latter's intent is simple enough to not be misunderstood.
So to summarize:
When is one preferable over the other?
Why does Array.of() exist when JavaScript survived without it for so long?
And, what're the differences of these two methods, if any? Would there be any needless overhead?

Is there a more compact option to check if a variable equals "this" OR "that"? [duplicate]

This question already has answers here:
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 4 years ago.
I want to check if a variable (in this case sampleVariable) is equal to THIS or THAT:
if(sampleVariable == "THIS" || chosenVerb == "THAT")
The above code should work fine, but I was wondering if there was a way to simplify and compact it - for example, something like this (this probably isn't how you do it, just an example):
if(sampleVariable == "THIS" || "THAT")
I'm fairly certain the above doesn't work since it will check for the two statements being true separately.
I found this website, which seems to be what I'm looking for. They say that this code is the best way to go around it:
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
handleYellowFruit();
}
Is this still the way that this is supposed to be done (since the blog post I linked above was published over half a decade ago)? If so, what are these characters in the parentheses: / ^ $ ?
Thanks for the help!
Depending on browser support and ability to polyfill, I'd try array.includes:
if ((["THIS", "THAT"]).includes(sampleVariable)) {

Why could I compare two strings with "==" but not two arrays of chars? [duplicate]

This question already has answers here:
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 9 years ago.
For example:
var one = ['H', 'i'];
var two = ['H', 'i'];
(one == two) returns false
but
(one.join('') == two.join('')) returns true
Why is that?
There is a difference on how equality is defined for strings and arrays - strings are considered equal if their contents are identical, but arrays are considered equal only if it's the same array, and different otherwise even if their contents match.
There are a bunch of reasons why it could be the way it is, for example two reasons:
1) you often don't want array comparison to go through the whole array, because it could be huge and would take a huge time. So the default way shouldn't be dangerous.
2) you can alter array contents while still being 'the same' array; while javascript strings are immutable so any changed string is a new, different object.
When comparing objects, JS wants to see if they are the actual same object, not just an object with the same contents.
I find underscore's isEqual method useful here, but if you want to figure out how it is done library free, just glance at underscores core, which is very easy to read
http://underscorejs.org/#isEqual

Javascript : Coding standards, Pascal Casing or Camel Casing? [duplicate]

This question already has answers here:
What is the best-practice casing style for javascript? Why?
(6 answers)
Closed 3 years ago.
I am creating calling a function and passing in an array of objects but i am unsure if to use camingCasing or PascalCasing. Here is my method
util.load({
DefaultText:'Empty',
Items:[
{
Id:0,
Title:'Press'
}
]
});
If you notice i am passing in DefaulText, but should it be defaultText? and also Items, should it be items? and within the Items and i am also passing in Id and Title.
Can anyone confirm the correct way of doing this?
I know that methods are camelCasing but passing in objects like above?
Thanks in advance
The very popular JavaScript convention is to use PascalCasing as you call it for constructors (classes), for example String, Number, Date and camel casing for variable names and object keys. This code convention is used for all the built-in JavaScript functionality in the modern browsers, so thats why I would recommend to use it for your own code too.
There is no one correct way.
The JavaScript API uses camelCase for functions and PascalCase for objects.
Just choose one and be consistent. JavaScript identifiers are case sensitive.

Categories