Javascript Notes
Javascript Notes
I. Beginner/Fundamentals
1. Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that is one of the core technologies
of the World Wide Web, alongside HTML and CSS. It is primarily known as the language for web
page interactivity, but its use has expanded significantly to server-side programming ([Link]),
mobile development (React Native), and desktop applications (Electron).
Key Concepts:
Client-side: Runs in the user’s web browser, manipulating the Document Object Model
(DOM) to create dynamic content.
Server-side: Runs on a server (via [Link]), allowing for full-stack development, file system
access, and database interaction.
Real-World Examples:
API login request and return a JSON web check credentials and send token */ });
token (JWT).
2. Variables and Data Types
Variables are containers for storing data values. JavaScript has three keywords for declaring
variables: var , let , and const , each with different scoping rules.
Function-
var Yes Yes Yes (initialized with undefined )
scoped
"Hello World" ,
String Textual data, enclosed in quotes.
'JavaScript'
Undefined A variable that has been declared but not assigned a value. let x;
Real-World Examples:
Example Description Code Snippet (Conceptual)
Operators are special symbols used to perform operations on operands (values and variables).
Basic math
Arithmetic + , - , * , / , % , ** 5 + 3
operations.
Assigns a value to a
Assignment = , += , -= , *= x += 5
variable.
Combines boolean
Logical && (AND), ` (OR), !` (NOT)
expressions.
=== (Strict Equality): Compares values without type coercion. It checks if both the value
and the type are the same. Always prefer === for predictable code.
Real-World Examples:
Example Description Code Snippet (Conceptual)
Using strict inequality ( !== ) to ensure a if ([Link] !== '' && typeof
Input
form field is not empty and is of the [Link] === 'string') { /*
Sanitization
expected data type before processing it. process */ }
4. Control Flow
Control flow statements dictate the order in which the program’s instructions are executed.
Conditional Statements:
switch : Evaluates an expression, matching the expression’s value to a case clause, and
executes statements associated with that case.
Loops:
do...while : Similar to while , but the block of code is executed at least once before the
condition is checked.
for...of : Iterates over the values of an iterable object (like Arrays, Strings, Maps,
NodeLists).
Real-World Examples:
Example Description Code Snippet (Conceptual)
Menu user actions based on which menu item they saveDoc(); break; case 'print':
Navigation clicked, leading to cleaner code than nested printDoc(); break; default:
if/else . showHelp(); }
5. Functions
Functions are the fundamental building blocks of JavaScript. A function is a set of statements that
performs a task or calculates a value.
Function Types:
Arrow Function (ES6): const greet = (name) => 'Hello, ' + name; (Shorter syntax, no
this binding, not hoisted)
Scope:
Function Scope ( var ): Variables are accessible anywhere within the function they are
declared in.
Block Scope ( let , const ): Variables are only accessible within the block (e.g., if
statement, for loop) they are declared in.
Real-World Examples:
Example Description Code Snippet (Conceptual)
Arrays and Objects are the two most common non-primitive data structures in JavaScript.
Objects: Unordered collections of key-value pairs. Keys are strings (or Symbols), and values can
be any data type.
Destructuring: A convenient way to extract values from arrays or properties from objects into
distinct variables.
Real-World Examples:
Example Description Code Snippet (Conceptual)
The DOM is a programming interface for web documents. It represents the page so that programs
can change the document structure, style, and content.
Key Operations:
Real-World Examples:
Example Description Code Snippet (Conceptual)
site’s theme.
Using [Link]() to
Creating dynamically generate new HTML const newDiv =
A Higher-Order Function (HOF) is a function that either takes one or more functions as
arguments or returns a function as its result. Array methods like map , filter , and reduce are
common HOFs.
Selects elements A new array containing Displaying only “active” users from a
filter()
that pass a test. only the passing elements. list of all users.
Reduces the array to The single, accumulated Calculating the total price of items in a
reduce()
a single value. value. shopping cart.
Real-World Examples:
Example Description Code Snippet (Conceptual)
Using map to iterate over a list of API results const normalized = [Link](item
Data
and standardize the key names and structure => ({ id: [Link], name:
Normalization
for internal use. item.full_name }));
A closure is the combination of a function bundled together (enclosed) with references to its
surrounding state (the lexical environment). In simpler terms, a closure gives you access to an
outer function’s scope from an inner function.
Key Principle: Lexical Scoping JavaScript uses lexical scoping, meaning that the scope of a
variable is determined by where the variable is defined in the source code, not where it is called.
Real-World Examples:
Function Currying a new function until all arguments b; const double = multiply(2);
are collected, often used in double(5); // 10
functional programming libraries.
JavaScript is a prototype-based language. Every object has a private property which holds a link
to another object called its prototype. That prototype object has its own prototype, and so on,
until an object with null as its prototype is reached. This chain is used for inheritance.
Key Concepts:
Prototype Chain: The mechanism by which objects inherit features from one another.
Real-World Examples:
JavaScript is single-threaded, meaning it can only execute one task at a time. Asynchronous
operations (like fetching data from a server) are handled by the Event Loop, which allows non-
blocking execution.
3. Callback Queue (Task Queue): Where callbacks from Web APIs are placed when their
operation is complete.
4. Event Loop: Constantly checks if the Call Stack is empty. If it is, it pushes the first function
from the Callback Queue onto the Call Stack.
Evolution of Async:
An object representing the eventual completion (or Still requires chaining with
Promises
failure) of an asynchronous operation and its resulting .then() , which can be
(ES6)
value. verbose.
Real-World Examples:
ECMAScript 2015 (ES6) introduced major features that fundamentally changed how JavaScript is
written.
Real-World Examples:
Code Snippet
Example Description
(Conceptual)
Using the Spread operator ( ... ) to create a new object by const newState = {
State Merging merging an existing state object with new properties, a ...oldState, counter:
13. Async/Await
async/await is a modern syntax built on top of Promises, making asynchronous code look and
behave more like synchronous code, which is easier to read and debug.
await expression: Can only be used inside an async function. It pauses the execution of
the async function until the Promise it is waiting for is resolved.
Error Handling: Unlike Promise chains where errors are caught with .catch() , async/await
uses the familiar synchronous try...catch block.
Real-World Examples:
Effective error handling and debugging are crucial for building robust applications.
try...catch : Catches synchronous errors. The try block contains the code to monitor,
and the catch block handles any errors thrown.
finally : Executes code after try and catch , regardless of the outcome (e.g., for cleanup).
Debugging Tools: The most powerful tool is the browser’s Developer Tools (DevTools). Key
features include:
Call Stack: Seeing the sequence of function calls that led to the current point.
Resource (like a file handle or a loading spinner) is closed processData(); } catch (e) {
JavaScript objects have capabilities beyond simple key-value storage, enabling powerful meta-
programming.
An object that wraps another object (the target) Creating reactive objects for
Proxy and intercepts fundamental operations (like state management or logging
property lookup, assignment, enumeration). all property access.
Real-World Examples:
Example Description Code Snippet (Conceptual)
Core FP Principles:
Immutability: Data cannot be changed after it is created. Instead of modifying an array, you
create a new one.
Pure Functions: Functions that, given the same input, will always return the same output
and have no side effects (e.g., modifying global state, I/O operations).
Function Composition: Combining simple functions to build more complex ones, where the
output of one function is the input of the next.
Real-World Examples:
Example Description Code Snippet (Conceptual)
Ensuring that
state updates are
immutable by
using the spread
operator or
State Updates
[Link]() const newState = { ...oldState, value: newValue };
in React/Redux
to create a new
state object
instead of
modifying the old
one directly.
Using a sequence
of pure functions
( filter , map ,
reduce ) to
Data
transform raw const report =
Transformation
data into a final [Link](isValid).map(format).reduce(calculateTotal);
Pipeline
report, making
the logic easy to
test and reason
about.
Creating reusable,
partially applied
functions for
common tasks,
Curried Utility const logError = log('ERROR'); logError('Database
such as a logging
Functions connection failed');
function that is
pre-configured
with a severity
level.
Caching the results of expensive function calls and Speeds up functions that are called
Memoization returning the cached result when the same inputs frequently with the same
occur again. arguments.
Real-World Examples:
Debounce the API request 300ms after the user debounce(fetchResults, 300));
stops typing.
Key Tools:
Tool Category Description Examples
Module Takes modules with dependencies and merges them into a few Webpack, Rollup,
Bundlers files (bundles) suitable for the browser. Parcel, Vite
Real-World Examples:
Answer: Hoisting is a JavaScript mechanism where variable and function declarations are
moved to the top of their containing scope during the compilation phase, before code
execution. Only the declaration is hoisted, not the initialization. var variables are initialized
with undefined , while let and const are also hoisted but remain uninitialized, leading to
a ReferenceError if accessed before the actual declaration (this is known as the
“Temporal Dead Zone”).
Answer: A closure is a function that retains access to its lexical scope (the variables in the
environment where it was declared), even after the outer function has finished executing.
They are essential for creating private variables and maintaining state.
function createCounter() {
let count = 0; // 'count' is a private variable
return function() {
count += 1;
return count;
};
}
const counter = createCounter();
[Link](counter()); // 1
[Link](counter()); // 2 (The inner function remembers 'count')
Method Call: this refers to the object the method is called on.
Explicit Binding: Using call() , apply() , or bind() , which explicitly set the value of
this .
Arrow Functions: Arrow functions do not have their own this . They inherit the this
value from their surrounding (lexical) scope.
Answer: Promises are objects that represent the eventual result of an asynchronous
operation, providing a structured way to handle success ( .then() ) and failure ( .catch() ).
Async/Await is a modern syntax built on top of Promises. It allows asynchronous code to be
written in a way that looks and behaves synchronously, making it much cleaner and easier
to read, especially when dealing with sequential asynchronous operations. async functions
implicitly return a Promise, and await pauses the function execution until the Promise
resolves.
Answer:
function flattenArray(arr) {
let result = [];
for (const element of arr) {
if ([Link](element)) {
result = [Link](flattenArray(element)); // Recursive call
} else {
[Link](element);
}
}
return result;
}
// Modern ES6 solution:
const flattenArrayES6 = (arr) => [Link](Infinity);
9. How would you prevent a user from submitting a form multiple times?
Answer:
1. Disable the Submit Button: Immediately after the first click, disable the submit
button using JavaScript ( [Link] = true; ).
2. Use a Flag Variable: Set a boolean flag ( isSubmitting = true ) when the submission
starts. Check this flag at the beginning of the submission handler and exit if it’s
already true. Reset the flag in the success or error callback of the API call.
Answer:
1. DOM Manipulation in Loops: Repeatedly accessing or modifying the DOM inside a
loop is slow. Instead, build the changes in memory (e.g., using a Document Fragment
or a single string) and apply them to the DOM once.
2. Global Variables: Excessive use of global variables can lead to namespace collisions
and make code harder to maintain.
4. Lack of Debouncing/Throttling: Not limiting the execution rate of event handlers for
events like scroll , resize , or keyup .
Answer: The TDZ is the period of time during which let and const variables exist but
cannot be accessed. It starts from the beginning of the variable’s scope and ends when the
variable is declared and initialized. Attempting to access a variable in the TDZ results in a
ReferenceError . This is a key difference from var , which is initialized with undefined
when hoisted.
End of Document