In the article, we will learn about what is difference between var, const and let variable in javascript with example
Var keyword is declared globally in the problem you have used anywhere, var keyword is the oldest keyword in javascript. var keyword defined outside of the function it can access globally. var keyword scope is global.
You can see different examples below of how to use the var keyword
- If I declare a var keyword outside of the function then it will use globally on the web page.
<html> <head> <script> var varKeyword = 10 function javascriptFunction() { console.log(varKeyword) // 10 } javascriptFunction() console.log(varKeyword) // 10 </script> </head> <body> </body> </html>
- user cane re-declareand update the var keyword value
<html> <head> <script> var varKeyword = 10 var varKeyword = 9 document.write(varKeyword) //9 </script> </head> <body> </body> </html>
Let Keyword has improved a version of the var keyword. let keyword scope is only block
- let keyword if I declare outside of the block it will give that value undefined
<html> <head> <script> let letKeyword1 = 10 function javscriptFunction() { if (true) { let letKeyword2 = 9 console.log(letKeyword2) //9 } console.log(letKeyword2) //give error } javscriptFunction() </script> </head> <body> </body> </html>
- it give not permission of re-declare of let veriable
<html> <head> <script> let letKeyword1 = 10 // It is not allowed let letKeyword1 = 10 // It is allowed letKeyword1 = 10 </script> </head> <body> </body> </html>
- users can declare the variable with the same name in different blocks using the let keyword.
<html> <head> <script> let letKeyword1 = 10 if (true) { let letKeyword1 = 9 console.log(letKeyword1) // It prints 9 } console.log(letKeyword1) // It prints 10 </script> </head> <body> </body> </html>
Const Keyword has the same properties as the let keyword, with the exception that the user cannot edit it.
- const keyword scop is block and const keyword require to first initialize and declare it otherwise it will give the error
<html> <head> <script> const constKeyword1 = 10 console.log(constKeyword1) //10 </script> </head> <body> </body> </html>
- users cannot change the properties of the const object, but they can change the value of properties of the const object.
<html> <head> <script> const constKeyword1 = 10 function javascriptFunction() { constKeyword1 = 9 console.log(constKeyword1) //TypeError:Assignment to constant variable. } javascriptFunction() </script> </head> <body> </body> </html>