JavaScript Foundations
Comprehensive Interview Notes & Code Examples
1. Data Types
JavaScript variables can hold different data types. Understanding these is fundamental to avoiding bugs
during comparisons or operations.
• String : Represents text, e.g., "hello world" . You can use [Link] to determine the
number of characters [cite: 1].
• Number : Represents both integer and floating-point numbers, e.g., 1234567 [cite: 1].
• Boolean : Logical entities holding true or false [cite: 1].
• Undefined : Indicates that a variable has been declared but has not yet been initialized (assigned
a value) [cite: 1].
• Null : Indicates an intentional absence of any object value (intentionally unassigned) [cite: 1].
Additional Types (ES6+): Modern JavaScript also includes Symbol (for unique identifiers) and
BigInt (for exceptionally large numbers).
2. Variables (let, const, var)
How you declare variables determines their scope and reassignment rules [cite: 1].
• var : Function-scoped. If declared inside a function, it is accessible throughout that entire function
[cite: 1].
• let : Block-scoped. Accessible only within the immediate block {} where it is declared [cite: 1].
• const : Block-scoped and cannot be reassigned after its initial declaration. Use this by default for
arrays and objects unless you need to reassign the entire variable.
3. Operators & Conditions
Comparison Operators
Comparisons evaluate to a boolean value [cite: 2].
• == (Loose Equality): Checks only the value, performing type coercion if necessary. E.g., "5" ==
5 returns true [cite: 1].
• === (Strict Equality): Checks both the value and the datatype. E.g., "5" === 5 returns false
[cite: 2].
• Others: !== (strict not equal), >= , <= , < , > [cite: 2].
Logical Operators
• && (AND): True if both operands are true [cite: 2].
• || (OR): True if at least one operand is true [cite: 2].
• ! (NOT): Reverses the boolean state [cite: 3].
Truthy vs. Falsy Values
When evaluated in a boolean context (like an if statement), values are coerced to true or false.
• Falsy values: undefined , null , NaN , 0 , "" (empty string), and false [cite: 3].
• Truthy values: All numbers except zero, all strings (even "false" ), and all objects/arrays (even
empty ones like [] and {} ) [cite: 3].
Conditional Statements
Used to perform different actions based on different conditions [cite: 2]. You can dynamically construct
strings using template literals (backticks) and ${variable} injection [cite: 2].
Ternary Operator
A shortcut to write a one-line if/else statement [cite: 3]. The syntax is condition ? if_true :
if_false [cite: 4].
let age = 22;
// Returns "go to website" if true, "you are not eligible" if false
let status = age >= 18 ? "go to website" : "you are not eligible" [cite: 4, 5];
4. Loops
Loops repeat a block of code over and over until a specific condition is satisfied [cite: 5].
• For Loop: Best when you know exactly how many times to iterate.
let plants = ["Jasmine", "Mint", "Rose", "Bougainvillea"];
for (let i = 0; i < [Link]; i++) {
[Link]("Watering " + plants[i]);
} [cite: 5, 6]
• While Loop: Evaluates the condition before each iteration [cite: 6].
• Do-While Loop: Will execute the block at least once before checking the condition [cite: 6].
5. Functions
Functions are reusable blocks of code that perform specific tasks [cite: 6]. Values can be passed as
arguments, making them dynamic, and results are passed back using the return keyword [cite: 6].
Function Declarations vs Arrow Functions
// Standard Function Declaration
function applyMicroclimate(layer1, layer2) {
return `Layering ${layer1} over ${layer2} to block heat.`;
}
// Arrow Function Syntax [cite: 6]
const calculateShade = (temperature) => {
return temperature > 35 ? "Use green net" : "Direct sunlight ok";
}
6. Arrays & Iteration Methods
Arrays store multiple values (typically of the same datatype) into a single variable [cite: 6, 7].
• push() : Adds an element to the end of an array. This is a mutated method (it changes the
original array) [cite: 7].
• filter() : Returns a new array containing elements that pass a specific condition. It is a non-
mutated method [cite: 7].
let candidates = [18, 20, 16, 15, 21]; [cite: 7]
// Filter candidates aged 18 and above
let eligible = [Link](age => age >= 18); [cite: 8]
• map() : Uses a callback function to transform elements of an array. It creates a new array
(cloned) and does not mutate the original [cite: 10].
let salariesUSD = [10, 20, 30, 40]; [cite: 10]
let salariesAUD = [Link](salary => {
return salary * 1.5;
}); [cite: 11]
7. Objects
Objects are used to store multiple data types into a single variable using key-value pairs [cite: 12].
let agencyTeam = [
{ name: "Mubasir", role: "Manager", email: "mubasir@[Link]" },
{ name: "Sufyan", role: "SEO Specialist", email: "sufyan@[Link]" }
];
// Adding a new user using an arrow function [cite: 12]
const addTeamMember = (name, role, email) => {
[Link]({ name, role, email }); // ES6 shorthand
}
8. The DOM (Document Object Model)
The DOM allows JavaScript to dynamically interact with, change the content of, and style elements on a
webpage [cite: 12]. When the browser loads an HTML document, it creates a hierarchical tree structure
of objects representing every element on the page.
Modern Context: While modern frontend stacks like React, Vite, and Tailwind abstract direct DOM
manipulation through the Virtual DOM, understanding vanilla DOM traversal and mutation is crucial
for integrating third-party scripts, handling complex ref optimizations, and deep debugging.
Selecting Elements
To manipulate the page, you must first "grab" the HTML element from the DOM tree.
• [Link]('header') : Selects a single element with the exact ID.
• [Link]('.btn-primary') : Selects the first element matching the CSS
selector.
• [Link]('[Link]') : Returns a NodeList of all elements matching the
selector.
Manipulating Elements
Once selected, you can modify an element's properties:
const titleEl = [Link]('job-portal-title');
// Change text content (safe from XSS)
[Link] = "Candidate Dashboard";
// Change HTML structure inside the element
[Link] = "Candidate Dashboard (Live)";
// Manipulate inline styles
[Link] = "#3b82f6";
[Link] = "none";
Modifying Classes
Instead of direct inline styles, it's best practice to toggle CSS classes (especially when using frameworks
like Tailwind).
const navBar = [Link]('nav');
[Link]('bg-gray-800'); // Adds a class
[Link]('bg-transparent'); // Removes a class
[Link]('hidden'); // Toggles a class on/off
Creating and Appending Elements
You can generate entirely new HTML elements purely through JavaScript.
// 1. Create the new element
const newListing = [Link]('li');
// 2. Add content to it
[Link] = "Frontend Developer - React/Vite";
[Link]('job-item');
// 3. Select the parent container
const listContainer = [Link]('job-list');
// 4. Append it to the DOM
[Link](newListing);
Event Listeners
Event listeners wait for user interactions (clicks, keypresses, forms submitting) and execute a callback
function in response.
const submitBtn = [Link]('submit-btn');
[Link]('click', (event) => {
// Prevents the default form submission behavior
[Link]();
[Link]("Form processing initialized...");
});