JavaScript

Last Updated: 12/14/2022

Variables

  • In programming, you use a variable to store data temporarily in the computer's memory. Your data is stored somewhere in the memory, and you give that memory location a name. Using this name, you can read the data from the given location in the future.
  • Think of the boxes you use to organize your stuff. You put your stuff in various boxes and put a label on each box. With this, you can easily find your stuff. A variable is like a box. what you put inside the box is the value/data that you assign to a variable and the label that you put on the box is the name of our variable.
  • In simple terms variables are containers for storing data.

Declare Variables

  • You can declare variables using var, let, const keyword.
  • Before ES6, var keyword was used to declare a variable, but there are issues with var
  • From ES6, the best practice is to use the let keyword to declare a variable.
  • Give the variable a name or identifier
let name;
name = "ganesh"
  • By default, variable declared without a value will have the value undefined.
  • You can initialize the variable with a value during declaration
let name = "ganesh";

Identifiers

  • All JavaScript variables must be identified with unique names. These unique names are called identifiers.
  • The general rules for constructing names for variables (unique identifiers) are:
    • Can contain letters, digits, underscores, and dollar signs.
    • Must begin with a letter.
    • Cannot start with a number.
    • Cannot contain a space or hyphen
    • Are case sensitive (firstName and FirstName are different variables).
    • Reserved words (like JavaScript keywords) cannot be used.

Declare Multiple Variables

  • You can declare multiple variables in one statement separated by a comma.
let firstName, lastName;
let firstName = 'Ganesh', lastName;
let firstName = 'Ganesh', lastName = "Kumar";
  • Always declare each variable in new line
let firstName = "Ganesh";
let lastName = "Kumar";