Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

What Are the Differences Between var and let Keywords in JavaScript?

Last updated by Dipen Dadhaniya on Sep 25, 2024 at 10:59 PM | Reading time: 5 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

What Are the Differences Between var and let Keywords in JavaScript?
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

JavaScript is one of the most commonly used programming languages, especially by software engineers who are front-end developers or full-stack developers. If you are preparing for a coding interview, reviewing some of the basics of JavaScript will help you employ it’s features in the best way possible.

In this article, we’re focusing on the var and let keywords. Before ES6, you could initialize a variable in Javascript using var keyword. However, after the launch of ES6 in 2015, JavaScript also allowed use of the let keyword to initialize any variable. So, both keywords essentially help in declaring a variable in JavaScript.

var a = 1;
let b = 2;

However, there are many differences between both the keywords in terms of functionality and behavior. We will cover each of these differences one by one along with the help of examples:

  • Scoping
  • Hoisting 
  • Global Properties
  • Variable redeclaration

Scoping

Scope is the availability of variables, functions, and objects in some particular part of your code during runtime. A variable defined inside a scope is accessible only within that scope, but inaccessible outside.

Variables declared by var keyword are function scoped, i.e., accessible to the immediate function body, while let variables are block scoped, i.e., scoped to the immediate enclosing block denoted by { }.

function foo () {
  var a = 1
  if(a>0) {
    let b = 2;
    console.log(b); // 2
  }
  console.log(a); // 1
  console.log(b); // ReferenceError
}

foo();

In the above example, variable b is initialized with let and since it is block scoped, it can only be accessible in the if block and trying to access it outside the block will give ReferenceError. However, variable a can be accessed inside the entire function foo.

Due to such scoping rules, let variables are easy to use in loops and closures. Consider following example:

for (let i = 0; i < 5; i++) {
  setTimeout(() => console.log(`i: ${i}`), 500);
}

Output:

i: 0
i: 1
i: 2
i: 3
i: 4

Here, since the scope of variable i is the block in which it is initialized, each iteration can be considered as a separate block and thus the value of i in the output will be different in each loop. However, if you replace let with var in the above example, output will be different. In the latter case, i will have global scope and the same variable i will get reinitialized and the latest value will be visible in the output.

for (var i = 0; i < 5; i++) {
setTimeout(_ => console.log(`i: ${i}`), 500);
}

Output:

i: 5
i: 5
i: 5
i: 5
i: 5

Hoisting 

Variables declared with var are hoisted, while let variables are not initialized until their definition is evaluated. So, accessing var variables before their initialization in code returns undefined as all the hoisted variables have value undefined before initialization. Accessing let variables before their initialization gives ReferenceError. Such a piece of block where you cannot access variables as their initialization is not completed is known as “temporal dead zone.”

var a;
console.log(a); // undefined
a = 2;
console.log(a); // 2
console.log(b); // ReferenceError
let b;
console.log(b); // ReferenceError
b = 4;
console.log(b); // 4

Global Properties

var variables declared in global scope are also created as members of the global object, while the same is not true for the let variables. JS code running in a web browser has window as their global object, while code running in the node.js environment has global as global object.

var a = 1; // globally scoped
let b = 2; // not allowed to be globally scoped
console.log(window.a); // 1
console.log(window.b); // undefined

Note: var variables are added as global object property only when code runs in a web browser. Code running in node.js environment does not allow this.

Variable Redeclaration

Variables declared with var keyword can be redeclared in the same scope while redeclaring let variables lead to SyntaxError. Consider the following example:

var a = 1;
var a = 2; // 1 is replaced with 2.
let b = 3;
let b = 4; // SyntaxError: Identifier 'b' has already been declared

Run code snippet

Here, you will find SyntaxError while trying to initialize variable b again.

Ace Your Next Tech Interview With Interview Kickstart!

If you’re looking for guidance and help to nail your next technical interview, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land their dream jobs at Google, Facebook, Apple, Netflix, Amazon, and other Tier-1 tech companies.

Join our webinar to learn more!

---------

Article contributed Prerak Dholakiya

Last updated on: 
October 10, 2024
Author

Dipen Dadhaniya

Engineering Manager at Interview Kickstart

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

What Are the Differences Between var and let Keywords in JavaScript?

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image