Skip to content

Variable declaration in JavaScript | Example code

  • by

Use the reserved var keyword to declare a variable in JavaScript or you can declare a JavaScript Variable in other ways:

Declare a JavaScript variable with the var or the let keyword:

var name;
let address;

There are some rules while declaring a JavaScript variable (also known as identifiers).

  1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  2. After first letter we can use digits (0 to 9), for example value1.
  3. JS variables are case sensitive, for example x and X are different variables.

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

var name = "ABC";

Variable declaration in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>    
    var x = 500;
    var y = 600;
    var z = x + y;

    console.log("z variable values:",z)
  </script>  

</body>
</html>

Output:

Variable declaration in JavaScript

JavaScript declares the variable type

JavaScript variables can hold different data types: numbers, strings, objects and more:

let length = 100;                               // Number
let lastName = "ABC";                      // String
let x = {firstName:"John", lastName:"King"};    // Object 

Do comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.