29 Feb, 2020

JavaScript Variables

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.