0

JavaScript array object and empty dictionary.

Supposed we define 2 new variables: a = new Array() // this is definition of new empty array in javascript b = {} // define new dynamic empty dictionary if ((new Array() == a) || (b=={})) What is the boolean return value of this if statement above? True or false?

6th Aug 2024, 2:39 AM
Oliver Pasaribu
2 odpowiedzi
+ 2
The expression: if((new Array() == a) || (b=={})) will always evaluate to false. You can't just directly use == or === for typechecking. There are various methods for doing that. In Javascript, almost everything is an object. While all arrays are objects, not all objects are arrays. So arrays passes some of the tests for objects. So it is better to use the stricter type checking methods. https://sololearn.com/compiler-playground/WE1240gdd8ep/?ref=app
6th Aug 2024, 3:11 AM
Bob_Li
Bob_Li - avatar
+ 2
In JavaScript, arrays and objects are reference types. When you create a new array or object, even if they have the same content, they have different references in memory. The equality (==) operator checks whether its two operands are equal, returning a Boolean result If the operands have the same type, they are compared as follows: Object: return true only if both operands reference the same object. String: return true only if both operands have the same characters in the same order. Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality The logical OR operator (||) only returns true if at least one of its conditions is true. In this case, neither condition is true, so the output is false. To see this for yourself, you can run the following code: let result = (new Array() == a) || (b == {}); console.log(result);
6th Aug 2024, 8:17 AM
Chris Coder
Chris Coder - avatar