whats the difference between string literals, and just a string? [duplicate] - javascript

This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Closed 4 years ago.
I’m studying JavaScript and this is a statement I came across:
new String("Hello");
This will create a new string that is the same as string literal "hello", although it will be classed as an object rather than a primitive values. For this reason it is preferable to use the string literal notation.
What is a String literal?
Why is new String("Hello") classed as Object?

A literal string (or literal <any data type>) means that you just reference the data directly.
For example
"Hello".length // returns 5
The "Hello" is a string literal since we are just referencing it "as-is".
You could do exactly the same thing with a string object:
var strObj = new String("Hello");
strObj.length // returns 5
These two examples are pretty much identical (for the sake of this example). Both create a string variable and measure it's length.
The first uses a string literal and the second uses a string object.
Here is another example using numbers - if you do a direct calculation such as:
5 + 2
you'll be using number literals - again, when you only reference the data directly, it is considered a "literal".

Related

user. and number later [duplicate]

This question already has answers here:
Can I get a javascript object property name that starts with a number?
(2 answers)
Closed 8 years ago.
I've got an object where one of the properties starts with a number. I've read that this was allowed, but I'm getting this error:
SyntaxError: identifier starts immediately after numeric literal
var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};
//works fine
window.alert(stats.COUNTS.TOTAL);
//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);
Here's a fiddle.
How can I access the properties that begin with a number without rewriting the PHP that generated it?
You can use bracket access for properties that aren't valid JavaScript identifiers, that goes for property names with spaces or other language symbols like +, *
window.alert(stats.LOAD_AVG["1_MIN"]);
You can use bracket access anywhere really
window.alert(stats["COUNTS"]["TOTAL"]);

How to convert an array of type String to an array object in javascript [duplicate]

This question already has answers here:
Parsing string as JSON with single quotes?
(10 answers)
Closed 2 years ago.
I have a string containing an array, and want to extract the array and play with its objects.
var arrayString = "[{'name': 'Ruwaida Abdo'}, {'name': 'Najlaa Saadi'}]";
Basically, I am dealing with a JSON file in which some properties are in fact arrays but stored as strings. Hence, I need to deal with them as strings and convert them to array to use their objects.
What you have here is a JSON string. You can parse it to get the object / array:
var array = JSON.parse(arrayString)
Edit: I see your JSON string has single quotes. You need to replace all of them with double quotes before parsing:
JSON.parse(arrayString.replace(/'/g, '"'))

convert the literal value with parentheses [duplicate]

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 3 years ago.
I'm new to Javascript, and I saw code like this:
var myData1 = (5).toString() + String(5);
and the author says he placed the numeric value in parentheses and then called the toString method. This is because you have to allow JavaScript to convert the literal value into a number before you can call the methods that the number type defines.
I'm confused, isn't that 5 is already a number, why 5 needs be converted as (5) to be a number?
The author is partly right. This has nothing todo with turning the literal into a number, this is just about a syntactical distinction: The. can either be used to express fractional numbers (1.1) or it can be used for property access (obj.prop). Now if you'd do:
1.toString()
that would be a syntax error, as the dot is treated as a number seperator. You could do one of the following to use the property access dot instead:
1.0.toString() // as the first dot is the number seperator already, the second dot must be property access
1..toString() // same here
(1).toString() // the dot is clearly not part of the number literal

How does object[[["key"]]] evaluate to object["key"] in javascript? [duplicate]

This question already has answers here:
Why does accessing an element in an object using an array as a key work?
(3 answers)
Closed 6 years ago.
Why does javascript evaluate the following as true, given that object foo has a valid property bar?
foo[[[["bar"]]]] === foo["bar"]
Based on operator precedence, I would think foo[[[["bar"]]]] is trying to access a property with the array [[["bar"]]] as the key, but why does that still "flatten down" to the same as foo["bar"]?
Colleagues of mine are saying javascript parsers have bracket simplifying which ignores the extra brackets. I don't think this is true since saving [[["foo"]]] to a variable test gives the same result:
> test = [[["bar"]]]
[Array[1]]
> foo["bar"] = 5
5
> foo[test]
5
What aspect of the language or parser is causing this behavior? Thanks!
JavaScript bracket notation accepts an expression, but it always converts the value of that expression to a string. Thus if you pass in an array, it will attempt to convert it to a string. In your case you are passing in an array [[["bar"]]], and [[["bar"]]].toString() === "bar".
If you are wondering why [[["bar"]]].toString() === "bar", it is because when an array arr is converted to a string implicitly it is like calling arr.join(','). That is each of its elements are converted to strings and then joined in a comma separated string. When the array only has one element, the string representation of the array is just the string representation of that one element. In your case your array ([[["bar"]]]) has one element: [["bar"]].
That array is converted to a string too, and since it is also a one element array, the string representation of it is the string representation of that single element: ["bar"].
["bar"] is also an array with one element, which is a string, so the string representation of ["bar"] is just "bar".
What this comes down to is: [[["bar"]]].toString() === "bar"
and foo[[[["bar"]]]] is the same as foo[[[["bar"]]].toString()].
You would also find that:
foo[[[[1]],[2]]] === foo["1,2"]
because: [[[1]],[2]].toString() === "1,2".
Let's see how foo[[[["bar"]]]] is evaluated, step-by step:
The outermost brackets in foo[...] denote a property
accessor. The expression foo[[[["bar"]]]] thus translates to
accessing a property of foo with name [[["bar"]]].
According to the ECMA standard, the abstract operation
ToPropertyKey(name) is then used to turn the name [[["bar"]]]
into a property key value:
A property key value is either an ECMAScript String value or a Symbol
value.
The name [[["bar"]]] is not of type Symbol and thus converted
into a string. An array is converted to a string by joining all its
string converted values:
[[["bar"]]].toString() === "bar"
Which finally means that our property key actually becomes "bar":
foo[[[["bar"]]]] === foo[[[["bar"]]].toString()] === foo["bar"]

How does JavaScript interpret indexing array with array? [duplicate]

This question already has answers here:
Why does [5,6,8,7][1,2] = 8 in JavaScript?
(3 answers)
Closed 7 years ago.
[1,2,4,8][0,1,2,3]
// equals to 8 (the last element of the indexing array (3) becomes the index)
Why is this not a SyntaxError error (a bad legacy or a purposeful feature)? (A possible duplicate, however I wasn't able to find an answer here.)
Update: Why the contents of the square brackets are treated as an expression?
The first part:
[1,2,4,8]
is interpreted as an array literal. The second part:
[0,1,2,3]
is interpreted as square bracket notation to access a member of the array. The contents of the square brackets are treated as an expression, which is seen as a sequence of comma separated values:
0,1,2,3 // or (0,1,2,3) as an independent expression
That expression returns the last value, so is effectively:
[1,2,4,8][3] // 8

Categories

Resources