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

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

Related

Why does Object.keys() return an Array of strings? [duplicate]

This question already has answers here:
What is the type of "keys" in JavaScript?
(5 answers)
Closed 5 months ago.
It took me quite some time to realize that Object.keys() return and Array of strings that correspond to the object keys. This is well documented (but you have to read carefully :)).
My question is: what are the (technical) reasons for the returned Array to be made of keys cast to a string? (and not the keys themselves)
In my case the keys were integers, so I had to re-cast what .keys() returns through a .map()
In my case the keys were integers
They were not.
Object property names can only be strings or Symbols (ECMAScript, mdn).
The numbers (JS doesn't have an integer data type) were converted to strings when the property was created, not when the property names were read.

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 good reasons to use the Number constructor (as opposed to literals)? [duplicate]

This question already has answers here:
What is the difference between JavaScript object and primitive types?
(1 answer)
Why to avoid creating objects of primitives in JavaScript?
(4 answers)
JavaScript primitive types and corresponding objects
(2 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Are there any good reasons to use new Number(n)? Why does this constructor exist?
I can think of several reasons to avoid it, eg.,
literals are more memory efficient since they don't construct anything new.
literals are equal to each other (5 === 5 but new Number(5) !== new Number(5)).
the typeof operator indicates that it's a number rather than an object.
new Number(0) is never falsey. (!!new Number(false) == true).
You can use it for type conversion, but there are more concise methods. (+false === 0).
To be clear, I understand the Number object has useful methods and properties, my question is specifically about the constructor.
I'm using Number as an example, but I don't understand why Javascript exposes other constructors where literals are available either (String, Object, Array, etc.).
Why do these exist and are there ever any good reason to use them?

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.

In JavaScript, why don't any objects equal each other, except strings? [duplicate]

This question already has answers here:
Difference between the javascript String Type and String Object?
(2 answers)
Closed 9 years ago.
Everything in JS is an object. I've always known that, and I totally understand that. I know why {} !== {}. It's two different objects. Same as if you were to write out new Object() == new Object().
Some other examples:
{} == {} // => false
[] == [] // => false
/ / == / / // => false
new String() == new String() // => false
But, Strings are objects too (it's why you can do ''.replace() and extend them), so why does this work:
'' == '' // => true
Obviously it'd be a huge headache to compare two strings if this didn't work, but this seems inconsistent with the rest of the language. Internally, what's going on? Is it just a one-off or is there some other concept behind this?
JavaScript basically treats strings and numbers as scalars at all times, converting them to objects when a method is called, and converting back afterward, in cases where you aren't explicitly declaring new String("");
Same with numbers.
Without string/number/boolean equality, you'd have a hard time doing much of anything.
It is a one-off.
Reference
There is a difference between string literals and string objects. The article goes into more detail if you are interested.
The same is true for booleans and numbers. These primitives are compared different from objects.
There are five primitive types in JavaScript: Number, String, Boolean, Undefined, and Null. Comparing the empty string literal "" to itself is no different from the comparison 5 === 5.

Categories

Resources