easyFrontend Developer interview question
What is the difference between var, let and const in JavaScript?
What the interviewer wants to hear
- var is function scoped; let and const are block scoped
- var is hoisted and initialised to undefined
- let and const are hoisted but in the temporal dead zone
- const cannot be reassigned but objects can still be mutated
- Prefer const by default, let when reassigning
Model answer
var is function scoped, so a var declared inside an if block is visible in the whole function. It is also hoisted and set to undefined, so you can read it before the line where it is declared without an error. let and const are block scoped, meaning they only exist inside the nearest curly braces. They are hoisted too, but they stay in the temporal dead zone until the declaration runs, so reading them early throws a ReferenceError. const means the variable binding cannot be reassigned, but if it holds an object or array you can still change its contents. In modern code I use const by default, let when I really need to reassign, and avoid var.
Can you answer it under time pressure?
Take a timed easy round and get scored on every answer.
More easy Frontend Developer questions
- Explain the CSS box model. What is the difference between content-box and border-box?
- What is semantic HTML and why does it matter?
- In React, what is the difference between props and state?
- How do you make a web page responsive for mobile, tablet and desktop?
- What is the difference between Flexbox and CSS Grid, and when would you use each?
- What is a closure in JavaScript? Give a practical example of where you use one.
- How do you make a form accessible?
- A button on a page does not work when clicked. How would you use browser DevTools to find the problem?
- What is a Promise, and how does async/await relate to it?