1. What is the difference between ==
and
===
?
==
checks for value equality with
type coercion.
===
checks for both value and type
without coercion.
'5' == 5 // true
'5' === 5 // false
2. What is a closure in JavaScript?
A closure is a function that retains access to its outer function’s variables even after the outer function has finished executing.
Closure – tai funkcija, kuri "prisimena" savo aplinką net ir tada, kai yra vykdoma už tos aplinkos ribų.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
3. What is the difference between var
,
let
, and const
?
- var
var is function-scoped, not block-scoped, and
can be redeclared and updated.
- let
is block-scoped, can be updated, but not
redeclared in the same scope.
- const
is also block-scoped, and cannot be
reassigned or redeclared, but if it's an object or array, the
contents can be mutated.
function test() {
if (true) {
var x = 1;
let y = 2;
const z = 3;
}
console.log(x); // 1
console.log(y); // ReferenceError
console.log(z); // ReferenceError
}