javascript
  1. javascript-variable

JavaScript Variables

Variables are memory locations for storing data values in a computer program. In JavaScript, variables are used to store data values of different data types. The value of a variable can be changed during the execution of a program. In this tutorial, we will discuss the syntax, example, output, explanation, use, important points and summary of JavaScript variables.

Syntax

The syntax for declaring a variable in JavaScript is:

var variable_name;

Here var is a keyword, variable_name is the name of the variable and the semicolon ; ends the statement.

A variable can also be initialized with a value at the time of declaration as shown below:

var variable_name = value;

Here, value can be any valid data type in JavaScript.

Example

Here is an example of how to declare and initialize variables in JavaScript:

var message;
message = "Hello World";
var num = 10;

In this example, we have declared a variable message without initializing it. Then we assigned the string value "Hello World" to the variable message. We have also declared and initialized a variable num with the integer value 10.

Output

We can output the values of variables to the console using the console.log() method as shown below:

console.log(message);
console.log(num);

This will output the values of the variables message and num to the console respectively.

Explanation

In JavaScript, variables are not bound to a specific data type, as the data type is determined automatically by the value assigned to it. JavaScript has six primitive data types:

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol

Besides these primitive data types, JavaScript also supports two complex data types:

  • Object
  • Function

Variable names must conform to the following rules:

  • Variable names can only contain letters, numbers, dollar signs ($) or underscores (_)
  • Variable names must begin with a letter, $ or _
  • Variable names are case sensitive (firstName and Firstname are two different variables)
  • Variable names should be descriptive and meaningful

Use

Variables can be used in many ways in JavaScript, including:

  • Storing information that may change during the execution of a program
  • Performing calculations
  • Iterating over collections of data
  • Storing results of user input or database queries

Important Points

  • A variable is declared using the var keyword
  • A variable can store any valid data type in JavaScript
  • Variable names are case sensitive and should be descriptive

Summary

In this tutorial, we covered the syntax, example, output, explanation, use, important points and summary of JavaScript variables. Understanding how to declare and use variables is an essential part of learning JavaScript.

Published on: