Types
JavaScript values fall into two categories: primitives and complex types. Understanding how each is accessed determines how changes to one variable affect others.1.1 Primitives
When you access a primitive type, you work directly on its value. The primitive types are:stringnumberbooleannullundefinedsymbolbigint
bar holds a copy of the value, reassigning bar has no effect on foo.
1.2 Complex types
When you access a complex type, you work on a reference to its value. The complex types are:objectarrayfunction
foo and bar point to the same array in memory. Mutating through either reference affects both.
References
Useconst by default and let only when reassignment is necessary. Avoid var entirely.
2.1 Prefer const
Use const for all of your references; avoid using var.
eslint: prefer-const, no-const-assign
Ensuring references can’t be reassigned helps prevent bugs and makes code easier to reason about.
- Good
- Bad
2.2 Use let for reassignable references
If you must reassign a reference, use let instead of var.
eslint: no-var
letis block-scoped rather than function-scoped likevar. This makes its behavior more predictable and avoids accidental leaks.
- Good
- Bad
2.3 Block scope vs. function scope
Bothlet and const are block-scoped, whereas var is function-scoped.
In the example above,
a and b are block-scoped — accessing them outside the block throws a ReferenceError. c is function-scoped via var, so it leaks out of the block and remains accessible.