JS must know topics
1. JS Event delegation
JS event listeners fire not only on a single DOM element but on all its descendants.
2. Event bubbling
Inverse of delegation. Also known as propogation, vents on an element will
“bubble up” and also fire on all parents.
3. Difference between “target” and “currentTarget”
The latter is the element with the listener attached,
the former is the actual element that triggered it.
Example: listen to all form changes:
function handleChange(event) {
console.log(event.currentTarget.value);
// currentTarget is element on which event listener was added (input)
// here target is “form” since it is the actual element clicked
}var formEls = document.getElementsByTagName(‘input’);
for (let i = 0; i < formEls.length; i++) {
formEls[i].addEventListener(‘change’, handleChange, false);
}
Solve above by of target and delegation:
listen to all form changes, instead of every input type:
function handleChange(event) {
console.log(event.target);
// switch case for each target, target is actual element clicked (input)
}var el = document.getElementById(‘form’);
el.addEventListener(‘change’, handleChange);
4. Functions as expression vs definitions
An epression is any valid unit of code that resolves to a value.
function foo() {
// I am a definition or statement
}var foo = function foo() {
// I am an expression, I resolve to a value, even if just “undefined”
}
5. Convert it to IIFE: Immediately invoked function expression
question:
function foo() {
// won’t work: syntax error
}();
above code is converted to
function foo() {
// won’t work: syntax error
}(); // function with no nameanswer: ( function foo() {} )();
Everything in enclosing parentasis is considered an expression not definition/statement
6. Hoisting
All variables (var) are declared at the top of any given function scope ( includes function declarations)
const and let:
a. not hoisted
b. scoped within the block they are in
c. Gives you more control
7. undeclared, undefined and null
undeclared: when we try to use variable that we never declared
const foo = bar — 1; // bar is not defined error
foo = 7 // Valid, assinged to global/window
undefined:
a. variable declared but no defined value (not initialized)
b. object/array exists but nothing at that key/index
c. function exists but doesn’t return anything
d. falsy
e. Not an error, totally valid
null:
a. null has a value. It’s value is null
b. null is a “nothing” value
c. not zero, not empty string/object/array
d. falsy
const foo = null;
console.log(foo) // null
Checking all three:
check;
let foo;
console.log(type of foo); // “undefined” as a string
console.log(type of bar); // undeclared, but also returns “undefined”
// preferred
console.log(foo === undefined); // true boolean, “==” would be true for string “undefined”
const foo = null;.
console.log(type of foo); // object, bug in JS
// preferred
console.log(foo === null); // true