Is there a difference between String(x) and '' - javascript

Is there a difference? Will string 2 inherit different object prototypes?
var s1 = 1234 + '';
var s2 = String(1234);
//s1.someNewFunc(); error?
//s2.someNewFunc();
Thanks

var s1 = 1234 + '';
Creates a string literal. This is a javascript language primitive.
var s2 = String(1234);
The String() function also returns a primitive string literal. s2 will have the same members as s1 because they are both the same type.
However
var s3 = new String("1234");
Will create an object of type String rather than a primitive string literal. This does have different members and is of type object.

Same thing!
var s1 = 1234 + '';
var s2 = String(1234);
typeof s1 //string
typeof s2 //string

Both will behave the same way.
Also, there is a nice explanation about string primitives vs. objects here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
Distinction between string primitives and String objects
[...] 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. [...]

Javascript allows you to treat primitive values as though they were objects. It does so by doing an on-the-fly coercion of the primitive to an object. That's why, even though primitives have no properties, something like this is perfectly fine:
"abcde".substr(1,3); //bcd
true.valueOf(); //true

Related

Javascript not replacing single character [duplicate]

This question already has answers here:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
Closed 2 years ago.
This code does not work
var x ='hello';
x[2] ='a';
Why doesn't it work?
I am not using the replace() function
In javascript the strings are immutable, you cannot change the string using index.
The string manipulation methods such as trim, slice return new strings.
It doesn't work because of legacy behavior of promoting string values to String object wrappers with the value of the primitive string value.
So for example
"xyz".charAt(0)
is at least notionally evaluated as
(new String("xyz")).charAt(0)
because charAt is a prototype method of String objects and can be applied to a primitive string value in this manner.
The down side is that the promoted String object is never stored anywhere and, even if modified in JavaScript is immediately discarded. This is what is happening in the code posted:
var x ='hello';
x[2] ='a';
is treated as
new String(x)[2] = 'a'
followed by discarding the String object which, incidentally, has a property named 2 with value 'a'.
The general solution to this is to run JavaScript in strict mode, so that any attempt to assign a property to a primitive value which has been promoted to an object wrapper generates an error:
"use strict"
var x ='hello';
x[2] ='a';

How is JavaScript Engine changing the type of Array Object to String

let arr = [1,2,3];
let empArr =[];
for(var i =0; i< arr.length;i++){
console.log('First',typeof empArr);
empArr+=arr[i];
console.log('Second',typeof empArr)
}
The above code gives this output
First object
Second string
First string
Second string
First string
Second string
Could anyone explain how in first iteration type was Array Object then after that it became string.How Javascript Engine works here?
If we run typeof empArr, we will see empArr an object. No matter if we declare it as an array, internally, it is an object. Further, typeof arr[i] shows arr[i] is a number. Therefore, empArr+=arr[i] means we are trying to add an object and a number. Since we are trying to add two different types, it can happen with the help of coercion, implicitly. Coercion means, converting a value of one type to another. JavaScript performs implicit coercion as per the following rules:
operand + operand = result
If at least one operand is an object, it is converted to a primitive
value (string, number or boolean);
After conversion, if at least one operand is string type, the second operand is converted to and the concatenation is executed;
In other case both operands converted to numbers and arithmetic addition is executed.
Note that the primitive value of an array or object is a string.
In our case, empArr is of type object and by rule 1, it is coerced as a string. Now by rule 2, the arr[i] which is a number, is coerced to a string as well and get assigned to empArr.
For more details:
JavaScript addition operator in details
JavaScript type coercion
According to javascript,
typeof [] is "object" ,i.e., every array is actually an object.
if you append anything to a string it will become a string
"1"+1 will equal "11"
It's because of auto type conversion.
The += is a not an array operator, and as the second operand is string - the 1st is converted to string.
Use empArr.push(arr[i])

In Javascript is an String literal an object? [duplicate]

This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Closed 7 years ago.
I'm reading about the difference between String literal and String objects. See
What is the difference between string literals and String objects in JavaScript?
But I'm a bit confuse because there it's explained that you can use methods of the String Objects but technically is a String literal an String Object? I'm not asking if we can use the same methods, only if a String literal is an object. Thanks!
The term "string literal" refers to a syntactic convention for representing string values directly in code.
The code
"Hello Everyone"
is a string literal for a string with 14 characters.
The value represented by a string literal is a string primitive. It is not an object. That's why if you use:
typeof "Hello Everyone"
this will return the value "string", not "object".
JavaScript allows boxing of any string primitive to promote them to string objects under certain circumstances. Attempting to call a method on a string value is one of these circumstances. So if you call:
"Hello Everyone".toUpperCase()
the value represented by this literal will be boxed into a string Object, and the method will be called on that object.
You can check the type of a Javascript variable with the typeof operator. typeof "Hello World" and typeof String("Hello World") both return the type "string".
Also, a strict-equal check "Hello" === String("Hello") returns true, which means that they are not just value-equal but type-equal.
However, typeof new String("Hello World") returns "object".

Convert Object to string and back [duplicate]

This question already has answers here:
Reverse of JSON.stringify?
(8 answers)
Closed 7 years ago.
I need to convert Javascript object to string and then this string back to object.
Objects i get like that:
var Checked = {};
// Hold all checkboxes
$('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {
Checked[name] = [];
}
Checked[name].push($el.val());
});
I know how to do this with array by using join and split, but how to be with objects?
Now how to convert this object to string?
How to get back this string to object?
Here you are:
var object = {
"1": [1, 2, {
3: "3"
}]
};
var str = JSON.stringify(object);
console.log(str);
var obj = JSON.parse(str);
console.log(obj["1"][2][3]);
Hope this helps.
The JSON.parse() method parses a string as a JSON object, optionally transforming the value produced by parsing.
Syntax
JSON.parse(text[, reviver])
Parameters
text
The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver Optional
If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Returns
Returns the Object corresponding to the given JSON text.
Throws
Throws a SyntaxError exception if the string to parse is not valid JSON.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
Syntax
JSON.stringify(value[, replacer[, space]])
Parameters
value
The value to convert to a JSON string.
replacer (Optional)
A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space (Optional)
A String or Number object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 if it's larger than that. Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
Source:
JSON.parse()
JSON.stringify()
var obj = { x: 5, y: 6 };
var a = JSON.stringify(obj);
console.log(typeof a);
console.log( a);
var b = $.parseJSON(a);
console.log(typeof b);
console.log( b);

JavaScript parentheses converts primitive type to object

If numbers are primitive types, why I can do:
> (12345).toString()
"12345"
Is the parenthesis converting the primitive type to a Number?
No, the parentheses are just letting the parser understand that the . is not a decimal point.
12345 .toString() will also work.
Primitive numbers implicitly converted to Numbers whenever you access their properties, but the objects are temporary and immediately lost. For example:
var foo = 5;
foo.bar = "something";
console.log(foo.bar); // undefined
Same goes for strings and booleans.
Actually, 1 .toString() works as well.
>>> typeof(Number(1)) === typeof(1)
true
>>> var a=1; a.toString()
"1"
It's the parser: 1.x expects x to be a digit.
>>> 1.toString()
SyntaxError: identifier starts immediately after numeric literal
[Break On This Error]
You can find further explanation here
If primitives have no properties, why does "abc".length return a
value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object
in order to access the property length. The string object is only used
for a fraction of second after which it is sacrificed to the Gods of
garbage collection – but in the spirit of the TV discovery shows, we
will trap the elusive creature and preserve it for further analysis…

Categories