- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - Variables
JavaScript Variables
JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the variables in 4 ways −
Without using any keywords.
Using the 'var' keyword.
Using the 'let' keyword.
Using the 'const' keyword.
The let and const keywords were introduced to JavaScript in 2015 (ES6). Prior to ES6, only var keyword was used to declare the variable in JavaScript. In this section, we will discuss 'var' keyword. We will cover the 'let' and 'const' keywords in subsequent chapters.
Variable Declaration in JavaScript
You can follow the syntax below to declare the variables without using any keywords.
<script> Money = 10; Name = "tutorialspoint"; </script>
Furthermore, you can use the var keyword to declare the variables as shown below.
<script> var money; var name; </script>
You can also declare multiple variables with the same var keyword as follows −
<script> var money, name; </script>
Variable Initialization using the Assignment Operator
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script> var name = "Ali"; var money; money = 2000.50; </script>
Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
JavaScript Data Types
In JavaScript, the variable can hold the value of the dynamic data type. For example, you can store the value of number, string, boolean, object, etc. data type values in JavaScript variables.
<script> var num = 765; // Number var str = "Welcome"; // String var bool = false; // Boolean </script>
You will learn data types in detail in JavaScript Data Types chapter.
JavaScript Variable Names (Identifiers)
In JavaScript, a unique character sequence is used to name the variables called identifiers.
Here are some rules for the naming of the identifiers in JavaScript −
Valid characters − In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one..
Case sensitivity − Variable names are case sensitive. It means Name and name are different identifiers.
Unicode support − The identifiers can also contain the Unicode. So, developers may define variables in any language.
Reserve keywords − You should not use any of the JavaScript reserved keywords as a variable name. For example, break or boolean variable names are not valid. Here, we have given a full list of the JavaScript revered keywords.
JavaScript Dollar Sign ($) and Under Score (_)
You can use the $ and _ to define the variables in JavaScript, as the JavaScript engine considers it a valid character.
Example (Demonstrating the identifiers)
In this example, we have defined the variables using the var keyword. The first variable name starts with the underscore, and the second variable name starts with the dollar sign. Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any identifier with the digit.
<html> <head> <title> Variables in JavaScript </title> </head> <body> <script> var _abc = "Hi!"; var $abc = "Hello!"; // var 9abc = "Bye!"; // This is invalid document.write("_abc " + _abc + "<br>"); document.write("$abc = " + $abc + "<br>"); </script> </body> </html>
It produces the following result −
_abc Hi! $abc = Hello!
Undefined Variable Value in JavaScript
When you don't initialize the variable after declaring, it contains the undefined value. However, you can also assign the undefined value to the variable.
Let's look at the example below.
Example
<html> <body> <script> var num; document.write("The value of num is: " + num + "<br/>"); </script> </body> </html>
This produces the following result −
The value of num is: undefined
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.
Example
In the example below, we have defined the variable named myVar outside the function and initialized it with the 'global' value. Also, we have defined the variable with the same identifier inside the checkscope() function and initialized it with the 'local' value.
We print the myVar variable's value inside the function. So, the local variable takes preference over the global variable and prints the 'local' in the output.
<html> <head> <title> JavaScript Variable Scope Example</title> </head> <body onload = checkscope();> <script> var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); } </script> </body> </html>
This produces the following result −
local
Example
In the example below, we have defined the variables without using the var keyword. The name variable contains the value of the string type, and the number variable contains the value of the float data type.
When we define the variables without using any keyword, JavaScript considers them global variables and can use them anywhere inside the code.
<html> <head> <title> Variables without var keyword </title> </head> <body> <script> name = "tutorialspoint"; // String type variable number = 10.25; // Number type variable document.write("name = " + name + ", number = " + number + "<br>"); </script> </body> </html>
This produces the following result −
name = tutorialspoint, number = 10.25
Also, the identifier doesn't lose the previous value if we declare the variable using the var keyword with the value and re-declare the same identifier without initialization. Let’s understand it via the example below.
Example
In the example below, we have declared the age variable and initialized it with 10. Again, we have declared the age variable but haven’t initialized it. Still, it prints 10 in the output because it doesn’t lose the previous initialization’s value. However, if we update the value of the age variable, it successfully updates it.
<html> <head> <title> Variables with var keyword </title> </head> <body> <script> var age = 10; var age; document.write("age = " + age + "<br>"); </script> </body> </html>
This produces the following result −
age = 10