JavaScript Variables

What are Variables?

Variables are used to store data that can be referenced and manipulated in a program. They act as containers for storing information. In JavaScript, you can declare variables using var, let, or const.

Tutorials dojo strip

Using var

The var keyword is used to declare a variable, which can be reassigned later and has function scope.

JavaScript

Using let

The let keyword is used to declare a block-scoped variable, which can be reassigned.

JavaScript

Using const

The const keyword is used to declare a block-scoped variable that cannot be reassigned.

JavaScript

Variable Naming Rules

  • Variable names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter, underscore, or dollar sign.
  • Variable names are case-sensitive (myVar and myvar are different).
  • Reserved words (like let, class, return, and function) cannot be used as variable names.

Initializing Variables

Variables can be declared without being assigned a value. In such cases, they are initialized with the value undefined.

JavaScript

Reassigning Variables

Variables declared with var or let can be reassigned new values.

JavaScript

JavaScript Variables Example Code

Explanation of Code:

  • Using var: Declares a variable name and assigns it a value of “John”.
  • Using let: Declares a variable age and assigns it a value of 30, which is later updated to 31.
  • Using const: Declares a constant variable PI and assigns it a value of 3.14.
HTML

JavaScript Labs

Tutorials dojo strip