JavaScript Variables


JavaScript Variables

In this tutorial, we will learn about variables in JavaScript. We will cover the basics of declaring and using variables, including naming conventions.


What are Variables

Variables in JavaScript are used to store data values that can be manipulated during program execution. They are dynamically typed, meaning the data type of a variable can change at runtime.


Naming Variables

When naming variables in JavaScript, follow these conventions:

  • Start with a letter, underscore (_), or dollar sign ($).
  • Subsequent characters can include letters, digits, underscores, or dollar signs.
  • Avoid using reserved keywords as variable names.
  • Use camelCase or snake_case naming conventions for readability.

Syntax

The syntax to declare variables in JavaScript is:

var variable_name;


Variable storing Integer Value

  1. Declare an integer variable named num.
  2. Assign a value of 10 to the variable.
  3. Print the value of the variable.

JavaScript Program

// Declare and initialize an integer variable
var num = 10;
// Print the value of the variable
console.log('The value of num is: ' + num);

Output

The value of num is: 10


Variable storing String Value

  1. Declare a string variable named name.
  2. Assign the value 'John' to the variable.
  3. Print the value of the variable.

JavaScript Program

// Declare and initialize a string variable
var name = 'John';
// Print the value of the variable
console.log('The value of name is: ' + name);

Output

The value of name is: John


Variable storing Boolean Value

  1. Declare a boolean variable named isTrue.
  2. Assign the value true to the variable.
  3. Print the value of the variable.

JavaScript Program

// Declare and initialize a boolean variable
var isTrue = true;
// Print the value of the variable
console.log('The value of isTrue is: ' + isTrue);

Output

The value of isTrue is: true