Naming variables
Valid names for variables can use any letter, upper or lowercase, a dollar sign $ and an underscore _. Numbers can also be used ONLY if they’re NOT the first character of a name.
Reserved words
The following words are reserved in JavaScript meaning you can’t use them for variable names:
- abstract
- arguments
- await
- boolean
- break
- byte
- case
- catch
- char
- class
- const
- continue
- debugger
- default
- delete
- do
- double
- else
- enum
- eval
- export
- extends
- false
- final
- finally
- float
- for
- function
- goto
- if
- implements
- import
- in
- instanceof
- int
- interface
- let
- long
- native
- new
- null
- package
- private
- protected
- public
- return
- short
- static
- super
- switch
- synchronized
- this
- throw
- throws
- transient
- true
- try
- typeof
- var
- void
- volatile
- while
- with
- yield
var, let and const
Variable are either var, let or const.
Generally don’t use var which is scoped globally and could cause problems if you have another variable with the same name.
ES6 aka ES 2015 added let and const
Let
let can have it’s value changed.
let age = 31
console.log('age'); // will give 31
age = 12
console.log('age'); // will now give 12
With const in the first line instead of let this would cause an error message.
const cannot be reassigned.
General usage
Always use const unless you know your variable will be reassigned.
Unassigned
let score;
score = 10;
You cannot do this with const
Primatives
- strings - in single or double quotes.
- numbers - any integer or decimal
- booleans -
trueorfalse - null - an empty variable
- undefined - when initialised but no value
let x; - symbols (added in ES6)
To get the type use typeof
console.log(typeof varName);
If typeof returns the value of object it is wrong and should be considered as null.
Concatenation
Joining variables of different types.
let age = 13
let name = 'John Bloggs'
// the older way
console.log('My name is ' + name + ' and I am' + age + 'years old');
// the newer ES6 way uses backticks
// (template literals) like this
console.log(`My name is ${name} and I am ${age} years old`);