javaScript Variable

--A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.

--In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically we can declare variables in three different ways : var, let and const keyword. Each keyword is used in some specific conditions.

--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.
--Two Types of Variable:-

1)Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.

2)Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Code:-

<html>
<body onload = checkscope();>  
<script type = "text/javascript">
         
var myVar = "global";      // Declare a global variable
function checkscope( ) {
var myVar = "local";    // Declare a local variable
document.write(myVar);
}
</script>    
</body>
</html>

Output:-

local

var: This keyword is used to declare variable globally. If you used this keyword to declare variable then the variable can accessible globally and changeable also. It is good for a short length of codes, if the codes get huge then you will get confused. 

Syntax:-

var variableName = "Variable-Value;"

Code:-

<html>
<body>
<script>  
var x = 10;  
var y = 20;  
var z=x+y;  
document.write(z);  
</script>  
</body>
</html>

Output:-

30

let: This keyword is used to declare variable locally. If you used this keyword to declare variable then the variable can accessible locally and it is changeable as well. It is good if the code gets huge.


Syntax:-

let variableName = "Variable-Value;"

Code:-

<html>
<body>
<script>  
if (true) {
let TechCode = "TechCode";
console.log(TechCode);
}
         
/* This will be error and
show geeks is not defined */
console.log(TechCode);
     
</script>  
</body>
</html>

Output:-


TechCode

Const: This keyword is used to declare variable locally. If you use this keyword to declare a variable then the variable will only be accessible within that block similar to the variable defined by using let and difference between let and const is that the variables declared using const values can’t be reassigned. So we should assign the value while declaring the variable.

Syntax: 

const variableName = "Variable-Value;"

Code:-

<html>
<body>
<script>  
const TechCode = "TechCode";
console.log(TechCode);
</script>  
</body>
</html


Output:-

TechCode


Post a Comment

0 Comments