Chapter 1: Types in JavaScript


ECMA Language Types
ECMA language types are:
- undefined
- null
- Boolean
- string
- Number
- Object
Built-in Types in JavaScript
JavaScript built-in types are:
- null
- undefined
- boolean
- number
- string
- object
- Symbol (added in ES6)
Note: Except object, all are called primitive types.
Whatever value you will see in JS, if you write
typeofbefore that, you will get these types.
Examples:
typeof Symbol(1) // "symbol"
typeof null == "object" // true (Bug!)
Bug: It is not fixed because there are so much web context exist and rely on this bug. Fixing this will create more bugs, so they left it as it is.
js
CopyEdit
typeof function foo(){} // "function"
typeof [1,2] // "object"
Functions in JavaScript
In JS, there is no built-in type as function but it is a subtype of object.
Function is nothing but a callable object.
Internally, it uses [[Call]] property to invoke function.
Note: Each function has length property attached to it that is equal to the number of params.
Example:
js
CopyEdit
function foo(a, b, c) { }
console.log(foo.length) // 3
Same goes with Array!
Values as Types
In JavaScript, variables don’t have types, values have types.
Variables can hold any value at any time.
Note: typeof always returns a string.
undefined vs undeclared
undefined:
- A variable that has been declared in the accessible scope but at the moment has no other value in it.
Example:
js
CopyEdit
var a;
console.log(typeof a); // "undefined"
undeclared:
- If a variable is not declared (not defined yet), and you try to use it, you get Reference Error!
Example:
js
CopyEdit
var b = 42;
console.log(typeof c); // "undefined"
console.log(b = c); // ReferenceError!
Type of undeclared
If you use typeof a where a is not declared yet, you will always get "undefined" without error.
Learn about DEBUG keyword in JS!
Want me to write notes on a course?
Tell me the course, book, or research topic you want covered. If it helps learners, I'll consider adding structured digital notes for it in the garden.
Have a notes collection to feature here?
Do you have open notes you want featured in this digital garden? Let me know — we can collaborate and publish them for learners worldwide.
Reach out on Topmate: topmate.io/aat
Contact to Collaborate