Skip to content

Commit aa43b08

Browse files
Redsandrogajus
authored andcommitted
docs: add a note about use of String vs string (#31)
* Taking my novel to a different publisher * Update check-types.md
1 parent 3cc6b0e commit aa43b08

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

.README/rules/check-types.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,36 @@ Date
1414
RegExp
1515
```
1616

17+
#### Why not capital case everything?
18+
19+
Why are `boolean`, `number` and `string` exempt from starting with a capital letter? Let's take `string` as an example. In Javascript, everything is an object. The string Object has prototypes for string functions such as `.toUpperCase()`.
20+
21+
Fortunately we don't have to write `new String()` everywhere in our code. Javascript will automatically wrap string primitives into string Objects when we're applying a string function to a string primitive. This way the memory footprint is a tiny little bit smaller, and the [GC](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) has less work to do.
22+
23+
So in a sense, there two types of strings in Javascript; `{string}` literals, also called primitives and `{String}` Objects. We use the primitives because it's easier to write and uses less memory. `{String}` and `{string}` are technically both valid, but they are not the same.
24+
25+
```js
26+
new String('lard') // String {0: "l", 1: "a", 2: "r", 3: "d", length: 4}
27+
'lard' // "lard"
28+
new String('lard') === 'lard' // false
29+
```
30+
31+
To make things more confusing, there are also object literals and object Objects. But object literals are still static Objects and object Objects are instantiated Objects. So an object primitive is still an object Object.
32+
33+
Basically, for primitives, we want to define the type as a primitive, because that's what we use in 99.9% of cases. For everything else, we use the type rather than the primitive. Otherwise it would all just be `{object}`.
34+
35+
In short: It's not about consistency, rather about the 99.9% use case.
36+
37+
type name | `typeof` | check-types | testcase
38+
--|--|--|--
39+
**Object** | object | **Object** | `({}) instanceof Object` -> `true`
40+
**Array** | object | **Array** | `([]) instanceof Array` -> `true`
41+
**Date** | object | **Date** | `(new Date()) instanceof Date` -> `true`
42+
**RegExp** | object | **RegExp** | `(new RegExp(/.+/)) instanceof RegExp` -> `true`
43+
Boolean | **boolean** | **boolean** | `(true) instanceof Boolean` -> **`false`**
44+
Number | **number** | **number** | `(41) instanceof Number` -> **`false`**
45+
String | **string** | **string** | `("test") instanceof String` -> **`false`**
46+
1747
|||
1848
|---|---|
1949
|Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`|

0 commit comments

Comments
 (0)