--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).
- Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
- After first letter we can use digits (0 to 9), for example value1.
- JavaScript variables are case sensitive, for example x and X are different variables.
<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
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.
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:-
Output:-
TechCode
0 Comments