Variables

  • The keyword var is used in pre-ES6 versions of JavaScript.

  • In programming, a variable is a container for a value. You can think of variables as little containers for information that live in a computer’s memory. Information stored in variables, such as a username, account number, or even personalized greeting can then be found in memory.

  • Variables also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves.

General rules for naming variables:

  • Variable names cannot start with numbers

  • Variable names are case sensitive, so myName and myname would be different variables.

  • Variable names cannot be the same as keywords. For a comprehensive list of keywords check out MDN's keyword documentation.

  • Variable names should follow Camel Casing format .e.g. myLastVariable (the first word of the variable is always in lowercase and all the following words will be always be in uppercase).

  • Assingment operator = is used to assign certain data type to the variable name.

Creating a variable: var

var myName = 'Arya';
console.log(myName);
// Output: Arya
  • A lot of changes were introduced in the ES6 version of JavaScript in 2015, like let and const, to create or declare, variables.

  • Prior to ES6 only var keyword could be used to declare variables.

Creating a variable: let

  • let keyword was introduced in ES6 in 2015, it signals that the variable can be reassigned a different value.

Example:

let meal = 'Enchiladas';
console.log(meal);	// Output: Enchiladas
meal = 'pizza';		// Reassigning value without creating a variable name
console.log(meal);	// Output: pizza
  • When using let we can declare a variable without assigning the variable a value.

  • In such cases the value is automatically initialized with a value of undefined.

Example:

let price;
console.log(price);		// Output: undefined
price = 350;
console.log(price);		// Output: 350
  • All variables declared with keyword let can be reassigned with new values.

Creating a variable: const

  • const keyword was also introduced in the ES6 version of JavaScript in 2015

  • Just like var and let we can use const to store any value in a variable

Example:

const myName = 'Gilberto';
console.log(myName);		// Output: Gilberto
  • A const variable cannot be reassigned because it is a constant, if tried so will throw an error TypeError

Example:

const entree = 'Enchiladas';
console.log(entree);	// Output: Enchiladas

entree = 'Tacos';		// Output:  TypeError: Assignment to constant variable.

Last updated