Advertisement

Google Ad Slot: content-top

Javascript var

~1 min read · JS
On this page

In JavaScript, var is one of the three ways to declare variables, along with let and const. Here's a detailed overview of how var works and its characteristics:



Characteristics of var:


1)  Function Scope:


     Variables declared with var are function-scoped. This means they are only accessible within the function in which they are defined. However, if declared outside a function, they become global variables.

Example
Online HTML Editor
Try it yourself

 2) Re-declaration:


     You can re-declare variables using var within the same scope without any errors.

Example
Online HTML Editor
Try it yourself

3) Global Variables:


    When a var is declared outside any function, it becomes a property of the global object.

Example
Online HTML Editor
Try it yourself

4) No Block Scope:


     var does not respect block scope (i.e., { ... } created by loops or conditionals). This means that variables declared with var are accessible outside of blocks, even if they are declared inside.

Example
Online HTML Editor
Try it yourself