Variables in JAVASCRIPT

*What is JavaScript Variable?

--A JavaScript variable is simply a name of storage location. Imagine a computer memory as your kitchen where you put each thing in a particular order so when you need that thing you went there and grab what you want it.

--So the same thing happens with a computer it has n number of storage when you want to put some data in it you need some placeholder or container that can do it for you. so variable is that container.

--Javascript includes variables that hold the data value and it can be changed on runtime as javascript is dynamic language.

  • You can use var, const, and let keyword to declare a variable, and JavaScript will automatically determine the type of this variable according to the value passed.

*There are some rules while declaring a JavaScript variable (also known as identifiers).

  1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.

  2. After first letter we can use digits (0 to 9), for example value1.

  3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables

var x = 10;
var _value="sonoo";

Incorrect JavaScript variables

var 123=30;
var \
aa=320;*

There are two types of variables in JavaScript :

  • Local Variable

Variables that exist only inside a function are called Local variables. They have no presence outside the function. The values of such Local variables cannot be changed by the main code or other functions. This results in easy code maintenance and is especially helpful if many programmers are working together on the same project.

  • Globle Variable

Variables that exist throughout the script are called Global variables. Their values can be changed anytime in the code and even by other functions.

local-variable-and-global-variable.png

In the next section, you will go through the Scope of Variables in JavaScript.

What is “variable scope”?

Local variables exist only inside a particular function hence they have Local Scope. Global variables on the other hand are present throughout the script and their values can be accessed by any function. Thus, they have Global Scope.

Local Scope Variables

  • Any variable that you declare inside a function is said to have Local Scope.

  • You can access a local variable within a function. If you try to access any variable defined inside a function from outside or another function, it throws an error.

Variables_in_Javacript_4.webp

Globle Scope Variables

  • Any variable declared outside of a function is said to have Global Scope.

  • In simple terms, a variable that can be accessed anywhere in the program is known as a variable with global scope. Globally scoped variables can be defined using any of the three keywords: let, const, and var.

Variables_in_Javacript_3.webp