- Numbers: 5, 6.5, 7 etc.
- String: “Hello GeeksforGeeks” etc.
- Boolean: true, false.
A variable is a name given to a memory location. 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.
// declaring single variable var name; // declaring multiple variables var name, title, num; // initializng variables var name = "Harsh"; name = "Rakesh";
// creating variable to store a number var num = 5; // store string in the variable num num = "GeeksforGeeks";
Scope of a variable is the part of the program from where the variable may directly be accessible.
- Global Scope – Scope outside the outermost function attached to Window
- Local Scope – Inside the function being executed
Let’s look at the code below. We have a global variable defined in first line in global scope. Then we have a local variable defined inside the function fun().
This is a global variable This is a local variable
When we execute the function fun(), the output shows that both global as well as local variables are accessible inside the function as we are able to console.log them. This shows that inside the function we have access to both global variables (declared outside the function) and local variables (declared inside the function).Let’s move the console.log statements outside the function and put them just after calling the function.
This is a global variable Uncaught reference error: localVar is not defined
We are still able to see the value of the global variable, but for local variable console.log throws an error. This is because now the console.log statements are present in global scope where they have access to global variables but cannot access the local variables.
- Variables in TypeScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.