Loading

KEYPOINTS:
  • Variables in Javascript are used to store and manage data
  • There are two types of variables Local and Global variables
  • we use 3 types of decalaration VAR, LET and CONST 

Variables are containers for storing data values. Variables allow programs to store, retrieve, and manipulate data dynamically.

  • They act as placeholders that can hold different types of data, such as numbers, strings, objects, or even functions. 
  • Variables can be declared using the keywords var, let, or const, each having different scopes and characteristics

There are three keywords for declaring variables in JavaScript: 

  • VAR: Declares a variable with function scope or global scope. It is hoisted, meaning the declaration is moved to the top of the scope, but its value is not initialized until the code is executed.
  • LET: Declares a block-scoped variable. Unlike VAR, it is not hoisted to the top, so it only exists within the block in which it is defined.
  • CONST: Declares a block-scoped variable that cannot be reassigned once it is initialized. The value it holds can still be mutable if it is an object, but the reference cannot change.

VAR (function-scoped):

  • Variables declared with the var keyword are function-scoped, meaning they are only accessible within the function in which they are defined.
  • Variables declared with var inside a function are confined to that function.
CODE EXAMPLE:
example() sample{
var x = 14;
if (true) {
var x = 20; // This re-declares the 'x' variable within the same function scope.
}
console.log(x); // Outputs 20
}

LET and CONST (block-scoped):

  • Variables declared with let and const keywords are block-scoped i.e are limited to that block, meaning they are only accessible within the nearest enclosing curly braces or block.
CODE EXAMPLE
if (true) {
 let y = 30;
 const z = 40;
}
// console.log(y); // This would result in an error since 'y' is not in scope.
// console.log(z); // This would result in an error since 'z' is not in scope.
let a = 50;
a = 60; // Valid for 'let'
const b = 70;
// b = 80; // This would result in an error since 'const' variables cannot be reassigned.

There are two types of variables in JavaScript:

  • Local variable 
  •  Global variable

Local variables:

  • Local variables in JavaScript are declared within a specific scope, typically within a function or block of code.

CODE EXAMPLE

<script>  
function abc(){  
var x=5;//local variable  
}  
</script>  

Global variables:

Global variables can be accessed from any function in JavaScript, including within functions, code blocks, and other parts of your program. 


CODE EXAMPLE
<html>
<body>
   <script>
      var data = 200;//gloabal variable  
      function a() {
         document.writeln(data);
      }
      function b() {
         document.writeln(data);
      }
      a();//calling JavaScript function
      b();
   </script>
</body>
</html>

Output:

200 200