Basic Flashcards

1
Q

What’s the difference between const, let and var?

A

var - function scope
let / const - block scope

let can be reassigned, while const creates a read-only reference to a value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the three ways to declare a variable?

A

var, let, or const.

var - function scope,
let and const - block scope. Use const for variables that won’t be reassigned and let for those that will be.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between let, const, and var?

A

let and const are block-scoped, var is function-scoped

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s the difference between a variable that is: null, undefined or undeclared? How would you go about checking for any of these states?

A

Undeclared variables are created when you assign a value to an identifier that is not previously created using var, let or const. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a ReferenceError will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad just like how global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a try/catch block.

A variable that is undefined is a variable that has been declared, but not assigned a value. It is of type undefined. If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of undefined. To check for it, compare using the strict equality (===) operator or typeof which will give the ‘undefined’ string. Note that you should not be using the abstract equality operator to check, as it will also return true if the value is null.

A variable that is null will have been explicitly assigned to the null value. It represents no value and is different from undefined in the sense that it has been explicitly assigned. To check for null, simply compare using the strict equality operator. Note that like the above, you should not be using the abstract equality operator (==) to check, as it will also return true if the value is undefined.

As a personal habit, I never leave my variables undeclared or unassigned. I will explicitly assign null to them after declaring if I don’t intend to use it yet. If you use a linter in your workflow, it will usually also be able to check that you are not referencing undeclared variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly