Index
Declaring Variables Examples


We use 'const' and 'let' to declare variables. They replace the older keyword 'var'. These examples will show how.

Js will allow these keywords to be used somewhat interchangably, but we will go over the suggested usage (coding conventions used by js coders). Even the older 'var' keyword is allowed, but discouraged by common convention.

We use the prn helper function in this playground lab.

The keyword 'const' is uses when the variable will not be assigned a new value.

const a = 10;
prn("a: " + a);

//not allowed
//a = 20;
The keyword 'let' is uses when the variable will be assigned a new value.

let a;

a = 10;
prn("a: " + a);

//allowed
a = 20;
prn("a: " + a);
Depending on our logic, we may prefer to declare all variables at the top of a method, to lighten the logic code. We would use 'let'.

let a, b, sum;
a = 10;
b = 2;
sum = a + b;
prn('sum: ' + (a + b));
This is to contrast the "declarations first" style in the previous snippet. Simple calcs have been used for the example purposes.

const a = 10;
const b = 2;
const sum = a + b;
prn('sum: ' + (a + b));

More Example Sources


Here are a couple (among many more) online related example sources: