Top 20 Technical Interview Questions for Junior Developers - MockThatInterview Blog

Master these essential technical interview questions for junior developers. Get detailed answers, coding examples, and preparation tips for your next tech interview.

💡Interview Tips
12 min read

Top 20 Technical Interview Questions for Junior Developers

Master these essential technical interview questions for junior developers. Get detailed answers, coding examples, and preparation tips for your next tech interview.

By Mockthatinterview Team
2025-01-15
Top 20 Technical Interview Questions for Junior Developers

Top 20 Technical Interview Questions for Junior Developers

Technical interviews can be intimidating, especially for junior developers and coding bootcamp graduates. However, with proper preparation and understanding of common question patterns, you can approach these interviews with confidence. This comprehensive guide covers the 20 most important technical interview questions you're likely to encounter.

Fundamental Programming Concepts

1. "Explain the difference between let, const, and var in JavaScript"

This is a fundamental question that tests your understanding of variable declarations and scope.

Key points to cover:

  • var: Function-scoped, can be redeclared, hoisted
  • let: Block-scoped, cannot be redeclared, temporal dead zone
  • const: Block-scoped, cannot be reassigned, must be initialized

Example answer:

// var - function scoped, can be redeclared
function example() {
    var x = 1;
    if (true) {
        var x = 2; // Same variable
        console.log(x); // 2
    }
    console.log(x); // 2
}

// let - block scoped, cannot be redeclared
function example() {
    let x = 1;
    if (true) {
        let x = 2; // Different variable
        console.log(x); // 2
    }
    console.log(x); // 1
}

// const - block scoped, cannot be reassigned
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable

2. "What is the difference between == and === in JavaScript?"

This tests your understanding of type coercion and strict equality.

Key differences:

  • ==: Performs type coercion before comparison
  • ===: Strict equality, no type coercion

Examples:

console.log(5 == "5");   // true (type coercion)
console.log(5 === "5");  // false (strict comparison)
console.log(null == undefined);  // true
console.log(null === undefined); // false

3. "Explain closures in JavaScript"

Closures are a fundamental concept that many developers struggle with initially.

Definition: A closure is a function that has access to variables in its outer (enclosing) scope even after the outer function returns.

Example:

function outerFunction(x) {
    // Outer function's variable
    return function innerFunction(y) {
        // Inner function has access to x
        return x + y;
    };
}

const addFive = outerFunction(5);
console.log(addFive(3)); // 8

Real-world use case:

function createCounter() {
    let count = 0;
    return {
        increment: () => ++count,
        decrement: () => --count,
        getCount: () => count
    };
}

const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2

Data Structures and Algorithms

4. "Implement a function to reverse a string"

This tests basic string manipulation and algorithm thinking.

Multiple approaches:

// Method 1: Using built-in methods
function reverseString1(str) {
    return str.split('').reverse().join('');
}

// Method 2: Using a loop
function reverseString2(str) {
    let reversed = '';
    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return reversed;
}

// Method 3: Using recursion
function reverseString3(str) {
    if (str === '') return '';
    return reverseString3(str.substr(1)) + str.charAt(0);
}

5. "Find the largest number in an array"

Tests array manipulation and basic algorithm skills.

Solutions:

// Method 1: Using Math.max with spread operator
function findLargest1(arr) {
    return Math.max(...arr);
}

// Method 2: Using reduce
function findLargest2(arr) {
    return arr.reduce((max, current) => current > max ? current : max);
}

// Method 3: Using a loop
function findLargest3(arr) {
    let max = arr[0];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

6. "Check if a string is a palindrome"

Tests string manipulation and algorithm thinking.

Solution:

function isPalindrome(str) {
    // Remove non-alphanumeric characters and convert to lowercase
    const cleaned = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
    
    // Compare with reversed string
    return cleaned === cleaned.split('').reverse().join('');
}

// Test cases
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("A man a plan a canal Panama")); // true
console.log(isPalindrome("hello")); // false

7. "Implement a function to find duplicates in an array"

Tests array manipulation and object/Set usage.

Multiple approaches:

// Method 1: Using Set
function findDuplicates1(arr) {
    const seen = new Set();
    const duplicates = new Set();
    
    for (const item of arr) {
        if (seen.has(item)) {
            duplicates.add(item);
        } else {
            seen.add(item);
        }
    }
    
    return Array.from(duplicates);
}

// Method 2: Using object
function findDuplicates2(arr) {
    const counts = {};
    const duplicates = [];
    
    for (const item of arr) {
        counts[item] = (counts[item] || 0) + 1;
        if (counts[item] === 2) {
            duplicates.push(item);
        }
    }
    
    return duplicates;
}

Object-Oriented Programming

8. "Explain the difference between class and function constructors"

Tests understanding of object creation patterns.

Function constructor:

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.greet = function() {
    return `Hello, I'm ${this.name}`;
};

const person1 = new Person("John", 30);

ES6 Class:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        return `Hello, I'm ${this.name}`;
    }
}

const person1 = new Person("John", 30);

9. "What is inheritance and how do you implement it?"

Tests understanding of OOP principles.

ES6 Class inheritance:

class Animal {
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        return `${this.name} makes a sound`;
    }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name);
        this.breed = breed;
    }
    
    speak() {
        return `${this.name} barks`;
    }
    
    fetch() {
        return `${this.name} fetches the ball`;
    }
}

const dog = new Dog("Buddy", "Golden Retriever");
console.log(dog.speak()); // "Buddy barks"
console.log(dog.fetch()); // "Buddy fetches the ball"

Asynchronous Programming

10. "Explain the difference between callbacks, promises, and async/await"

Tests understanding of asynchronous JavaScript patterns.

Callbacks:

function fetchData(callback) {
    setTimeout(() => {
        callback("Data received");
    }, 1000);
}

fetchData((data) => {
    console.log(data);
});

Promises:

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Data received");
        }, 1000);
    });
}

fetchData()
    .then(data => console.log(data))
    .catch(error => console.error(error));

Async/Await:

async function fetchData() {
    try {
        const data = await fetchData();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

11. "How do you handle multiple promises?"

Tests understanding of promise handling patterns.

Promise.all:

const promise1 = fetch('/api/data1');
const promise2 = fetch('/api/data2');
const promise3 = fetch('/api/data3');

Promise.all([promise1, promise2, promise3])
    .then(responses => {
        // All promises resolved
        console.log('All data received');
    })
    .catch(error => {
        // Any promise rejected
        console.error('One or more requests failed');
    });

Promise.allSettled:

Promise.allSettled([promise1, promise2, promise3])
    .then(results => {
        results.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                console.log(`Promise ${index} succeeded`);
            } else {
                console.log(`Promise ${index} failed`);
            }
        });
    });

Web Development Concepts

12. "Explain the difference between GET and POST requests"

Tests understanding of HTTP methods.

GET requests:

  • Used to retrieve data
  • Parameters sent in URL
  • Can be cached
  • Idempotent (same result multiple times)
  • Limited data size

POST requests:

  • Used to send data
  • Parameters sent in request body
  • Not cached
  • Not idempotent
  • No data size limit

Example:

// GET request
fetch('/api/users?id=123')
    .then(response => response.json())
    .then(data => console.log(data));

// POST request
fetch('/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        name: 'John Doe',
        email: 'john@example.com'
    })
})
.then(response => response.json())
.then(data => console.log(data));

13. "What is the DOM and how do you manipulate it?"

Tests understanding of web development fundamentals.

DOM manipulation:

// Select elements
const element = document.getElementById('myId');
const elements = document.querySelectorAll('.myClass');

// Create elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello World';

// Add to DOM
document.body.appendChild(newDiv);

// Modify attributes
element.setAttribute('class', 'newClass');
element.style.color = 'red';

// Event listeners
element.addEventListener('click', function() {
    console.log('Element clicked');
});

14. "Explain CORS and how to handle it"

Tests understanding of web security and cross-origin requests.

CORS (Cross-Origin Resource Sharing):

  • Browser security feature
  • Prevents requests from different origins
  • Server must include CORS headers

Handling CORS:

// Server-side (Node.js/Express example)
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

// Client-side
fetch('https://api.example.com/data', {
    method: 'GET',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',
    }
})
.then(response => response.json())
.then(data => console.log(data));

Database and Data Management

15. "Explain the difference between SQL and NoSQL databases"

Tests understanding of database concepts.

SQL Databases:

  • Relational databases
  • Structured data with tables, rows, columns
  • ACID properties
  • Examples: MySQL, PostgreSQL, SQLite

NoSQL Databases:

  • Non-relational databases
  • Flexible schema
  • Different data models (document, key-value, graph)
  • Examples: MongoDB, Redis, Neo4j

Example queries:

-- SQL
SELECT * FROM users WHERE age > 25;

-- MongoDB (NoSQL)
db.users.find({ age: { $gt: 25 } });

16. "What is normalization in databases?"

Tests understanding of database design principles.

Normalization levels:

  • 1NF: Eliminate duplicate columns
  • 2NF: Remove partial dependencies
  • 3NF: Remove transitive dependencies

Example:

-- Before normalization (denormalized)
CREATE TABLE orders (
    order_id INT,
    customer_name VARCHAR(100),
    customer_email VARCHAR(100),
    product_name VARCHAR(100),
    product_price DECIMAL(10,2),
    order_date DATE
);

-- After normalization
CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE products (
    product_id INT PRIMARY KEY,
    name VARCHAR(100),
    price DECIMAL(10,2)
);

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    product_id INT,
    order_date DATE,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

System Design Basics

17. "How would you design a URL shortener like bit.ly?"

Tests basic system design thinking.

Key components:

  1. URL shortening service
  2. Database to store mappings
  3. Redirect service
  4. Analytics tracking

Basic implementation:

class URLShortener {
    constructor() {
        this.urlMap = new Map();
        this.baseUrl = 'https://short.ly/';
    }
    
    shorten(longUrl) {
        const shortCode = this.generateShortCode();
        this.urlMap.set(shortCode, longUrl);
        return this.baseUrl + shortCode;
    }
    
    redirect(shortCode) {
        return this.urlMap.get(shortCode);
    }
    
    generateShortCode() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < 6; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }
}

18. "Explain load balancing and why it's important"

Tests understanding of scalability concepts.

Load balancing benefits:

  • Distribute traffic across multiple servers
  • Improve performance and availability
  • Handle traffic spikes
  • Provide redundancy

Types of load balancing:

  • Round Robin: Distribute requests evenly
  • Least Connections: Route to server with fewest active connections
  • IP Hash: Route based on client IP
  • Weighted: Assign different weights to servers

Testing and Debugging

19. "How do you debug JavaScript code?"

Tests practical debugging skills.

Debugging techniques:

// 1. Console logging
console.log('Variable value:', variable);
console.table(arrayData);
console.group('Debug Group');
console.log('Nested information');
console.groupEnd();

// 2. Breakpoints in browser dev tools
// Set breakpoints in Sources tab

// 3. Error handling
try {
    // Risky code
    const result = riskyFunction();
} catch (error) {
    console.error('Error occurred:', error.message);
    // Handle error gracefully
}

// 4. Assertions
function assert(condition, message) {
    if (!condition) {
        throw new Error(message);
    }
}

assert(user.age > 0, 'User age must be positive');

20. "Write a simple unit test for a function"

Tests understanding of testing concepts.

Function to test:

function add(a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw new Error('Both arguments must be numbers');
    }
    return a + b;
}

Unit test:

// Simple test framework
function test(description, testFunction) {
    try {
        testFunction();
        console.log(`✓ ${description}`);
    } catch (error) {
        console.log(`✗ ${description}: ${error.message}`);
    }
}

function expect(actual) {
    return {
        toBe: function(expected) {
            if (actual !== expected) {
                throw new Error(`Expected ${expected}, but got ${actual}`);
            }
        },
        toThrow: function(expectedError) {
            try {
                actual();
                throw new Error('Expected function to throw an error');
            } catch (error) {
                if (error.message !== expectedError) {
                    throw new Error(`Expected error "${expectedError}", but got "${error.message}"`);
                }
            }
        }
    };
}

// Test cases
test('add should return sum of two numbers', () => {
    expect(add(2, 3)).toBe(5);
});

test('add should throw error for non-number inputs', () => {
    expect(() => add('2', 3)).toThrow('Both arguments must be numbers');
});

Interview Preparation Tips

1. Practice Coding Problems

Recommended resources:

  • LeetCode (start with easy problems)
  • HackerRank
  • Codewars
  • FreeCodeCamp algorithms

Practice strategy:

  • Start with easy problems
  • Focus on understanding patterns
  • Practice explaining your thought process
  • Time yourself to simulate interview conditions

2. Mock Interview Practice

Benefits of mock interviews:

  • Practice explaining your code
  • Get feedback on your approach
  • Build confidence
  • Identify knowledge gaps

Mock interview platforms:

  • MockThatInterview
  • Pramp
  • Interviewing.io
  • Practice with peers

3. Study System Design Basics

Key concepts to understand:

  • Scalability principles
  • Database design
  • Caching strategies
  • Load balancing
  • Microservices architecture

4. Prepare Your Questions

Good questions to ask:

  • "What does a typical day look like for this role?"
  • "What technologies does the team use?"
  • "How do you handle code reviews?"
  • "What opportunities are there for learning and growth?"
  • "What are the biggest challenges facing the team?"

Conclusion

Technical interviews can be challenging, but with proper preparation and practice, you can succeed. Focus on understanding fundamental concepts, practice coding problems regularly, and don't forget to prepare questions to ask your interviewer.

Key takeaways:

  • Master fundamental programming concepts
  • Practice coding problems daily
  • Understand web development basics
  • Learn system design principles
  • Practice explaining your code
  • Prepare thoughtful questions

Remember, technical interviews are not just about getting the right answer, they're about demonstrating your problem-solving process, communication skills, and ability to learn. Approach each interview as a learning opportunity, and you'll continue to improve with each experience.

Start practicing these questions today, and you'll be well-prepared for your next technical interview!