开发者

Is String a Primitive type or Object in Javascript?

开发者 https://www.devze.com 2023-04-11 09:20 出处:网络
Is String a Primitive type or Object in Javascript? Source says Undefined, Null, Boolean, Number and String are all primitive types开发者_如何学JAVA in Javascript. But it says String is an Object too.

Is String a Primitive type or Object in Javascript? Source says Undefined, Null, Boolean, Number and String are all primitive types开发者_如何学JAVA in Javascript. But it says String is an Object too. I'm confused. Can someone please explain?

Thank you in advance ;-)


Actually the same answer applies to: strings, numbers, booleans. These types have their primitive and object version which are coerced in the application runtime, under the hood (without your knowledge).

Coercion

JavaScript is weakly typed. This means that whenever your code wants to perform an operation with invalid datatypes (such as add a string to a number), JavaScript will try to find a best match for this scenario.

This mechanism is also called, as mentioned above, coercion.

Primitives and Properties

You can find following code confusing:

> "hello world".length
11

because "hello world" is a string literal, i.e. a primitive. And we know that primitives don't have properties. All is right.

So how does that work? Coercion - the primitive is wrapped with an object (coerced) for just a tiny fraction of time, the property of the object is used and immediately the object gets disposed.

Coercion working both ways

So primitives are casted with their object wrapping versions - but it also works the other way round as well. Consider following code:

> String("hello ") + String("world")
"hello world"

> Number(2) + 3
5

The objects are down-casted to their primitive versions in order to accomplish the operation.

Read this brilliant explanation to learn more.


Both.

There is a String object and there are string literals.

You can call any string method on a literal and you can call any string method on a string object.

The major difference is that a string object generates a new object so new String("foo") !== new String("foo")

That and a String object is type "object" and not "string"

How to check for both?

if(typeof(s) == "string" || s instanceof String){
  //s is a string (literal or object)
}

Credits to @Triynko for the snippet in the comments


JavaScript has both primitive and object Strings.

const foo = "foo"
const bar = new String("bar");
console.log("foo: ", foo);
console.log("bar: ", bar);
console.log("typeof foo: ", typeof foo);
console.log("typeof bar: ", typeof bar);


var a = "string"; 
typeof a    // yields "string" 

var a = new String('string'); 
typeof a   // yields "object" 


To continue the topic of coercion: in most cases, when any string property is accessed (like in the example above: "hello world".length), converting a string primitive to an object is performed implicitly; however in some cases coercion can be explicit, like, for example, if to call Array.prototype functions upon strings, the respective String instance object (NOT a primitive) is passed to an array argument of the callback function. Here is a runnable example:

function test() {
    const str = 'abcdefgh';
    alert(Array.prototype.reduce.call(str, (result, _, i, _str) => {
        if(!i) result.push(`typeof str: ${typeof str}`);
        else if(i === 1) result.push(`typeof _str: ${typeof _str}`);
        else if(i === 2) result.push(`str instanceof String: ${str instanceof String}`);
        else if(i === 3) result.push(`_str instanceof String: ${_str instanceof String}`);
        else if(i === 4) result.push(`_str == str: ${_str == str}`);
        else if(i === 5) result.push(`_str === str: ${_str === str}`);
        else if(i === 6) result.push(`str[${i}]: "${str[i]}", _str[${i}]: "${_str[i]}"`);
        else result.push(`str: "${str}", _str: "${_str}"`);
        return result;
    }, []).join('\n'));
}
<button onclick="test()">Click me to run the test!</button>


This is a very basic utility function that I use all the time

const isString = (s, instance = false) => {
  return typeof s === 'string' || (instance && s instanceof String)
}

const foo = 'lalalalala'
const faa = new String('bababababab')
const fnc = () => {}

console.log(`foo is string primitive: ${isString(foo)}`)
console.log(`faa is string primitive: ${isString(faa)}`)

console.log(`foo is string primitive or object: ${isString(foo, true)}`)
console.log(`faa is string primitive or object: ${isString(faa, true)}`)
console.log(`fnc is string primitive or object: ${isString(fnc, true)}`)

0

精彩评论

暂无评论...
验证码 换一张
取 消