📚 JavaScript Fundamentals Notes
1. Introduction & Setup
Purpose: JavaScript (JS) is a programming language used to create
dynamic and interactive web pages. It runs on the web browser.
Prerequisites: Recommended to know HTML and CSS first.
Tools: A text editor (e.g., VS Code) and the Live Server extension are
recommended.
File Structure: Typically requires three files:
o [Link] (Structure/Homepage)
o [Link] (Style/Appearance)
o [Link] (Actions/Interactivity)
Linking Files:
o CSS: <link rel="stylesheet" href="[Link]"> (in <head>)
o JS: <script src="[Link]"></script> (Best placed just before the
closing </body> tag to ensure HTML elements render first.)
Output:
o To console: [Link]("Hello!"); (View in Dev Tools -> Console)
o To a popup box: [Link]("This is an alert!");
Comments:
o Single-line: // This is a comment
o Multi-line: /* This is a multi-line comment */
Updating HTML Content:
o Get Element: [Link]("myId")
o Update Text: .textContent = "New Text";
2. Variables & Data Types
Variable: A container that stores a value.
Steps to Create:
1. Declaration: let x; (using the let keyword)
2. Assignment: x = 100;
o Combined: let x = 123;
Naming: Variable names must be unique within their scope.
Data Types:
o Number: Whole numbers or decimals (e.g., 123, 10.99).
o String: A series of characters (text). Can use double quotes (""),
single quotes (''), or backticks (``).
o Boolean: Either true or false.
Template Literals (Backticks): Used for easy string formatting and
inserting variables:
o [Link](Your name is ${firstName});
Type Checking: [Link](typeof age);
const Keyword (Constants): Declares variables that cannot be
changed once assigned (e.g., mathematical constants like Pi). Good
practice to name constants in UPPERCASE.
3. Arithmetic, Math & Type Conversion
Arithmetic Operators:
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o ** (Exponentiation)
o % (Modulus/Remainder)
Augmented Assignment Operators (Shorthand):
o students += 1; (Equivalent to students = students + 1;)
o students -= 1;
o students *= 2;
o students /= 2;
o students %= 2;
Increment/Decrement: i++ (add 1), i-- (subtract 1)
Operator Precedence (Order of Operations): Parentheses () >
Exponents ** > Multiplication/Division/Modulus */% > Addition/Subtraction
+-
Type Conversion: Changing the data type of a value (e.g., a String to a
Number).
o Convert to Number: Number(value)
o Convert to String: String(value)
o Convert to Boolean: Boolean(value) (An empty string, 0, or
undefined converts to false; any other value converts to true).
Math Object: A built-in JS object with math-related properties/methods.
o Properties: [Link]
o Methods: [Link](), [Link]() (round down), [Link]()
(round up), [Link](base, exp), [Link](), [Link](),
[Link]().
Random Numbers: [Link]([Link]() * max) + min; (Generates
a random integer between min and max inclusive).
4. User Input & Conditionals
Input (Easy Way): let username = [Link]("What's your
username?"); (Input is always a String).
Input (Professional Way): Use an <input type="text"> and a <button>
with an onclick event to retrieve the value:
o [Link]("myText").value;
if Statement: Executes code if a condition is true.
o if (condition) { /* code if true */ }
else Statement: Executes code if the if condition is false.
else if Statement: Checks an additional condition if the previous if or
else if conditions were false.
Comparison Operators:
o > (Greater than), < (Less than), >= (Greater than or equal to), <=
(Less than or equal to)
o == (Equal to value, ignores data type - AVOID)
o != (Not equal to value, ignores data type - AVOID)
Strict Equality Operators (Recommended):
o === (Strictly equal to: value AND data type must match)
o !== (Strictly not equal to: value OR data type is different)
Logical Operators:
o && (AND): Both conditions must be true.
o || (OR): At least one condition must be true.
o ! (NOT): Flips a boolean value (true becomes false, false becomes
true).
checked Property: Used on checkboxes/radio buttons to see if they are
selected (returns true or false).
o [Link]("myCheckbox").checked
Ternary Operator (Shorthand if-else):
o let message = (age >= 18) ? "You're an adult" : "You're a minor";
o Syntax: condition ? value_if_true : value_if_false;
switch Statement: An efficient alternative to many else if statements.
o Checks a value against multiple case conditions. Requires a break
after each case to prevent "fall-through."
o default: Executes if no case matches.
5. Strings, Loops & Arrays
String Methods:
o .charAt(index): Returns the character at a specific index (starting at
0).
o .indexOf(char): Returns the index of the first occurrence.
o .lastIndexOf(char): Returns the index of the last occurrence.
o .length: Returns the length (a property, not a method).
o .trim(): Removes whitespace from both ends of a string.
o .toUpperCase(), .toLowerCase()
o .repeat(n): Repeats the string n times.
o .startsWith(str), .endsWith(str): Returns true or false.
o .includes(str): Returns true if the string contains the substring.
o .replaceAll(old, new): Replaces all occurrences of a substring.
o .padStart(len, char), .padEnd(len, char): Adds padding characters.
String Slicing: Creates a substring from a portion of another string (does
not alter the original string).
o .slice(startIndex, endIndex): endIndex is exclusive.
o Negative indices work from the end of the string.
Method Chaining: Calling one method after another in a continuous line
of code.
Loops:
o while Loop: Repeats code while a condition is true. (Be cautious of
infinite loops).
o do-while Loop: Executes the code at least once, then checks the
condition.
o for Loop: Repeats code a limited amount of times.
Syntax: for (let i = start; condition; increment/decrement) { /*
code */ }
o for...of Loop (Enhanced Loop): Iterates over the elements of an
array.
Syntax: for (let element of arrayName) { /* code */ }
o continue: Skips the current iteration of the loop.
o break: Exits the loop entirely.
Arrays: A variable-like structure that holds more than one value.
o Declaration: let fruits = ["apple", "orange", "banana"];
o Accessing Elements: fruits[0] (always starts at index 0).
o Length: [Link]
o Adding/Removing:
.push(element): Adds to the end.
.pop(): Removes from the end.
.unshift(element): Adds to the beginning.
.shift(): Removes from the beginning.
o .indexOf(element): Returns index, or -1 if not found.
o .sort(), .reverse()
Spread Operator (...): Expands an iterable (like an array or string) into
separate elements (e.g., used with [Link]() on an array).
6. Functions & Scope
Function: A section of reusable code declared once and executed by
calling it.
o Declaration: function functionName(parameters) { /* code */ }
o Execution (Call): functionName(arguments);
Parameters & Arguments: Parameters are placeholders in the
definition; arguments are the actual values passed when calling the
function. Order matters.
return Keyword: Sends a value back to the spot where the function was
called. A function call effectively becomes the returned value.
Rest Parameters (...): A parameter prefixed with three dots that
bundles a variable number of arguments into an array. (Opposite of the
spread operator).
Variable Scope: Where a variable is recognized and accessible.
o Local Scope: Variable declared inside a function (or curly braces).
Only accessible within that scope.
o Global Scope: Variable declared outside a function. Accessible
throughout the whole program.
Function Expression: Defining a function as a value or a variable.
o const hello = function() { [Link]("Hello!"); };
Arrow Function (ES6): A concise way to write a function expression.
Great for simple, one-time use functions.
o Syntax: const hello = (parameters) => { /* code */ };
o Shorthand (single parameter/return): const square = element =>
element * element;
7. Object-Oriented Programming (OOP)
Object: A collection of related properties (things an object has) and
methods (functions an object can do).
o Declaration: const person = { key: value, method: function() { /*
code */ } };
this Keyword: A reference to the object where this is used. The
referenced object depends on the immediate context.
o Example: [Link] inside a person object's method refers to that
person's name property.
Constructor: A special function (traditionally) or method (in a class) used
for defining the initial properties and methods of objects.
Classes (ES6): Provides a structured and cleaner way to define objects (a
blueprint).
o Declaration: class ClassName { constructor(params) { [Link] =
param; } method() { /* code */ } }
static Keyword: Defines properties or methods that belong to the class
itself, not the individual objects created from it. Accessed via
[Link].
Inheritance: Allows a new "child" class to inherit properties and
methods from an existing "parent" class.
o Child class declaration: class ChildClass extends ParentClass { ... }
super Keyword: Used in a child class to call the constructor or access
properties/methods of its parent (super class).
Getters & Setters: Special methods for properties:
o Getter (get propName): Makes a property readable and allows
computed properties (e.g., getting area).
o Setter (set propName(newValue)): Makes a property writable
and is used for input validation before a property is updated.
Nested Objects: Objects inside of other objects, allowing for more
complex data structures.
Array of Objects: An array where each element is an object.
Destructuring (ES6): Conveniently extracts values from arrays and
objects and assigns them to variables.
o Array: const [first, second] = myArray;
o Object: const { name, age } = myObject;
8. Array Iteration Methods
forEach(): Iterates through the elements of an array and applies a
function (callback) to each element.
o Purpose: To modify the original array or simply perform an action
(e.g., [Link]) for each element.
o It does not return a new array.
map(): Accepts a callback, applies that function to each element, and
returns a brand new array with the results.
o Purpose: To transform an array's elements into a new format (e.g.,
convert Celsius to Fahrenheit, transform names to uppercase).
o It preserves the original array.
filter(): Accepts a callback, applies a condition to each element, and
returns a brand new array containing only the elements that return
true.
o Purpose: To create a subset of an array (e.g., filter out only even
numbers, find students over 18).
reduce(): Reduces the elements of an array to a single value.
o Purpose: To calculate a sum, find a max/min value, or tally items.
o Requires two parameters in the callback: an accumulator (the
running result) and the current element.
sort(): Sorts array elements in place.
o By default, sorts lexicographically (as strings).
o To sort numbers: Use a custom comparison function: .sort((a, b) =>
a - b) for ascending.
9. Asynchronous JavaScript & APIs
Synchronous Code: Executes line by line, waiting for each operation to
complete before moving on.
Asynchronous Code: Allows multiple operations concurrently without
blocking the execution flow. (e.g., network requests, fetching data).
Callback: A function passed as an argument to another function, ensuring
it executes only after an asynchronous operation completes.
Callback Hell: A difficult-to-read situation where callbacks are nested
within other callbacks (avoid this!).
setTimeout(callback, delay): Schedules the execution of a function
once after a specified delay (in milliseconds). (Asynchronous).
setInterval(callback, interval): Calls a function repeatedly with a fixed
time delay between calls. (Asynchronous).
Promises: An object that manages asynchronous operations. It is either:
o Pending: The operation is ongoing.
o Resolved: The operation completed successfully.
o Rejected: The operation failed.
o Chained using .then() for success and .catch() for failure.
async & await (ES6): Allows you to write asynchronous code in a linear,
synchronous-looking manner.
o async: Precedes a function declaration, making it return a promise.
o await: Used inside an async function to pause execution until a
promise resolves.
JSON (JavaScript Object Notation): A data interchange format (data is
represented as a single string).
o [Link](object): Converts a JS object/array to a JSON string.
o [Link](jsonString): Converts a JSON string to a JS object/array.
fetch(url): A function used for making HTTP requests (e.g., to an API) to
fetch resources. Returns a promise.
o Typically followed by .then(response => [Link]()) to convert
the data.
10. DOM Manipulation & Events
DOM (Document Object Model): A JS object that represents the HTML
page and provides an API to interact with it.
Element Selectors: Methods to target HTML elements:
o [Link]("id"): Returns a single element (or null).
o [Link]("class"): Returns an HTML
Collection (live but limited methods).
o [Link]("selector"): Returns the first matching
element (or null).
o [Link]("selector"): Returns a NodeList (static
but has .forEach()).
DOM Navigation: Properties to move between elements:
o .firstElementChild, .lastElementChild
o .nextElementSibling, .previousElementSibling
o .parentElement, .children (returns an HTML Collection)
Adding/Changing Elements:
1. Create: [Link]("elementName")
2. Modify: Set .textContent, .style, .setAttribute(), etc.
3. Append: [Link](child) (or .prepend(), .insertBefore())
Event Listeners: Listen for specific events on elements or the document.
o Syntax: [Link]("eventType", callbackFunction);
Mouse Events:
o click: When an element is clicked.
o mouseover: When the cursor hovers over an element.
o mouseout: When the cursor leaves an element.
o The browser passes an event object with details about the
interaction.
Key Events (on document):
o keydown: When a key is pressed down.
o keyup: When a key is released.
classList Property: Used to interact with an element's list of CSS classes.
o .[Link]("class-name")
o .[Link]("class-name")
o .[Link]("class-name") (Add if absent, remove if present)
o .[Link]("class-name") (Returns true or false)