Skip to content

Instantly share code, notes, and snippets.

@meetzaveri
Last active March 13, 2018 08:33
Show Gist options
  • Save meetzaveri/27a06bc033312c163daede7f66484c68 to your computer and use it in GitHub Desktop.
Save meetzaveri/27a06bc033312c163daede7f66484c68 to your computer and use it in GitHub Desktop.

Values

It's easy to think that function would be a top-level built-in type in JS, especially given this behavior of the typeof operator. However, if you read the spec, you'll see it's actually a "subtype" of object. Specifically, a function is referred to as a "callable object" -- an object that has an internal [[Call]] property that allows it to be invoked.

The fact that functions are actually objects is quite useful. Most importantly, they can have properties. For example:

function a(b,c) {
	/* .. */
}

The function object has a length property set to the number of formal parameters it is declared with.

a.length; // 2 Since you declared the function with two formal named parameters (b and c), the "length of the function" is 2.

Values as Types

In JavaScript, variables don't have types -- values have types. Variables can hold any value, at any time.

Another way to think about JS types is that JS doesn't have "type enforcement," in that the engine doesn't insist that a variable always holds values of the same initial type that it starts out with. A variable can, in one assignment statement, hold a string, and in the next hold a number, and so on.

The value 42 has an intrinsic type of number, and its type cannot be changed. Another value, like "42" with the string type, can be created from the number value 42 through a process called coercion (see Chapter 4).

If you use typeof against a variable, it's not asking "what's the type of the variable?" as it may seem, since JS variables have no types. Instead, it's asking "what's the type of the value in the variable?"

var a = 42;
typeof a; // "number"

a = true;
typeof a; // "boolean"
The typeof operator always returns a string. So:

typeof typeof 42; // "string"
The first typeof 42 returns "number", and typeof "number" is "string".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment