Can you use the value of an Array as a Comparison [duplicate] - javascript

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 6 years ago.
var hits = ["a", "b", "c"];
if (hits !== ["a", "b", "c"]){
//Do some stuff here
};
Can you use the value of an array as a comparsion? The above does not seem to work for me I was wondering if this is the way to go about it or if there is another way to access the literal value of an array for comparison.

The equality operators (=== and !==) compare references, not values in case of objects. Mind that in JavaScript Arrays are objects. Because of that and because these are two distinct arrays (they look the same, they contain the same values, but they're not the same array) their references differ:
If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
You can read more about it on MDN.
Note: == and != equality operators also compare objects by references, but since they do more than just simple comparison (and it's often unexpected), it's generally advised not to use them and always stick to strict equality operators (=== and !==).
How to compare arrays then?
There are at least a few different methods. Some people advise to compare JSON.stringify of both arrays but, even though it works for simple cases, it's not really a good solution performance-wise. You can find better methods here https://stackoverflow.com/a/14853974/704894
If you happen to use some kind of utility library such as lodash or underscore this function is already there! See https://lodash.com/docs#isEqual

You can write this
if (JSON.stringify(hits) === JSON.stringify(["a", "b", "c"])) {

You can't do it this way because of the way Javascript handles arrays - it's not checking the values are the same, it's checking that the object is the same object (which it isn't).

Related

is this method object.keys returning an array or keep it an object [duplicate]

This question already has answers here:
Why does typeof array with objects return "object" and not "array"? [duplicate]
(3 answers)
Closed 2 years ago.
I'm learning JavaScript, so pardon any mistakes in how I phrase the question.
let nan={
n:3,
j:4
};
let nag = Object.keys(nan)
> nag
(2) ["n", "j"]0: "n"1: "j"length: 2__proto__: Array(0)
> typeof nag
"object"
Why is nag an object and not an array? And that makes difference when you want to access, you will be not able to access with dot notation I think we need in that case square bracket
This is because internally javascript engines store Arrays as objects. Therefore, when you ask for the typeof an array, it returns an object since that is what it is. Essentially, in javascript, Array is an abstraction over native object (an indexed collection object).
If you want to know whether a variable is an Array and not an object you should use Array.isArray(nag). This returns a boolean.
You can lookup the docs here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
or if you are in the mood, lookup the typeof spec at:
https://www.ecma-international.org/ecma-262/#sec-typeof-operator
tip: With JS, whenever in doubt, lookup the specs. It's probably the best place to clear up confusions
In Javascript, everything that is not a primitive (numbers, bigints, strings, symbols) are objects. This includes arrays. Objects also have square bracket notation to look up a key, and the dot notation is just a shorthand for looking up a string key:
const a = {
foo: "bar"
};
a.foo // "bar"
a["foo"] // "bar"

Any way in JavaScript to deep-check an object for a truthy value? [duplicate]

This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Closed 6 years ago.
I believe there's a mechanism for this in CoffeeScript (the ? token), but I'm wondering if there's a better way to do this kind of check in ES6:
if (item && item.integrations && item.integrations.slackData) ...
(besides writing a helper function, which is the immediately obvious solution)
EDIT: The goal here is to make the code is simple and terse as possible.
Example object:
item = { integrations: { slackData: { url: '...' } } };
EDIT 2: Thanks for pointing out the duplicates. I couldn't figure out what terms to search for. I'm probably going to go with using lodash's _.get() function.
You can use Array.prototype.every()
var check = [item, item.integrations, item.integrations.slackData]
.every(function(element) { return element });
Edit, Updated
As noted at comments by #FelixKling, the pattern at above using .every() will fail if item.integrations is undefined.
Given the example object at Question you can use JSON.stringify(), String.prototype.match() with RegExp /"integrations":|"slackData":|"ur‌​l":/g/, then check that .length of resulting array, if any, is equal to the number of properties expected; in the present case 3.
A javascript object which is passed to JSON.stringify() should have properties with the following pattern:
" followed by property followed by " followed by :. Depending on the source object, the RegExp can be further adjusted to meet the specific properties and values of that object.
JSON.stringify(item).match(/"integrations":|"slackData":|"ur‌​l":/g).length === 3
Note that JSON.stringify() has a replacer option which can be used to match properties of the object. The replacer function option is recursive. See also
remove object from nested array
Nested object and array destructuring
Convert javascript object to array of individual objects
How do I filter Object and get a new Object?
but I'm wondering if there's a better way to do this kind of check in
ES6:
The present Answer does not attempt to indicate that using JSON.stringify() and RegExp to match or filter a javascript object is "better"; but only that the approach can meet the described requirement at the present Question.

Why are two objects with the same values not equal? [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 8 years ago.
I run the following in console why is the output false. Not asking how to compare two objects but why these two objects are not same.
> a = {same:'same'}
Object {same: "same"}
> b = {same:'same'}
Object {same: "same"}
> a === b
false
> a == b
false
Two objects are never the same even if they have the same content, as two different instances of Object is never equal.
When comparing two object, JavaScript compares internal references which are equal only when both operands refer to the same object in memory, keys and values are not checked, so the content of the object doesn't matter, the operands both have to reference the same object to return true in a comparison.
This is simply due to how == is defined per the The Abstract Equality Comparison Algorithm:
1. If Type(x) is the same as Type(y) [i.e. Type(x) == Type(y) == Object], then ..
1.f. Return true if x and y refer to the same object. Otherwise, return false.
None of the other rules/conversions apply because both operands are Objects.
Although there is no ECMAScript 5th edition "core" support for this task, several solutions are discussed in How to determine equality for two JavaScript objects?
This has naught to do with "references", which are an implementation detail not defined in ECMAScript, and can be entirely discussed per the above rules: two different Objects are never equal per == (and by extension ===) rules.
You are comparing two objects which never be equal. If you compare a.same and b.same then they will be the same.

In JavaScript, if “Strings are objects” then why not Numbers too? [duplicate]

This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 6 years ago.
You can do
"a".charAt(0);
wouldn't it be nice if you could do:
42.isMeaningOfLife();
well, or rather something more practical like
myNumber.round();
Sure the first thing that crossed my mind is that this would be a performance hog but apparently that is not how the JS compiler works. Check this MDN article on JS strings:
Note that JavaScript distinguishes between String objects and
primitive string values. (The same is true of booleans and numbers.)
String literals (denoted by double or single quotes) and strings
returned from String calls in a non-constructor context (i.e., without
using the new keyword) are primitive strings. JavaScript automatically
converts primitives to String objects, so that it's possible to use
String object methods for primitive strings. In contexts where a
method is to be invoked on a primitive string or a property lookup
occurs, JavaScript will automatically wrap the string primitive and
call the method or perform the property lookup.
I believe it's a simple matter of supported syntax. Both, strings and numbers are wrapped in their respective object wrapper (String, Number) when performing objects operations on them.
Number.prototype.isTheMeaningOfLife = function () {
return this.valueOf() === 42;
};
(42).isTheMeaningOfLife(); //true
42.0.isTheMeaningOfLife(); //true

Putting items in JavaScript arrays on arbitrary indices [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are Javascript arrays sparse?
Is the following "safe" in JavaScript? (as in, can be expected to work reliably on all JavaScript engines)
a = [];
a[100] = "hello";
a[100] == "hello"; // should be true
Yes. Arrays in JavaScript are sparse and your code is expected to work in all JavaScript implementations.
You can get into requirements in the section 15.4 of the specification(PDF).
Short summary: array is special object that have length property adjusted when one adds elements at properties with numeric names (like `a[123]="test"). Other methods like join take length into account duuring operations.
Yes, why wouldn't it work? Its perfectly acceptable syntax.
You can even assume
a[100] === "hello"; // will return true

Categories

Resources