The Wayback Machine - https://web.archive.org/web/20240920014719/https://www.geeksforgeeks.org/javascript-var/
Open In App

JavaScript var

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The JavaScript var statement declares variables with function scope or globally. Before ES6, var was the sole keyword for variable declaration, without block scope, unlike let and const.

Syntax:

var variableName = valueOfVar;

Function Scope

The variables declared inside a function are function-scoped and cannot be accessed outside the function.

The variables declared using the var statement are hoisted at the top and are initialized before the execution of code with a default value of undefined. The variables declared in the global scope that is outside any function cannot be deleted

Examples of JavaScript var

Example 1: In this example, we will declare a global variable and access it anywhere inside the program

JavaScript
var test = 12
function foo(){
    console.log(test);
}
foo();

Output:

12

Example 2: In this example, we will declare multiple variables in a single statement

JavaScript
var test1 = 12,
    test2= 14,
    test3 = 16
function foo(){
    console.log(test1, test2, test3);
}
foo();

Output:

12 14 16

Example 3: In this example, we will see the hoisting of variables declared using var

JavaScript
console.log(test);
var test = 12;

Output:

undefined

Explanation: We get the output without any error because the variable test is hoisted at the top even before the execution of the program began and the variable is initialized with a default value of undefined

Example 4: In this example, we will redeclare a variable in the same global block

JavaScript
var test = 12;
var test = 100;
console.log(test);

Output:

100

Explanation: We did not get any error when redeclaring the variable if we did the same with the let keyword an error would be thrown

Example 5: In this example, we will redeclare the variable in another scope and see how it is the original variable.

JavaScript
var test = 12;
function foo(){
    var test = 100;
    console.log(test);
}
foo();
console.log(test);

Output:

100
12

Explanation: We did not get any error while redeclaring the variable inside another function scope and the original value of the variable is preserved.

Example 6: In this example, we will try to delete a global variable declared using var in the ‘use strict’ mode

JavaScript
'use strict';
var test = 12;
delete(test);
console.log(test);

Output:

Image

Explanation: Whenever a variable is declared using var in global scope it cannot be configured. Hence it cannot be deleted using the delete keyword. and an error is thrown

Supported Browser:

P.S: To clear your concept of var, const, and let please go through How to declare variables in different ways in JavaScript?

JavaScript var – FAQs

What is var in JavaScript?

var is a keyword used to declare variables in JavaScript. It has function scope and is hoisted, meaning it can be accessed before its declaration in the code.

How does var differ from let and const?

var has function scope and is hoisted, whereas let and const have block scope. const also prevents reassignment of the variable’s value.

What is function scope in JavaScript?

Function scope means a variable declared with var is accessible throughout the entire function in which it is declared, regardless of where it is declared within that function.

What is hoisting in JavaScript?

Hoisting is JavaScript’s default behavior of moving variable and function declarations to the top of their containing scope before code execution. Only the declarations are hoisted, not the initializations.

Can you redeclare a variable using var?

Yes, variables declared with var can be redeclared in the same scope without any error, which can lead to unintentional overwriting of variables.



Previous Article
Next Article

Similar Reads

Difference between $var and $$var in PHP
In PHP, $var is used to store the value of the variable like Integer, String, boolean, character. $var is a variable and $$var stores the value of the variable inside it. $var: Syntax: $variable = value;The $variable is the variable nameThe value is the initial value of the variable. Example 1: This example stores and displays values with $. C/C++
2 min read
Difference between "var functionName = function() {}" and "function functionName() {}" in JavaScript
In this article, we will be discussing the function functionName() {} and functionName = function() {} with suitable code examples for each condition & then we will see the difference between the function functionName() {} and functionName = function() {}. function functionName() {}: A function declaration is a statement that creates a named fu
3 min read
Difference between var and let in JavaScript
In the early days of JavaScript, there was only one way of declaring variables and that was using the var keyword. A variable declared with var is defined throughout the program. One of the issues with using the var keyword was redeclaring a variable inside a block will also redeclare the variable outside the block.  With the introduction of ES6 in
3 min read
Difference between var, let and const keywords in JavaScript
In JavaScript, we use var, let, and const to create variables. These keywords might seem similar at first, but they control how and where your variables work in your code. Let's explore each one and how they differ from each other. JavaScript var keywordThe var is the oldest keyword to declare a variable in JavaScript. It has the Global scoped or f
5 min read
What is the use of curly brackets in the `var { ... } = …` statements ?
Destructuring assignment allows us to assign the properties of an array or object to a bunch of variables that are sometimes very convenient and short. Consider the following illustration. Both of the below-mentioned methods are right and produce the same result. Without Destructuring: var array = [1, 20, 40]; var first = array[0] var second = arra
2 min read
Which one is better (unset() or $var = null) to free memory in PHP ?
In this article, we will discuss freeing the memory with unset() and using NULL value to any variable. unset(): The unset() function is an inbuilt function in PHP that is used to unset a specified variable. The unset() function just destroys or removes the variable from the symbol table. After the unset() applied on a variable, it's marked for PHP
2 min read
Explain the differences on the usage of foo between function foo() {} and var foo = function() {}
Here we see the differences on the usage of foo between function foo() {} and var foo = function() {} types of function declarations in JavaScript. function foo() {} is a Normal Function or traditional general way of Function Declaration which every user or developer finds it simpler to declare and use it every ever required and var foo = function(
4 min read
HTML <var> Tag
HTML <var> Tag is a phrase tag used to define the variable in a mathematical equation or a computer program. The content of this tag is displayed in an italic format in most browsers. Note: This tag is not deprecated, but by using CSS we can achieve better effects. Syntax: <var> Contents... </var>Other elements that are used in co
3 min read
CSS var() Function
The var() function in CSS is used to insert a value for a custom property. Syntax: var( custom_property, value )Parameters: This function accepts two parameters which are listed below: custom_property: It is the required parameter. The name of the custom property must start with two dashes(--).value: It is an optional parameter. It is used if the c
2 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important attribute of <script> tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. <script> cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &&:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
JavaScript Course Operators in JavaScript
An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithmetic operations, etc. There are various operators
7 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the code block inside it will be executed otherwise n
3 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How can JavaScript codes be hidden from old browsers that do not support JavaScript ?
Nowadays all modern browsers support JavaScript, however, older browsers did not support JavaScript. In this article, we will learn how we can hide JavaScript code from running in older browsers. Approach: After opening the <script> tag, we will use a one-line HTML style comment without any closing character ( <!-- ). We will then write th
2 min read
How are the JavaScript window and JavaScript document different from one another?
What is a JavaScript window? The window is at a root/top level at the JavaScript object hierarchy. It is a global/root object in JavaScript and it is the root object of the Document object model(DOM); What is a JavaScript document? A document is an object inside the window object and we use a document object for manipulation inside the document. Th
3 min read
Explore the concept of JavaScript Function Scope and different types of JavaScript Functions
JavaScript is based on functional programming. Therefore, functions are fundamental building blocks of JavaScript. So the function is called first-class citizens in JavaScript. Syntax: Define a functionfunction functionName(parameters) { // SET OF STATEMENTS } Call a functionfunctionName(arguments); The function execution stops when all the stateme
10 min read
Which href value should we use for JavaScript links, "#" or "javascript:void(0)" ?
In this article, we will know which "href" should be used for JavaScript when we can use "#" or "javascript:void(0)". Let us understand it. Using the '#' value: The # is a fragment identifier used to refer to a specific section of the same document. When a user clicks a link with a # href, the browser will scroll to that section of the page specifi
3 min read
How to include a JavaScript file in another JavaScript file ?
In native JavaScript, before ES6 Modules 2015 was introduced had no import, include, or require functionalities. Before that, we can load a JavaScript file into another JavaScript file using a script tag inside the DOM that script will be downloaded and executed immediately. Now after the invention of ES6 modules, there are so many different approa
3 min read
JavaScript Program to find Length of Linked List using JavaScript
Given a linked list, the task is to determine its length using various methods. The linked list is a fundamental data structure consisting of nodes connected in a chain, offering efficient data organization. Different approaches, including Iterative and Recursive Methods, enable us to compute the length of a linked list easily. Use the below approa
3 min read
JavaScript Cheat Sheet - A Basic Guide to JavaScript
JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsers. It is one of the core technologies of the World Wide Web, alongside HTML and CSS, and the powerhouse behind the
15+ min read
JavaScript Course Variables in JavaScript
Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In JavaScript, all the variables must be dec
4 min read
JavaScript Complete Guide - A to Z JavaScript Concepts
What is JavaScript ? JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for webpages. What is JavaScript Complete Guide ? JavaScript Complete Guide is a list of A to Z JavaScript concepts from beginner to advanced level. Table of Contents Introducti
8 min read
How to Delay a JavaScript Function Call using JavaScript ?
Delaying a JavaScript function call involves postponing its execution for a specified time using methods like setTimeout(). This technique is useful for timed actions, animations, or asynchronous tasks, enabling smoother user experiences and better control over when certain operations run. There are several ways to delay the execution of a function
3 min read