50 Beginner Programming Interview Questions (with Answers)
The questions a junior dev actually gets in a real interview, mapped to the 13 core concepts. Each answer is the kind a hiring manager wants to hear β direct, correct, no fluff.
Pick a concept you're weak on. Read the question. Try to answer aloud before reading the answer. If you trip over wording, you'll trip in the interview. Practice articulating, not just reading.
Variables (5 Qs)
What is the difference between let, const, and var?
let is block-scoped and reassignable. const is block-scoped and lock once assigned (the binding, not the contents β a const object can still be mutated). var is function-scoped and hoisted; it predates the others and is rarely used in modern code. Prefer const by default; use let when you need to reassign.
Explain "hoisting" in JavaScript.
JavaScript moves declarations to the top of their scope at parse time. var declarations are hoisted and initialized to undefined; function declarations are fully hoisted; let and const are hoisted but not initialized (the "temporal dead zone"). Practically: relying on hoisting hurts readability.
What's the difference between an immutable and a mutable variable?
A binding is "immutable" if you can't reassign it (const, final). A value is "immutable" if you can't change its contents (frozen object, primitive number). The distinction matters: const obj = {}; obj.x = 1 is legal β the binding is locked but the object isn't.
What is variable shadowing?
When a variable in a smaller scope reuses the name of a variable in an outer scope. The inner shadows the outer for the duration of its scope. Legal in most languages but a readability red flag.
When would you choose const over let?
By default β for any value that won't be reassigned. const protects against accidental reassignment, signals intent to readers, and helps optimizers. Use let only when reassignment is required.
Data Types (4 Qs)
What's the difference between null and undefined in JavaScript?
null is an explicit "no value" marker. undefined means a variable was declared but never assigned. Practically: assign null deliberately; undefined usually appears by accident.
Why does 0.1 + 0.2 not equal 0.3?
Floats use IEEE 754 binary representation, which can't exactly represent every decimal. 0.1 + 0.2 is actually 0.30000000000000004. Compare with a tolerance.
What is type coercion?
Automatic conversion between types β common in JS, rare in Python. "5" + 3 coerces 3 to a string and concatenates. === avoids coercion.
How do you check the type of a value?
typeof x in JS, type(x) in Python, x.getClass() in Java. (Note: typeof null === "object" is a famous JS quirk.)
Strings (3 Qs)
How do you check if a string contains a substring?
str.includes(sub) in JS, sub in str in Python, str.contains(sub) in Java.
Why is concatenating strings in a loop slow in some languages?
Strings are immutable, so each += creates a new string and copies the old contents. O(nΒ²) for n iterations. Use a builder: StringBuilder in Java, "".join(parts) in Python, or array + .join() in JS.
What's an f-string?
Python's syntax for embedding expressions inside strings: f"Hello, {name}!". Equivalent to JS template literals: `Hello, ${name}!`.
Operators (3 Qs)
What's the difference between == and === in JavaScript?
== compares with type coercion ("5" == 5 is true). === compares strictly ("5" === 5 is false). Always prefer ===.
What does the modulo operator do?
Returns the remainder of integer division. 10 % 3 is 1. Useful for "every Nth," circular indexing, even/odd checks.
What's the ternary operator?
condition ? a : b β returns a if true, b otherwise. One-line conditional expression.
Conditionals (4 Qs)
Explain truthy and falsy values in JavaScript.
Falsy values: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy β including "0", "false", {}, []. Conditions coerce values to boolean using these rules. Bug magnet for beginners.
What is short-circuit evaluation?
Logical operators stop evaluating once the result is determined. false && anything is false without running anything. Used for control flow: user && user.name, name || "Guest".
When should you use a switch over if/else?
Switch fits when comparing one value against many discrete cases. Many else if chains are equivalent but harder to scan. Modern alternative: a lookup object: { "Mon": handle, "Tue": handle }[day]?.().
What is a guard clause?
An early return at the top of a function that handles edge cases first, leaving the main logic un-nested. Replaces deep if (x) { if (y) { ... } } with if (!x) return; if (!y) return;.
Loops (4 Qs)
When do you use a for vs a while loop?
for when you know the iteration count or you're traversing a collection. while when you stop on a condition (e.g., reading until end of stream).
What does break do vs continue?
break exits the innermost loop immediately. continue skips the rest of the current iteration and proceeds to the next.
How would you find the first matching element in an array?
Use arr.find(predicate) in JS, next(x for x in arr if cond) in Python. Don't loop manually unless the language lacks the helper.
How do you avoid an infinite loop bug?
Make sure the loop variable is updated inside the body, the exit condition is reachable, and the variable is the right type. In dev tools, set a "max iterations" sanity check during early development.
Functions (8 Qs)
What's the difference between a function declaration and a function expression?
function f() {} is a declaration β hoisted, callable before its line. const f = function() {} or const f = () => {} is an expression β a value assigned to a variable, not hoisted.
What is a closure?
A function that captures references to variables in its enclosing scope, keeping them alive even after the outer function returns. Foundation of most callback patterns.
What's the difference between parameters and arguments?
Parameters are listed in the function definition; arguments are the actual values passed at call time. Often used interchangeably.
What is a pure function?
One whose output depends only on its input and that has no side effects. Same input β same output, every time. Easy to test, easy to reason about.
What is a higher-order function?
A function that takes another function as an argument or returns one. map, filter, reduce are HOFs.
What is recursion and when would you use it?
A function calling itself. Natural fit for tree-shaped data (file systems, ASTs, JSON), divide-and-conquer algorithms (merge sort, binary search), and problems with self-similar structure. Comes with risk of stack overflow on deep inputs.
What is a base case in recursion?
The condition under which the function returns without recursing further. Without one, recursion never stops and the stack overflows. Always write the base case first.
What is a callback?
A function passed as an argument to another function, to be called later (often after some async work). setTimeout(fn, 1000) takes a callback to run after 1s.
Arrays (6 Qs)
How do you copy an array (shallow)?
[...arr] in JS, arr.copy() in Python, arr.clone() in Java. All three create a new array; nested objects are still shared references.
What's the difference between map and forEach?
map returns a new array of transformed values. forEach just runs a function on each item and returns nothing.
How would you remove duplicates from an array?
In JS: [...new Set(arr)]. In Python: list(set(arr)) if order doesn't matter, or list(dict.fromkeys(arr)) if it does.
How do you sort numbers in JavaScript?
arr.sort((a, b) => a - b). The default sort coerces to strings, which gives wrong order for numbers ([10, 2, 1].sort() returns [1, 10, 2]).
What's the time complexity of array operations?
Index access: O(1). Push/pop at end: O(1) amortized. Insert/remove middle: O(n). Search: O(n) linear, O(log n) on sorted, O(1) with a hash set.
What is Big-O notation?
A way to describe how an algorithm's time or memory grows as input size grows. O(1) constant, O(log n) logarithmic, O(n) linear, O(nΒ²) quadratic. You don't need to derive it on day one, but you should recognize when nested loops over an array become expensive.
Objects (4 Qs)
How do you check if a key exists on an object?
"name" in user or user.hasOwnProperty("name") in JS. "name" in user in Python. map.containsKey("name") in Java.
How do you deep-clone an object?
In modern JS: structuredClone(obj). In Python: copy.deepcopy(obj). Spread ({...obj}) only does shallow.
What is destructuring?
A syntax for extracting values from objects/arrays into named variables: const { name, age } = user. Cleaner than const name = user.name; const age = user.age.
What's the difference between == and equals() for object comparison?
In Java, == compares references. .equals() compares contents (when properly implemented). For value comparison of objects, always use .equals().
Input Output (2 Qs)
What's the difference between stdout and stderr?
Both are output streams. stdout is for normal program output; stderr is for errors and diagnostics. They can be redirected separately, which is why production scripts often log errors to a different file.
How do you avoid SQL injection?
Never concatenate user input into a query string. Use parameterized queries / prepared statements: db.query("SELECT * FROM users WHERE name = ?", [name]).
Debugging (5 Qs)
What's the first thing you do when you see an error?
Read the error message slowly. Read the stack trace from the top to find the actual error, then walk down to find where in your code it happened. Beginners panic and ignore both β it's the single most expensive habit.
What is "rubber-duck debugging"?
Explaining your code aloud to an inanimate object. The act of articulating each step often reveals the bug. Senior engineers genuinely use this.
How do you debug a bug you can't reproduce?
Add logs around the suspect path, deploy with a flag, wait for it to recur, inspect the captured state. For race conditions, try increasing concurrency in a test environment.
What is git bisect?
A tool that does binary search across commits to find which one introduced a bug. You mark a known-good and known-bad commit; git checks out the middle one, you test, mark it good or bad, repeat. Finds the bad commit in log(n) steps.
How do you write a useful bug report?
Include: (1) what you did, (2) what you expected, (3) what actually happened, (4) environment (OS, browser, version), (5) steps to reproduce, (6) screenshot/error/log. The first three are the absolute minimum.
Comments (2 Qs)
When should you write a comment?
When the code can't express the why on its own. Examples: explaining a non-obvious choice, citing a workaround for a specific bug, documenting an interface someone else will use. Don't restate what the code obviously does.
What's the difference between a docstring and a regular comment?
A docstring is the first statement inside a function/class (Python) or a special comment (JSDoc, Javadoc). It's extracted by tools to generate documentation. Regular comments are just for human readers.