Skip to content

JavaScript var keyword | Basics

  • by

The javaScript var keyword is used to declare an implicit type variable, that specifies the type of a variable based on the initial value.

var varibale_name = value;  

Using var statement you can declare a function-scoped or globally-scoped variable, optionally initializing it to a value. If you want your code to run in an older browser, you must use var, don’t use of let and const.

JavaScript var keyword

A simple example code variable declared with the var keyword can be re-declared and updated in the same scope. var is the keyword that tells JavaScript you’re declaring a variable.

<!DOCTYPE html>
<html>
<body>
  <script>    

   function varGreeter(){
    var a = 10;        
    var a = 20; 
    console.log("New value of Var variable",a);
  }
  varGreeter();
</script>  

</body>
</html>

Output:

JavaScript var keyword

Naming variables

Variable names are pretty flexible as long as you follow a few rules:

  • Start them with a letter, underscore _, or dollar sign $.
  • After the first letter, you can use numbers, as well as letters, underscores, or dollar signs.
  • Don’t use any of JavaScript’s reserved keywords.

With that in mind, here are valid variable names:

var camelCase = "lowercase word, then uppercase";
var dinner2Go = "pizza";
var I_AM_HUNGRY = true;
var _Hello_ = "what a nice greeting"
var $_$ = "money eyes";

And here are some invalid variable names:-

var total% = 78;
var 2fast2catch = "bold claim";
var function = false;
var class = "easy";

Here’s a tabular representation highlighting the key differences between var, let, and const in JavaScript:

Characteristicvarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
HoistingHoisted and initialized with undefinedHoisted but not initializedHoisted but not initialized
RedeclarationAllowedAllowedNot allowed
ReassignmentAllowedAllowedNot allowed (constant)
Block-level scopeNoYesYes

Do comment if you have any doubts or suggestions on this JS var code.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading