1

This is not a real life scenario. I am trying to learn more about strings in js, and came across the following:

var name = new String('sann');

console.log('type of name=' ,typeof name); 
// returns object in nodejs but string in browser
console.log('name instanceof String' ,name instanceof String) 
// returns true in nodejs but false in browser

NodeJS output was in line with my expectation, I am puzzled by the browser output.
What is the reason for this difference in behaviour ?

1
  • I tested on both chrome and firexfox Commented Jun 24, 2018 at 19:10

2 Answers 2

2

Both are right.

The spec says (emphasis mine):

The String constructor is the %String% intrinsic object and the initial value of the String property of the global object. When called as a constructor it creates and initializes a new String object. When String is called as a function rather than as a constructor, it performs a type conversion.

So new String(value) returns a String object rather that a primitive.

In a browser anyway, the global window object has a property called name, whose setter automatically converts the supplied value into a string.

The same snippet, if wrapped into a function call, reports name to be of type object, as expected.

(() =>
{
    var name = new String('sann');

    console.log('type of name', typeof name);
    console.log('name instanceof String', name instanceof String);
}
)();

In Node.js the global object does not have that property, and so name is treated as a plain value.

Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is about window object in the browser, which does not exist in nodejs. You can also read this answer which explains your problem: https://stackoverflow.com/a/36408348/3554534

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.