Variables are named values and can store any type of JavaScript value.
var name = 'Adithya';
JavaScript is a dynamically typed language unlike C, C++, Java, Go etc...
var number = '123'; number = 123; // this works 😲
Declaring variables in JavaScript: let
, const
and var
1. var
Prior to ECMAScript 2015, variables in JS were declared solely using the var
keyword.
var name;
Do's and Don'ts
- Names should begin with lowercase string.
- Names cannot contain symbols or begin with symbols.
- Names cannot begin with a number.
- Names can contain a mix of uppercase strings, lowercase strings, and numbers.
2. let
Introduced in ES6
, let
has similarities to var
but has some scope constraints unlike var
.
It is constrained in whatever scope it was declared in.
if(true) { let x = 1; console.log(x); // 1 } console.log(x); // Reference Error: x is not defined 😭
Unlike var
, let
can't be used to re-declare variables
var x = 1; var x = 3; // this works 😐 let y = 1; let y = 3; // this doesn't work 🎊
3. const
Also Introduced in ES6
, const
is used to define constants (not really).
const a = 1; a = 2; // Error: Assignment to constant variable
Don't use const
to declare variables
const x; // SyntaxError: missing initializer in const declaration
Loophole in const
const object = { workshop: 'React' }; object.workshop = 'Kubernetes'; // this works
Which to Use?
When declaring variables, it is good practice to avoid using var
.
Always lean towards let
or const
based on the rules below.
- Use
let
when we will be changing the value of the variable - Use
const
when you are sure that variable won't change
Using both let
and const
will keep our variables in the right scope and make our code easier to manage.