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 (known as identifiers).

  1. The name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  2. After the 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.

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 

Here’s a tabular representation of variable declaration in JavaScript:

KeywordScopeHoistingReassignmentExample
varFunction/globalHoistedAllowedvar x = 10;
letBlockNot hoistedAllowedlet a = 30; if (true) { let b = 40; }
constBlockNot hoistedNot allowedconst PI = 3.14;
  • Scope:
    • Function/global: Variables are scoped to the function or globally.
    • Block: Variables are scoped to the block ({ }) where they are defined.
  • Hoisting:
    • Hoisted: Variables are moved to the top of their scope during compilation.
    • Not hoisted: Variables are not moved to the top of their scope.
  • Reassignment:
    • Allowed: Variables can be reassigned to a new value.
    • Not allowed: Variables cannot be reassigned after the initial assignment.

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 *