This question already has answers here:
What's the point of new String("x") in JavaScript?
(9 answers)
Closed 7 years ago.
I'm very confused about what the wrapper objects for primitives. For example, a string primitive and a string created with the string wrapper object.
var a = "aaaa";
var b = new String("bbbb");
console.log(a.toUpperCase()); // AAAA
console.log(b.toUpperCase()); // BBBB
console.log(typeof a); // string
console.log(typeof b); // object
Both give access to String.prototype methods, and seem to act just like a string literal. But one is not a string, it's an object. What is the practical difference between a and b? Why would I create a string using new String()?
A primitive string is not an object. An object string is an object.
Basically, that means:
Object strings are compared by reference, not by the string they contain
"aaa" === "aaa"; // true
new String("aaa") === new String("aaa"); // false
Object strings can store properties.
function addProperty(o) {
o.foo = 'bar'; // Set a property
return o.foo; // Retrieve the value
}
addProperty("aaa"); // undefined
addProperty(new String("aaa")); // "bar"
Related
In JavaScript is there any difference between using String() and new String()?
console.log(String('word')); // word
console.log(new String('word')); // word
Using the String() constructor without new gives you the string (primitive) value of the passed parameter. It's like boxing the parameter in a native object if necessary (like a Number or Boolean), and then calling .toString() on it. (Of course if you pass a plain object reference it just calls .toString() on that.)
Calling new String(something) makes a String instance object.
The results look the same via console.log() because it'll just extract the primitive string from the String instance you pass to it.
So: just plain String() returns a string primitive. new String(xyz) returns an object constructed by the String constructor.
It's rarely necessary to explicitly construct a String instance.
String() returns a string primitive and new String() returns a Object String. This has some real consequences for your code.
Using String() returns 'true' with other primitives both with == and === operator.
Using String() gives you a primitive so it cannot use the "instanceOf" method to check its type. You can check only value type with "typeof" operator
Using new String() with "instanceOf" method with String or Object prototypes - both assert to true.
Using new String() will return 'true' with string primitives only by calling valueOf() method. String() has also this method and returns true when compared to string of the same value.
Using new String() allows you to add some other properties and methods to the Object to allow more complex behaviour.
From my coding experience you should avoid using new String() if you have no need for adding special methods to your String Object.
var x = String('word');
console.log(typeof x); // "string"
var y = new String('word');
console.log(typeof y); // "object"
// compare two objects !!!
console.log(new String('') === new String('')) // false!!!
// compare with string primitive
console.log('' == String('')) // true
console.log('' === String('')) // true
//compare with string Object
console.log('' == new String('')) // true
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
console.log('' === new String('')) // false !!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// instance of behavior
console.log(x instanceof String); // false
console.log(x instanceof Object); // false
// please note that only new String() is a instanceOf Object and String
console.log(y instanceof String); // true
console.log(y instanceof Object); // true
//valueOf behavior
console.log('word' == x.valueOf()); // true
console.log('word' === x.valueOf()); // true
console.log('word' == y.valueOf()); // true
console.log('word' === y.valueOf()); // true
//create smart string
var superString = new String('Voice')
superString.powerful = 'POWERFUL'
String.prototype.shout = function () {
return `${this.powerful} ${this.toUpperCase()}`
};
console.log(superString.shout()) //"POWERFUL VOICE"
Strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
Strings created with new String() (constructor mode) is an object and can store property in them.
Demonstrating the difference:
var strPrimitive = String('word');
strPrimitive.prop = "bar";
console.log(strPrimitive.prop); // undefined
var strObject = new String('word');
strObject.prop = "bar";
console.log(strObject.prop); // bar
Here is an example in addition to the good answers already provided:
var x = String('word');
console.log(typeof x); // "string"
var y = new String('word');
console.log(typeof y); // "object"
The exact answer to your question is here in the documentation.
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.
Generally it's not recommended to use constructor functions (i.e. using new keyword) because it can lead to unpredictable results.
For example:
if (new Number(0)) { //
console.log('It will be executed because object always treated as TRUE in logical contexts. If you want to treat 0 as falsy value then use Number(0)')
}
Also, as mentioned above, there is another potential problem:
typeof 0; // number
typeof Number(0) // number
typeof new Number(0) // object
This question already has answers here:
Map vs Object in JavaScript
(15 answers)
Closed 2 years ago.
let m = new Map();
let obj = {};
let keyString = 'a string';
let keyObj = {};
let keyFunc = function() {};
obj[keyObj] = 'object inside object as keys!';
obj[keyFunc] = function() {}
m.set(keyObj, 'object');
m.set(keyFunc, 'function');
console.log(typeof obj[keyObj]); // type = string
console.log(typeof obj[keyFunc]); // type = function
console.log(typeof m.get(keyObj)); // type = string
console.log(typeof m.get(keyFunc)); // type = string
console.log(m.get(keyObj)) // object
console.log(m.get(keyFunc)) // function
Then what is difference between map and object?
map also converts the keys type to string.
Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity.
Object follows the same concept as that of map i.e. using key-value pair for storing data. But there are slight differences which makes map a better performer in certain situations.
Few basic differences are as follows:
In Object, the data-type of the key-field is restricted to integer,
strings, and symbols. Whereas in Map, the key-field can be of any
data-type (integer, an array, even an object!)
In the Map, the original order of elements is preserved. This is not
true in case of objects.
The Map is an instance of an object but the vice-versa is not true.
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
I have a global object with various properties whose values are strings. When a user types a string into an HTML input, I'm using javascript to assign that string to a variable. I need to convert that string to a property name and return the string associated with that property.
For example:
myglobalobject = {
propertyname : "String value to be returned."
}
function GetInput(){
mystring = document.getElementById('input').value;
myproperty = convertstringToProperty(str); //This is where I need a solution
return myglobalobject.myproperty;
}
Just use a computed property:
return myglobalobject[mystring];
This is a generalization of the fact that property accesses using dot notation are the same as accessing with brackets and a string literal:
obj.prop === obj["prop"];
So when you have something that isn't a string literal, just use the bracket notation.
Well, properties can be accessed with, you guess it, a string:
const myObject = {
property1: 0,
property2: 1,
};
const inputFromUser = 'property1';
console.log(myObject[inputFromUser]);
You don't even need a function:
var myglobalobject = {
propertyname : "String value to be returned."
}
function GetInput(){
mystring = 'anotherKey';
return myglobalobject[mystring] = undefined;
}
GetInput()
console.log(myglobalobject)
This question already has an answer here:
Why is my JavaScript hoisted local variable returning undefined but the hoisted global variable is returning blank? [duplicate]
(1 answer)
Closed 6 years ago.
var name = new String("green");
console.log(name instanceof String);//returns false
var color= new String("green");
console.log(color instanceof String);//returns true
Here the first one is returning false and the second one is returning true,what is the reason if i use variable as name it showing false
and are there are any variables like name which throws error as happened with variable name
Since name is reserved keywrd in javascript (not really reserved but global object), it directly points to window.name
you can try _name and it will work
var _name = new String("green");
console.log(_name instanceof String);//returns true
This is because you are trying to overwrite the global name variable, which has a setter that automatically converts anything you assign to it to a string (new String creates a String object, which is not the same as a string).
The solution: use a different variable name or properly scope your variables.
console.log(typeof name); // string
var name = new String("green");
console.log(typeof name); // still string
var color = new String("green");
console.log(typeof color); // object
// create new scope
function myFunction() {
var name = new String("green");
console.log(typeof name); // object
var color = new String("green");
console.log(typeof color); // object
}
myFunction();
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
In the first case it checks the prototype chain find it undefined and return false. This is not only with name but following example will also return false
var simpleStr = 'This is a simple string';
console.log(simpleStr instanceof String);
An alternative way is to test it using typeof or constructor
The same example will return true for the following case
var simpleStr = 'This is a simple string';
simpleStr .constructor == String
For your example also if you do
var name = new String("green");
name .constructor == String
it will return true
This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Closed 9 years ago.
What is the difference between creating a string object like this
var txt = new String("Hello World");
and this
var txt = "Heloo World";
First of all let's bust some myths. String literal is not a syntactic sugar.
> var txt = new String("Hello World");
> typeof x
"string"
> var txt2 = "Hello World";
> typeof txt2
"object"
As you can see these two things are of different type. Even more: one of them is object and the second is not. This has a practical consequence, like:
> new String("Hello World") == new String("Hello World")
false
> "Hello World" == "Hello World"
true
Another difference is that primitives are passed by value while objects by reference. This might save some memory if you are passing around lots of big strings. However both objects and literals are immutable so it really isn't a big deal (why would you pass lots of big strings if you're not going to modify them?).
Also you can add attributes to objects while you can't add them to primitive types. But that's not 100% true. You can add an attribute to the prototype of a primitive. Note that both literals and objects have the same prototype:
> String.prototype.test = 11;
> var x = new String("x");
> x.test;
11
> var y = "x":
> y.test;
11
There's very little practical use for String objects as created by new String("foo"). The only advantage a String object has over a primitive string value is that as an object it can store properties:
var str = "foo";
str.prop = "bar";
alert(str.prop); // undefined
var str = new String("foo");
str.prop = "bar";
alert(str.prop); // "bar"
Hope this helps..
The String constructor function returns an object of type String. Usually, you want a literal string value, because strictly comparing an object to a literal will always return false.
One is a string primitive and the other is a String object.
The advantage of String object over string primitive is that it can store properties
var x = "foobar"
x.y = "hello"
console.log(x.hello) /* Undefinded*/
var z = new String("foobar")
z.y = "hello"
console.log(z.y) /* hello*/
typeof x = "string"
typeof z = object.
also
x==z //true
x===z // false
Nothing much but beware of this,
var s = new String('A');
var s1 = String('A');
var s2 = 'A';
console.log(s === 'A');//fasle -- since type is Object
console.log(s1 === 'A');//true
console.log(s2 === 'A');//true
var txt = "Heloo World";
here 'txt' is a primitive data type. It has no methods, it is nothing more than a pointer to a raw data memory reference, which explains the much faster random access speed.
var txt = new String("Hello World");
If you use new, you're explicitly stating that you want to create an instance of an Object. Therefore, new String is producing an Object wrapping the String primitive, which means any action on it involves an extra layer of work.
The first returns a String object, the second returns a string.
typeof txt; //object
typeof txt2; //string
While they may act similar, txt !== txt2
The primitive data types are:
String
Number
Boolean
If you using:
var txt = "Heloo World";
this is primitive type data type alert(typeof txt); will give you string type.
In JavaScript all variable can be of object type, for each primitive their is a Object type.
var txt = new String("Heloo World");
here typeof will give you object.
For difference see jsfiddle
var str="text";
alert(typeof str); //string
var str2="text";
alert(str === str2); //true
str = new String("text changed");
alert(typeof str); //object
var str2 = new String("text changed");
alert(str === str2); //false
Nothing, really. In the first example you call the constructor of class String and put as a parameter the body of the string, where as in the second example it is done automatically at the interpretation phase.
So basically the second is syntactic sugar, where as the first isn't.
There is no difference in the functionality.