In Kyle Simpson's book You Don't Know JS: this & Object Prototypes, he writes this on the subject of how to duplicate an object:
One subset solution is that objects which are JSON-safe (that is, can be serialized to a JSON string and then re-parsed to an object with the same structure and values) can easily be duplicated with:
var newObj = JSON.parse( JSON.stringify( someObj ) );
Of course, that requires you to ensure your object is JSON safe. For some situations, that's trivial. For others, it's insufficient.
What is a "JSON-safe" object? I ran a few tests with JavaScript and so far most things (arrays, numbers, strings, objects) can be duplicated using the above line, except for methods (foo.bar), when trying to duplicate a method, undefined is inserted in the method's place in the duplicated object.
To get foo<=> JSON.parse(JSON.stringify(foo)) as true, we must be able to represent foo in the JSON format.
JSON only supports:
Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers like NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double-precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently.
String: a sequence of zero or more Unicodecharacters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
Boolean: either of the values true or false
Array: an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with elements being comma-separated.
Object: an unordered collection of name/value pairs where the names (also called keys) are strings. Since objects are intended to represent associative arrays,[12] it is recommended, though not required,[13] that each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
null: An empty value, using the word null
In javascript, the concept of JSON safe object basically refers to a javascript object that can be represented in the JSON format without any loss.
Related
The MDN page on Array#slice states:
For strings, numbers and booleans (not String, Number and Boolean
objects), slice copies the values into the new array. Changes to the
string, number or boolean in one array do not affect the other array.
Surely string literals, being reference types (admittedly with a value semantic), are not copied. Instead a reference is copied?
String literals produce immutable primitive values. Those are not reference values.
That strings might be implemented with shared references to character arrays in JS engines is just that, an implementation detail. As you say yourself, strings do have value semantics in JS, and that's all what matters.
No, string literals are considered primitive types in JavaScript, just like numbers.
See MDN - Strings # Distinction between string primitives and String objects
Is there an upper limit to the possible character length of strings in JavaScript, and ES6+ in particular?
Could you do this?
const wowThisIsALongString = `${collectedWorksOfWilliamShakespeare}`
[I'd write the collected works out by hand but am feeling lazy.]
If I understand correctly (and odds are that I don't), a JavaScript string is just a special kind of JavaScript Object, so there's technically no limit?
But maybe things are different in practice?
EDIT / UPDATE: As people have noted, a string primitive isn't an Object. I'd never thought of it as such until I checked the ECMAScript 2015 specs.
4.3.17 String value
primitive value that is a finite ordered sequence of zero or more
16-bit unsigned integer
NOTE A String value is a member of the String type. Each integer value
in the sequence usually represents a single 16-bit unit of UTF-16
text. However, ECMAScript does not place any restrictions or
requirements on the values except that they must be 16-bit unsigned
integers.
4.3.18 String type
set of all possible String values
4.3.19 String object
member of the Object type that is an instance of the standard built-in
String constructor
NOTE A String object is created by using the String constructor in a
new expression, supplying a String value as an argument. The resulting
object has an internal slot whose value is the String value. A String
object can be coerced to a String value by calling the String
constructor as a function (21.1.1.1).
So, when they write that, is the meaning that String objects are objects which contain strings, or ... something else?
Another Update: I think that Ryan has answered this below.
There is a specified length of 253 − 1 in Section 6.1.4:
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values (“elements”) up to a maximum length of 253-1 elements.
This is the highest integer with unambiguous representation as a JavaScript number:
> 2**53 === 2**53 - 1
false
> 2**53 === 2**53 + 1
true
Individual engines can have smaller limits. V8, for example, limits its strings to 228 − 14 characters.
Side note: primitive strings aren’t objects, but that doesn’t have much to do with length limits. JavaScript has a “primitive wrapper” misfeature allowing strings, numbers, and booleans to be wrapped by objects, and that’s what the section you linked refers to, but there’s no reason to ever use it.
I am using a basic identifier which uses a unix timestamp with an appended alphanumeric section appended to it.
Everything has been working fine until recently - a couple of identifiers fail to update in the database.
I have noticed that the failing id's have all numbers and the letter E.
EG 1386953039E87 which is being transcribed as 1.386953039e+96
I am far from being a mathematician but feel that the original value is being treated as a number. I have tried using the toString() function but this has not worked for me.
Calling toString is too late because outputting 1386953039E87 has already created it as a number (or JavaScript's best guess at a number).
Try modifying your server-side code to output it surround in quotes instead, so that it gets created as a string instead of a number.
This could also be a side-effect of using jQuery's data() function. They mention in their api docs that it doesn't alter their value but it seems like your situation is proving otherwise:
Every attempt is made to convert the string to a JavaScript value
(this includes booleans, numbers, objects, arrays, and null). A value
is only converted to a number if doing so doesn't change the value's
representation. For example, "1E02" and "100.000" are equivalent as
numbers (numeric value 100) but converting them would alter their
representation so they are left as strings. The string value "100" is
converted to the number 100.
When the data attribute is an object (starts with '{') or array
(starts with '[') then jQuery.parseJSON is used to parse the string;
it must follow valid JSON syntax including quoted property names. If
the value isn't parseable as a JavaScript value, it is left as a
string.
To retrieve the value's attribute as a string without any attempt to
convert it, use the attr() method.
So it seems you need to use the attr() instead of data() for this
I have recently seen some references that explain Strings in Javascript as a primitive type.I know that a primitive is a data type that is composed of no other data types and can not be broken down any further.But the problem is I have also read strings are objects.How it can be both ?Please clarify me about the confusion.
You can read about that exact topic on MDN:
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
This question already has answers here:
What is the difference between JSON and Object Literal Notation?
(10 answers)
Closed 4 years ago.
I am new to JSON and JavaScript objects.
Can someone please explain the differences between JSON and JavaScript object?
What are their uses?
Is one better than the other? Or does it depend on the situation?
When to use which one, in what situation?
Why was JSON created in the first place? What was its main purpose?
Can someone give examples of when one should use JSON rather than a JavaScript object and vice versa?
First you should know what JSON is:
It is language agnostic data-interchange format.
The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.
For example, in JSON all keys must be quoted, while in object literals this is not necessary:
// JSON:
{ "foo": "bar" }
// Object literal:
var o = { foo: "bar" };
The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:
var o = { if: "foo" }; // SyntaxError in ES3
While, using a string literal as a property name (quoting the property name) gives no problems:
var o = { "if": "foo" };
So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.
The data types in JSON are also restricted to the following values:
string
number
object
array
A literal as:
true
false
null
The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.
// Invalid JSON:
{ "foo": 'bar' }
The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.
// Invalid JSON:
{ "foo": 0xFF }
There are some buggy implementations (Firefox 3.5+, IE8+, json2.js) where octal literals are wrongly allowed, e.g. JSON.parse('01') should produce a SyntaxError.
JSON is a string representation of an object. It is an interoperable serialization format. It is not tied only to javascript. For example there are JSON serializers for .NET allowing you to serialize/deserialize .NET objects.
So it's just a format allowing you to convert from objects to string and back which is convenient if you want to transfer them over the wire.
It is very close to javascript object representation and if you simply eval() a JSON string you will get the corresponding object.
JSON is a data interchange format, which just happens to look like a subset of YAML or JavaScript code you can execute and get an object back. A JavaScript object is just an object in JavaScript.
With JSON being a data interchange format you can exchange structured data in a textual form with it. It is pretty decoupled from JavaScript by now. JavaScript object allow you to create and work with structured data during the execution of a JavaScript program.