Difference Between ‘let’ and ‘var’

Designed by: Akhund Technologies Using pre-made template

While you are studying Typescript or Javascript, you may be asked about the difference between ‘let’ and ‘var’…

Why Do We Use Both?

We use both ‘let’ and ‘var’ because they serve different purposes…

Global vs. Local

  • Var is a global variable…
  • Let is a local variable…

Scope of Variables

  • Global variable can be used throughout the code…
  • Local variable can only be used inside the block it is declared…

Example for Better Understanding

The example is: ‘var’ is your global friend who helps you in every situation… While ‘let’ is also a friend, he can help you in his block only… Inside curly braces when he is declared… He is a local hero of his block…

QUESTION

What will be printed?

var x = 11;
if (x > 10) {
  let x = 10;
}
print(x);

Options:

  • 10
  • 11
  • x

ANSWER

Let x = 10 is inside the {} block of the if statement, which means that it is in its own scope. When print(x); runs, it prints the value of the original variable x, which is still 11.


Discover more from LearnAI

Subscribe to get the latest posts sent to your email.

Comment your thoughts! Connect with other members too…

0

)

Discover more from LearnAI

Subscribe now to keep reading and get access to the full archive.

Continue reading

Design a site like this with WordPress.com
Get started