SpinSpire logo

Variable Declarations

Keywords to declare variables in JavaScript are ...

var keyword

Example of var:

var hello = "hello"; // global
function helloFunction() {
var hi = "hello"; // function local
console.log(hi, hello); // this can be done because var "hello" is global
}
console.log(hi,hello); // error: "hi" is not defined
/*
* the reason for this is because "hi" is only
* locally defined in helloFunction
*/

var can be re-declared and updated:

var hi = "hi";
var hi = "hello hi";
hi = "say hello";

The problem with var:

var hi = "hi";
var timesIveSaidHello = 5;
if (timesIveSaidHello > 3) {
var hi = "I'm saying hello now";
}
console.log(hi); //"im saying hello now"

let keyword

let myItem = "banana";
let numberOfItems = 2;
if (numberOfItems > 1) {
let myItem = "I have more than one item";
console.log(myItem);
// Output: "I have more than one item"
}
console.log(myItem);
//Output: myItem is not defined

let can be updated:

// this will work
let banana = "banana";
banana = "new banana";
// this will not work
let banana = "banana";
let banana = "new banana";
let banana = "banana";
if (true) {
let banana = "new banana";
console.log(banana); // output: new banana
}
console.log(banana); // output: banana

const keyword

const hello = "hello";
hello = "now sau hello";
/*
* cannot assign new value to a constant variable
*/

const hello = "say Hi";
const hello = "say Hello instead";
/*
* Error variable hello has already been declared
*/

Hoisting of let, const, and var

An example of hoisting:

console.log(greeter);
var greeter = "say hello";
/*
* javascript interprets the above code as this
*/

var greeter;
console.log(greeter); // greeter is undefined
greeter = "say hello";

In summary