When do you need "var"? Can you only use "let" to declare variables?

Hello Forum,

Can p5js variables be declared and used exclusively with “let” or are there instances when you need “var”?

Thank you for your help

let move = 150;
let on = true;  

//or

var move;
var on;   
1 Like

Hello,

There is a video here discussing this topic:

:)

2 Likes

Very helpful. ‘Let’ it is!

1 Like

There are very few edge cases for var.

I guess the most important 1 is when we need to create some global namespace object across multiple JS files like in the example below:

If we had declared variable sketches w/ let in place of var, the code above would crash, b/c once a variable is declared w/ let it can’t be redeclared anymore within the same scope.

BtW, JS got 6 keywords for declaring variables:

  1. var
  2. function
  3. let
  4. const
  5. class
  6. import

Among those 6, only the keywords var & function allow redeclaration and are function-scoped (hoist).

2 Likes

Variables declared by “var” keyword are scoped to the immediate function body (function scope) while “let” variables are scoped to the immediate enclosing block denoted by {…} (block scope).

Variable declared with var keyword can be re-declared and updated in the same scope while variable declared with let keyword can be updated but not re-declared.

Variables defined with let are hoisted to the top of the block , but not initialized. This means that the block of code is aware of the variable, but it cannot be used until it has been declared. So, using a let variable before it is declared will result in a ReferenceError.

AFAIK all function’s parameters plus its local variables are “hoisted” not only in JavaScript but any programming language!

That is, when a function is invoked, a stack memory block is allocated w/ enough room for all parameters & variables that function needs to operate.

Therefore, everything is already “hoisted” even before the function’s 1st line code is executed.

If a local variable is prohibited of being accessed before its declaring statement line it’s effectively moot whether an early block of code is “aware” of its existence!

In JS only those variables declared w/ var or function have their access permitted anywhere within their function’s body, even though variables declared using other keywords pre-exist as well.

Don’t forget keyword function both hoists & initializes the variable it declares w/ a function reference, while var hoists but initializes later.