Variable
- Declarations
- Automatic semicolon insertion (ASI)
- Dynamic Type
- Weak Typing
- Case Sensitive
- Identifier Pattern
- Multiple Declaration
- Hoisting
Declarations
Keyword | Scope | Reassignable | Mutable | Temporal Dead Zone |
---|---|---|---|---|
const |
Block | No | Yes* | Yes |
let |
Block | Yes | Yes | Yes |
var |
Function | Yes | Yes | No |
Other languages
C:
int number = 10;
Python:
number = 10
Keyword
var number = 10;
console.log(number); //=> 10
let number = 10;
console.log(number); //=> 10
const number = 10;
console.log(number); //=> 10
Reassignable
var number;
number = 10;
number = 100;
console.log(number); //=> 100
let number;
number = 10;
number = 100;
console.log(number); //=> 100
const number; // SyntaxError
const number = 10;
number = 100; // TypeError
const numbers = [];
numbers.push(1);
console.log(numbers); //=> [ 1 ]
Reference:
- Declarations | MDN
- Variable declaration: var, const, let | Modern JavaScript Cheatsheet
- Variable | You Don’t Know JS: Up & Going
Automatic semicolon insertion (ASI)
const number = 10
console.log(number) //=> 10
Dynamic Type
let variable = 10;
console.log(variable); //=> 10
console.log(typeof variable); //=> number
variable = 'fulano';
console.log(variable); //=> 'fulano'
console.log(typeof variable); //=> string
Weak Typing
const x = 10;
const y = '5';
console.log(x - y); //=> 5
Case Sensitive
const number = 8;
const Number = 80;
const NUMBER = 800;
Identifier Pattern
const 0number //=> SyntaxError (^\W)
const %number //=> SyntaxError (^\W)
const var //=> SyntaxError (keyword)
const function //=> SyntaxError (keyword)
const number
const _number
const $number
Reference:
Multiple Declaration
let x, y, z;
console.log(x); //=> undefined
console.log(y); //=> undefined
console.log(z); //=> undefined
const a = 1,
b = 2,
c = 3;
console.log(a); //=> 1
console.log(b); //=> 2
console.log(c); //=> 3
Hoisting
name = 'fulano';
console.log(name); //=> 'fulano'
console.log(name); //=> ReferenceError: name is not defined
name = 10;
console.log(name); //=> undefined
var name = 10;
console.log(name); //=> ReferenceError: name is not defined
let name = 10;
Reference: