Javascript: Variables and Scoping
đ Wiki page | đ Last updated: Feb 9, 2022Defining variables and scoping can be confusing in Javascript, but if you use only let
and const
(ES6+) to declare variables, things will work as expected:
With let
, we're defining a normal, block scoped variables (which you're probably familiar with from other languages).
let answer = 42
console.log(answer) // 42
const
is the same as let
, only you can't redefine the variable (but you can still mutate it (if the variable is mutable)):
const answer = 42
answer = 43 // you can't do this - Uncaught TypeError: Assignment to constant variable.
Before ES6, there were only function function scoped variables (which can be tricky to work with, because they leak out of the current block):
{
var answer = 42
}
console.log(answer) // 42
var
variables are also hoisted to the top and can be used before they are declared:
answer = 42
var answer
console.log(answer) // 42
Never do this:
answer = 42
console.log(answer) // 42
This way, you're defining a global variable (more strictly, a variable on window
or global
object, which have a global scope)
Javascript is dynamically typed language, without any official support for type annotations, but you can document your types in jsdoc comments (which are supported by a lot of tools):
/** @type {MyType} */
var myvar;
There's also a very popular, progressively-typed superset of Javascript, called TypeScript, which makes this a bit less cumbersome (i.e. just var myvar:MyType
), but more on all that later.
Ask me anything / Suggestions
If you find this site useful in any way, please consider supporting it.