Home  >  Article  >  Web Front-end  >  Why Can\'t You Add Properties to String Primitives in JavaScript?

Why Can\'t You Add Properties to String Primitives in JavaScript?

DDD
DDDOriginal
2024-10-31 21:36:29633browse

Why Can't You Add Properties to String Primitives in JavaScript?

Why Attempting to Add Properties to String Primitives Fails

In JavaScript, attempts to add properties to string primitives, such as the code below, will be ineffective:

<code class="javascript">var test = "test";
test.test = "test inner";
console.log(test.test); // Output: undefined</code>

Types in JavaScript

To understand this issue, one must grasp the concept of types in JavaScript. There are eight types in JavaScript:

  • Seven primitive types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol
  • One non-primitive type: Object

Primitive values (e.g., strings) cannot possess properties, while objects can.

Property Assignment

When assigning a property to a variable, such as:

<code class="javascript">foo.bar = 'abc';</code>

The result depends on the value of foo:

  • Undefined or Null: Error
  • Object: Creates or assigns to the named property 'bar'
  • Other types (e.g., String): TypeError in strict mode (no-op in loose mode)

Solution for Sorting Dates

In your specific case, since dates are stored as strings, one workaround for sorting dates is to use a custom comparison function in your sorting algorithm that assumes dates are always stored in the same format. This custom function can perform a date-aware comparison based on the format of the date strings.

The above is the detailed content of Why Can\'t You Add Properties to String Primitives in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn