- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between var and let in JavaScript
As we know in order to declare a variable in javascript we have two options either declare with var or declare with let. Now the question is when to use var and when to use let i.e what are the major difference between both.
In the following text we come to know the major difference between var and let in javascript.
The main difference between let and var is that scope of a variable defined with let is limited to the block in which it is declared while variable declared with var has the global scope. So we can say that var is rather a keyword which defines a variable globally regardless of block scope.
The scope of let not only limited to the block in which it is defined but variable with let also do not get added with global window object even if it get declared outside of any block. But we can access variable with var from window object if it is defined globally.
Due to limited scope let variables are usually used when there is limited use of those variables such as in for loops, while loops or inside the scope of if conditions etc while var variable is used when value of variable need to be less change and used to accessed globally.
Also, one difference between var and let is variable with var can be redeclared to some other value while variable could not be redeclared if it is defined with let.
Example representing difference between var and let
let a = 'hello'; // globally scoped var b = 'world'; // globally scoped console.log(window.a); // undefined console.log(window.b); // 'world' var a = 'hello'; var a = 'world'; // No problem, 'hello' is replaced. let b = 'hello'; let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
- Related Articles
- Explain the difference between let and var in Swift
- Difference between Var and Dynamics in C#
- Difference between var and dynamic in C#
- What is the difference between: var functionName = function() {} and function functionName() {} in Javascript
- What is the difference between "var" and "val" in Kotlin?
- What is the difference between VAR and DYNAMIC keywords in C#?
- JavaScript Let
- Difference between == and === operator in JavaScript
- Const vs Let in JavaScript.
- Difference between Java and JavaScript.
- Difference between TypeScript and JavaScript
- Difference Between PHP and JavaScript
- Difference between JavaScript and HTML
- Difference between Python and JavaScript
- Difference between JavaScript and AngularJS
