What are variables in JavaScript?

A variable is a named storage location in computer memory that can store a value. In JavaScript, variables are declared using the var keyword.

var myInteger = 5;

In the example above, myInteger is the name of the variable and 5 is the value that is stored in the variable.

You can also initialize a variable when you declare it, like this:

var myInteger = 5, myString = "Hello world!";

In the example above, myInteger is initialized to 5 and myString is initialized to Hello world!.

Variable names can be any valid JavaScript identifier. However, TypeScript will give you an error if you try to assign a value to a variable that has not been declared.

Variable Types

When you declare a variable in TypeScript, you also specify the type of data that the variable can store. The following are some of the more common data types:

  • A boolean data type can store either true or false values.
  • A number data type can store integer or decimal values.
  • A string data type can store characters, such as letters, numbers, and symbols.
  • An object data type can store a collection of key-value pairs.
  • A variable that has not been assigned a value has the type undefined.
  • A variable that has been assigned the value null has the type null.

TypeScript also includes a number of other data types, such as arrays and enums.

JavaScript Code Samples

The following code samples demonstrate how to use variables in JavaScript.

// Declaring Variables
var myInteger = 5;
var myString = "Hello world!";

// Initializing Variables
var myInteger = 5, 
myString = "Hello world!";

// Assigning Values to Variables
myInteger = 5;
myString = "Hello world!";