InterviewPitch
JavaScript interview questions

JavaScript Interview Questions with Answers

Most Asked JavaScript Interview Questions for Software Engineer Roles

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

This page provides a complete collection of JavaScript Interview Questions and Answers designed for frontend developers, full-stack developers, React developers, and professionals preparing for JavaScript technical interviews. JavaScript is one of the most popular programming languages used for web development. It enables developers to create interactive websites, frontend applications, backend services using Node.js, and modern frameworks like React, Angular, and Vue. This interview guide covers beginner, intermediate, and advanced JavaScript concepts including variables, functions, objects, arrays, closures, promises, async/await, ES6 features, DOM manipulation, event handling, JavaScript engine concepts, and real-world coding interview scenarios.

Why JavaScript?

  • Runs natively in every modern web browser – no compilation needed
  • Supports both frontend and backend (Node.js) – full‑stack development
  • Asynchronous and event‑driven – handles user interactions and API calls efficiently
  • Rich ecosystem with powerful libraries and frameworks (React, Angular, Vue, Express)
  • Massive community, continuous updates, and one of the most in‑demand skills in tech interviews

Most Asked JavaScript Interview Questions

Beginner
1. What is PHP?

PHP (Hypertext Preprocessor) is a widely-used open-source general-purpose scripting language especially suited for web development.

  • Server-side scripting: Runs on web servers
  • Dynamic typing: Flexible variable types
  • Web development: Built-in for HTML integration
  • Large ecosystem: Extensive package library
  • Database integration: PDO, MySQLi
javascript
// Hello World in JavaScript
console.log("Hello, World!");
Beginner
2. How to declare variables in PHP?

Variables in PHP are declared using the $ symbol. PHP is dynamically typed, so type declarations are optional.

  • Assignment: $x = 10;
  • Dynamic typing: Types are inferred at runtime
  • Constants: define('PI', 3.14159);
  • Global scope: Variables defined at top level
  • Local scope: Variables defined inside functions
javascript
// Variables in JavaScript
var old = "function scoped";
let block = "block scoped";
const constant = "cannot be reassigned";

console.log(old);
console.log(block);
console.log(constant);
Beginner
3. What are the data types in PHP?

PHP supports various data types including scalar, compound, and special types.

  • Integer: int
  • Float: float
  • String: string
  • Boolean: bool
  • Array: array
  • Object: object
  • NULL: null
  • Resource: resource
javascript
// Data Types in JavaScript
let str = "Hello";
let num = 42;
let bool = true;
let nul = null;
let undef = undefined;
let sym = Symbol("id");
let big = 9007199254740991n;
let obj = { name: "Alice", age: 25 };
let arr = [1, 2, 3];

console.log(typeof str);  // string
console.log(typeof num);  // number
console.log(typeof bool); // boolean
console.log(typeof nul);  // object (historical bug)
console.log(typeof undef); // undefined
console.log(typeof sym);  // symbol
console.log(typeof big);  // bigint
console.log(typeof obj);  // object
console.log(typeof arr);  // object
Beginner
4. How to define functions in PHP?

Functions in PHP are defined using the function keyword. They can have parameters, return values, and support type declarations.

  • Function declaration: function name($args) { ... }
  • Type declarations: function add(int $a, int $b): int
  • Anonymous functions: $fn = function($x) { return $x * 2; }
  • Arrow functions: fn($x) => $x * 2
  • Variable arguments: function sum(...$numbers)
javascript
// Functions in JavaScript
// Function declaration
function add(a, b) {
  return a + b;
}

// Function expression
const subtract = function(a, b) {
  return a - b;
};

// Arrow function
const multiply = (a, b) => a * b;

// Default parameters
function greet(name = "Guest") {
  return `Hello, ${name}!`;
}

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((acc, n) => acc + n, 0);
}

console.log(add(5, 3));
console.log(subtract(10, 4));
console.log(multiply(6, 7));
console.log(greet("Alice"));
console.log(sum(1, 2, 3, 4, 5));
Beginner
5. What are arrays in PHP?

PHP arrays are ordered maps that can hold values of any type. They can be indexed or associative.

  • Indexed arrays: [1, 2, 3]
  • Associative arrays: ['name' => 'Alice']
  • Multidimensional: Arrays within arrays
  • Functions: array_map, array_filter, array_reduce
  • Spread operator: [...$arr1, ...$arr2]
javascript
// Arrays in JavaScript
const arr = [1, 2, 3, 4, 5];

// Map - transform each element
const doubled = arr.map(x => x * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Filter - select elements
const evens = arr.filter(x => x % 2 === 0);
console.log(evens); // [2, 4]

// Reduce - aggregate
const sum = arr.reduce((acc, x) => acc + x, 0);
console.log(sum); // 15

// forEach - iterate
arr.forEach(x => console.log(x));

// Find - find first match
const found = arr.find(x => x > 3);
console.log(found); // 4

// Some - check if any match
const hasEven = arr.some(x => x % 2 === 0);
console.log(hasEven); // true

// Every - check if all match
const allEven = arr.every(x => x % 2 === 0);
console.log(allEven); // false
Beginner
6. What are associative arrays in PHP?

Associative arrays in PHP are arrays that use named keys instead of numeric indices, similar to dictionaries.

  • Creation: ['name' => 'Alice', 'age' => 25]
  • Access: $dict['name']
  • Add/Update: $dict['new_key'] = 'value'
  • Keys/Values: array_keys, array_values
  • Check: isset($dict['key'])
javascript
// Objects in JavaScript
// Object literal
const person = {
  name: "Alice",
  age: 25,
  city: "NYC",
  greet() {
    return `Hello, I'm ${this.name}`;
  }
};

console.log(person.name);
console.log(person.age);
console.log(person.greet());

// Object destructuring
const { name, age } = person;
console.log(name, age);

// Spread operator
const personCopy = { ...person, age: 26 };
console.log(personCopy);

// Object.keys, values, entries
console.log(Object.keys(person));
console.log(Object.values(person));
console.log(Object.entries(person));

// Object.assign
const merged = Object.assign({}, person, { country: "USA" });
console.log(merged);
Beginner
7. What are arrays as tuples in PHP?

PHP arrays can be used as tuples by using ordered lists of values without keys.

  • Creation: [1, 'hello', 3.14]
  • Access: $tuple[0]
  • Unpacking: [$a, $b, $c] = $tuple
  • Named tuples: Use associative arrays
  • Spread: [...$t1, ...$t2]
javascript
// DOM Manipulation
// Select elements
const element = document.getElementById("myId");
const elements = document.getElementsByClassName("myClass");
const query = document.querySelector(".myClass");
const all = document.querySelectorAll("div");

// Create elements
const div = document.createElement("div");
div.textContent = "Hello";
div.className = "my-class";
div.id = "my-id";
document.body.appendChild(div);

// Event listeners
button.addEventListener("click", function(e) {
  console.log("Clicked!", e.target);
});

// Remove element
element.remove();

// Get/Set attributes
const value = element.getAttribute("data-value");
element.setAttribute("data-value", "new");

// Class manipulation
element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");
element.classList.contains("active");

// InnerHTML vs textContent
element.innerHTML = "<span>HTML</span>";
element.textContent = "Plain text";
Beginner
8. What are control flow statements in PHP?

PHP provides standard control flow statements including conditionals, loops, and the match expression.

  • If-else: if ($condition) { ... }
  • Ternary: $x = $condition ? 'yes' : 'no'
  • Match: match($value) { 1 => 'one', default => 'other' }
  • For loops: for ($i = 0; $i < 10; $i++)
  • Foreach: foreach ($array as $key => $value)
javascript
// Events in JavaScript
// Click event
button.addEventListener("click", function(event) {
  console.log("Button clicked!", event);
});

// Mouse events
element.addEventListener("mouseenter", () => console.log("Mouse entered"));
element.addEventListener("mouseleave", () => console.log("Mouse left"));
element.addEventListener("mousemove", (e) => console.log(e.clientX, e.clientY));

// Keyboard events
document.addEventListener("keydown", (e) => {
  console.log(`Key ${e.key} pressed`);
});

// Form events
form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log("Form submitted");
});

input.addEventListener("change", (e) => {
  console.log("Value changed:", e.target.value);
});

input.addEventListener("input", (e) => {
  console.log("Input:", e.target.value);
});

// Event delegation
document.addEventListener("click", (e) => {
  if (e.target.matches(".button-class")) {
    console.log("Button clicked via delegation");
  }
});

// Remove event listener
button.removeEventListener("click", handler);
Beginner
9. How to generate arrays in PHP?

PHP provides several ways to generate arrays including range(), array_map(), and generators.

  • Range: range(1, 10)
  • Map: array_map(fn($x) => $x*2, $arr)
  • Filter: array_filter($arr, fn($x) => $x > 5)
  • Generator: function squares() { yield 1; yield 4; }
  • Comprehension: Using array_map with range
javascript
// Hoisting in JavaScript
// Function hoisting
console.log(add(2, 3)); // Works: 5
function add(a, b) {
  return a + b;
}

// Variable hoisting (var)
console.log(x); // undefined (not error)
var x = 10;
console.log(x); // 10

// Variable hoisting (let/const) - Temporal Dead Zone
// console.log(y); // ReferenceError
let y = 20;

// Function expression hoisting
// console.log(multiply(2, 3)); // TypeError
var multiply = function(a, b) {
  return a * b;
};

// Class hoisting
// const obj = new MyClass(); // ReferenceError
class MyClass {
  constructor() {
    this.name = "test";
  }
}
Beginner
10. How to work with strings in PHP?

PHP provides extensive string manipulation functions including concatenation, interpolation, and case conversion.

  • Concatenation: 'Hello' . ' ' . 'World'
  • Interpolation: "Hello $name"
  • Functions: strlen, strtoupper, strtolower
  • Substring: substr($str, 0, 5)
  • Split/Join: explode, implode
javascript
// Closures in JavaScript
// Basic closure
function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

// Closure with parameters
function multiplier(factor) {
  return function(number) {
    return number * factor;
  };
}
const double = multiplier(2);
console.log(double(5)); // 10

// Closure in loops
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100); // 3, 3, 3
}

// Fix with let
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100); // 0, 1, 2
}

// Private variables
function createCounter() {
  let count = 0;
  return {
    increment() { count++; },
    decrement() { count--; },
    getValue() { return count; }
  };
}
const counter2 = createCounter();
counter2.increment();
counter2.increment();
console.log(counter2.getValue()); // 2
Beginner
11. What are namespaces in PHP?

Namespaces in PHP provide a way to organize code and avoid name collisions.

  • Definition: namespace MyProject;
  • Use: use MyProject\MyClass;
  • Alias: use MyProject\MyClass as Alias;
  • Constants: namespace\CONSTANT
  • Functions: namespace\function_name()
javascript
// Scope in JavaScript
// Global scope
const globalVar = "global";

function testScope() {
  // Function scope
  var functionScoped = "function";

  // Block scope
  if (true) {
    let blockScoped = "block";
    const blockConst = "block const";
    var stillFunctionScoped = "still function";
  }
  // console.log(blockScoped); // ReferenceError
  console.log(stillFunctionScoped); // Works

  // Lexical scope
  function inner() {
    console.log(globalVar); // Access outer
    console.log(functionScoped); // Access outer
  }
  inner();
}

testScope();

// Module scope (ES modules)
// Each file has its own scope
// export const moduleVar = "module";

// Strict mode scope
"use strict";
// var x = 10; // Error if not declared
Beginner
12. What are classes and types in PHP?

PHP supports object-oriented programming with classes, inheritance, and type declarations.

  • Class definition: class MyClass { ... }
  • Properties: public $name;
  • Methods: public function method() { ... }
  • Constructor: public function __construct() { ... }
  • Inheritance: class Child extends Parent
javascript
// == vs === in JavaScript
// == (loose equality) - type coercion
console.log(5 == "5");  // true
console.log(true == 1); // true
console.log(null == undefined); // true
console.log(0 == false); // true
console.log("" == false); // true

// === (strict equality) - no type coercion
console.log(5 === "5");  // false
console.log(true === 1); // false
console.log(null === undefined); // false
console.log(0 === false); // false
console.log("" === false); // false

// Object comparison
console.log({} === {}); // false
console.log([] === []); // false

// NaN comparison
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(isNaN(NaN)); // true
console.log(Object.is(NaN, NaN)); // true

// Best practice: Always use === unless you need type coercion
Intermediate
13. What are type declarations in PHP?

PHP supports type declarations for function arguments and return values, including union types and nullable types.

  • Basic types: int, float, string, bool
  • Union types: int|float
  • Nullable types: ?string
  • Mixed type: mixed
  • Return type: : int
javascript
// Callbacks in JavaScript
// Basic callback
function greet(name, callback) {
  console.log(`Hello, ${name}`);
  callback();
}

greet("Alice", function() {
  console.log("Callback executed!");
});

// Callback with error handling
function fetchData(callback) {
  try {
    const data = { id: 1, name: "Alice" };
    callback(null, data);
  } catch (error) {
    callback(error, null);
  }
}

fetchData((error, data) => {
  if (error) {
    console.error("Error:", error);
  } else {
    console.log("Data:", data);
  }
});

// Callback hell
doSomething(function(result1) {
  doSomethingElse(result1, function(result2) {
    doAnotherThing(result2, function(result3) {
      console.log("Done!", result3);
    });
  });
});

// Solution: Promises or async/await
Intermediate
14. How to handle exceptions in PHP?

PHP provides try-catch-finally blocks for error handling, with support for custom exceptions.

  • Try-catch: try { ... } catch (Exception $e) { ... }
  • Finally: try { ... } finally { ... }
  • Throw: throw new Exception('message')
  • Custom exceptions: class MyException extends Exception
  • Multiple catch: catch (SpecificException $e) { ... }
javascript
// JSON in JavaScript
// JSON stringify and parse
const person = {
  name: "Alice",
  age: 25,
  hobbies: ["reading", "coding"],
  address: {
    city: "NYC",
    country: "USA"
  }
};

// Convert object to JSON string
const jsonString = JSON.stringify(person);
console.log(jsonString);
// {"name":"Alice","age":25,"hobbies":["reading","coding"],"address":{"city":"NYC","country":"USA"}}

// Convert JSON string to object
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);

// Pretty print
const pretty = JSON.stringify(person, null, 2);
console.log(pretty);

// Replacer function
const filtered = JSON.stringify(person, (key, value) => {
  return key === "age" ? undefined : value;
});
console.log(filtered);

// Reviver function
const revived = JSON.parse(jsonString, (key, value) => {
  return key === "age" ? value + 10 : value;
});
console.log(revived);
Intermediate
15. How to work with files in PHP?

PHP provides functions for file operations including reading, writing, and CSV handling.

  • Read: file_get_contents
  • Write: file_put_contents
  • Line by line: fgets, feof
  • CSV: fgetcsv, fputcsv
  • File info: is_file, is_dir
javascript
// Promises in JavaScript
// Creating a promise
const myPromise = new Promise((resolve, reject) => {
  // Async operation
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve("Operation successful!");
    } else {
      reject("Operation failed!");
    }
  }, 1000);
});

// Using a promise
myPromise
  .then(result => {
    console.log("Success:", result);
    return "Next step";
  })
  .then(nextResult => {
    console.log("Next:", nextResult);
  })
  .catch(error => {
    console.error("Error:", error);
  })
  .finally(() => {
    console.log("Promise completed");
  });

// Promise.all
const promises = [
  Promise.resolve("First"),
  Promise.resolve("Second"),
  Promise.resolve("Third")
];

Promise.all(promises)
  .then(results => {
    console.log("All results:", results);
  })
  .catch(error => {
    console.error("One failed:", error);
  });

// Promise.race
Promise.race([
  new Promise(resolve => setTimeout(() => resolve("Fast"), 100)),
  new Promise(resolve => setTimeout(() => resolve("Slow"), 1000))
]).then(result => {
  console.log("Race winner:", result);
});

// Promise.allSettled
Promise.allSettled([
  Promise.resolve("Success"),
  Promise.reject("Failure")
]).then(results => {
  console.log("All settled:", results);
});
Intermediate
16. How to use packages in PHP?

PHP uses Composer as a dependency manager. Packages are installed via Composer and autoloaded.

  • Composer: composer require vendor/package
  • Autoloading: require 'vendor/autoload.php'
  • Using packages: use Vendor\\Package\\Class
  • composer.json: Project dependencies
  • composer.lock: Locked versions
javascript
// Async/Await in JavaScript
// Basic async/await
async function fetchData() {
  try {
    const data = await new Promise((resolve) => {
      setTimeout(() => resolve({ id: 1, name: "Alice" }), 1000);
    });
    console.log("Data:", data);
    return data;
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}

// Using async function
fetchData();

// Async with multiple awaits
async function processData() {
  const data = await fetchData();
  const processed = await process(data);
  return processed;
}

// Parallel execution
async function parallelTasks() {
  const [user, posts] = await Promise.all([
    fetchUser(),
    fetchPosts()
  ]);
  return { user, posts };
}

// Error handling with async/await
async function safeFetch() {
  try {
    const response = await fetch("/api/data");
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error("Fetch failed:", error);
    return null;
  }
}
Intermediate
17. How to create plots in PHP?

PHP can create plots using GD library, ImageMagick, or JavaScript libraries like Chart.js.

  • GD: imagecreatetruecolor
  • Chart.js: JavaScript library
  • ImageMagick: Advanced image processing
  • Custom: Generate SVG
  • Web-based: Use Chart.js with PHP data
javascript
// Event Bubbling and Delegation
// HTML structure
/*
<div id="parent">
  <button id="child">Click me</button>
</div>
*/

// Event bubbling
document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent clicked (bubbling)");
}, false); // false = bubbling (default)

document.getElementById("child").addEventListener("click", () => {
  console.log("Child clicked");
}, false);

// Event capturing
document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent clicked (capturing)");
}, true); // true = capturing

// Stop propagation
document.getElementById("child").addEventListener("click", (e) => {
  e.stopPropagation();
  console.log("Child clicked - propagation stopped");
});

// Event delegation
document.getElementById("parent").addEventListener("click", (e) => {
  if (e.target.matches("button")) {
    console.log("Button clicked via delegation:", e.target.id);
  }
});

// Dynamic elements with delegation
document.addEventListener("click", (e) => {
  if (e.target.classList.contains("dynamic-btn")) {
    console.log("Dynamic button clicked");
  }
});
Intermediate
18. What are data structures in PHP?

PHP provides built-in data structures through arrays and Spl extensions for specialized structures.

  • Stack: SplStack
  • Queue: SplQueue
  • Map: Associative arrays
  • Set: array_unique
  • Linked list: SplDoublyLinkedList
javascript
// this keyword in JavaScript
// Global context
console.log(this); // Window (browser)

// Function context (non-strict)
function showThis() {
  console.log(this); // Window/global
}
showThis();

// Function context (strict)
"use strict";
function showThisStrict() {
  console.log(this); // undefined
}
showThisStrict();

// Object method
const obj = {
  name: "Alice",
  greet() {
    console.log(this.name);
  }
};
obj.greet(); // Alice

// Arrow function (lexical this)
const arrowObj = {
  name: "Bob",
  greet: () => {
    console.log(this.name); // undefined (lexical this)
  }
};
arrowObj.greet();

// Constructor function
function Person(name) {
  this.name = name;
}
const person1 = new Person("Alice");
console.log(person1.name); // Alice

// call, apply, bind
function introduce(greeting) {
  console.log(`${greeting}, I'm ${this.name}`);
}
const user = { name: "Alice" };
introduce.call(user, "Hello"); // Hello, I'm Alice
introduce.apply(user, ["Hi"]); // Hi, I'm Alice
const bound = introduce.bind(user, "Hey");
bound(); // Hey, I'm Alice
Intermediate
19. How to do statistics in PHP?

PHP provides statistical functions through built-in functions and custom implementations.

  • Mean: array_sum($data) / count($data)
  • Median: Sort and find middle
  • Standard deviation: Custom calculation
  • Correlation: Manual calculation
  • Quantiles: Custom implementation
javascript
// Arrow Functions in JavaScript
// Basic arrow function
const add = (a, b) => a + b;

// Arrow function with multiple statements
const multiply = (a, b) => {
  const result = a * b;
  return result;
};

// Arrow function with no parameters
const greet = () => "Hello!";

// Arrow function with one parameter (parens optional)
const double = x => x * 2;

// Arrow function returning object
const createPerson = (name, age) => ({ name, age });

// Arrow function in array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(x => x * 2);
const evens = numbers.filter(x => x % 2 === 0);
const sum = numbers.reduce((acc, x) => acc + x, 0);

// Arrow function with rest parameters
const sumAll = (...nums) => nums.reduce((acc, n) => acc + n, 0);

// Arrow function with destructuring
const printName = ({ name }) => console.log(name);

// Arrow function lexical this
function Timer() {
  this.seconds = 0;
  setInterval(() => {
    this.seconds++;
    console.log(this.seconds);
  }, 1000);
}
const timer = new Timer(); // Works correctly

// When NOT to use arrow functions
// 1. Object methods
const obj2 = {
  name: "Alice",
  greet: () => console.log(this.name) // Wrong!
};
// 2. Constructors
const Person2 = (name) => { this.name = name }; // Error
// 3. Event listeners (if you need 'this')
button.addEventListener("click", function() {
  console.log(this); // button element
});
Intermediate
20. How to do linear algebra in PHP?

PHP provides linear algebra operations through custom implementations or libraries.

  • Matrix multiplication: matMul
  • Transpose: transpose
  • Determinant: determinant
  • Eigenvalues: Complex calculation
  • Inverse: Using Gauss-Jordan
javascript
// Array Methods in JavaScript
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// map - transform each element
const doubled = arr.map(x => x * 2);
console.log(doubled);

// filter - select elements
const evens = arr.filter(x => x % 2 === 0);
console.log(evens);

// reduce - aggregate
const sum = arr.reduce((acc, x) => acc + x, 0);
console.log(sum);

// forEach - iterate
arr.forEach(x => console.log(x));

// find - find first match
const first = arr.find(x => x > 5);
console.log(first);

// findIndex - find index of first match
const index = arr.findIndex(x => x > 5);
console.log(index);

// some - check if any match
const hasEven = arr.some(x => x % 2 === 0);
console.log(hasEven);

// every - check if all match
const allEven = arr.every(x => x % 2 === 0);
console.log(allEven);

// includes - check if value exists
const includes = arr.includes(5);
console.log(includes);

// sort - sort array
const sorted = [...arr].sort((a, b) => a - b);
console.log(sorted);

// reverse - reverse array
const reversed = [...arr].reverse();
console.log(reversed);

// slice - create subarray
const sliced = arr.slice(2, 5);
console.log(sliced);

// splice - modify array
const spliced = [...arr];
spliced.splice(2, 3, 99, 100);
console.log(spliced);

// concat - merge arrays
const merged = arr.concat([11, 12, 13]);
console.log(merged);

// flat - flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
const flattened = nested.flat(2);
console.log(flattened);
Intermediate
21. How to work with dates in PHP?

PHP provides DateTime class and date functions for comprehensive date and time handling.

  • Current: new DateTime()
  • Create: new DateTime('2024-01-01')
  • Arithmetic: $date->modify('+1 day')
  • Difference: $date1->diff($date2)
  • Formatting: $date->format('Y-m-d')
javascript
// Object Methods in JavaScript
const person = {
  name: "Alice",
  age: 25,
  city: "NYC",
  hobbies: ["reading", "coding"]
};

// Object.keys - get keys
const keys = Object.keys(person);
console.log(keys);

// Object.values - get values
const values = Object.values(person);
console.log(values);

// Object.entries - get key-value pairs
const entries = Object.entries(person);
console.log(entries);

// Object.fromEntries - create from entries
const fromEntries = Object.fromEntries(entries);
console.log(fromEntries);

// Object.assign - merge objects
const additional = { country: "USA", age: 26 };
const merged = Object.assign({}, person, additional);
console.log(merged);

// Object.freeze - prevent modifications
const frozen = Object.freeze({ name: "Alice" });
// frozen.name = "Bob"; // Error in strict mode

// Object.seal - prevent adding/removing properties
const sealed = Object.seal({ name: "Alice" });
sealed.name = "Bob"; // Works
// sealed.age = 25; // Error

// Object.hasOwn - check own property
console.log(Object.hasOwn(person, "name")); // true
console.log(Object.hasOwn(person, "toString")); // false

// Object.getOwnPropertyNames
const ownProps = Object.getOwnPropertyNames(person);
console.log(ownProps);
Intermediate
22. How to use regular expressions in PHP?

PHP provides PCRE functions for regular expression matching, replacement, and splitting.

  • Match: preg_match('/hello/', $text)
  • Find all: preg_match_all('/hello/', $text)
  • Capture groups: preg_match('/(\d+)/', $text)
  • Replace: preg_replace('/\d+/', 'NUM', $text)
  • Split: preg_split('/[\s,]+/', $text)
javascript
// Destructuring in JavaScript
// Array destructuring
const arr = [1, 2, 3, 4, 5];
const [first, second, ...rest] = arr;
console.log(first, second, rest); // 1, 2, [3, 4, 5]

// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2, 1

// Object destructuring
const person = { name: "Alice", age: 25, city: "NYC" };
const { name, age } = person;
console.log(name, age);

// Rename variables
const { name: fullName, age: years } = person;
console.log(fullName, years);

// Default values
const { country = "USA" } = person;
console.log(country);

// Nested destructuring
const user = {
  id: 1,
  profile: {
    name: "Alice",
    address: {
      city: "NYC",
      zip: "10001"
    }
  }
};
const { profile: { address: { city } } } = user;
console.log(city);

// Function parameter destructuring
function printPerson({ name, age }) {
  console.log(`${name} is ${age} years old`);
}
printPerson(person);

// Array destructuring with rest
const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail);
Advanced
23. How to do parallel computing in PHP?

PHP supports parallel computing through PCNTL, pthreads, parallel extension, and async libraries.

  • PCNTL: Process forking
  • pthreads: Threading (deprecated)
  • parallel: New parallel extension
  • Amp: Async programming
  • ReactPHP: Event-driven
javascript
// Spread and Rest Operators
// Spread operator in arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined);

// Copy array
const copy = [...arr1];
console.log(copy);

// Spread in function calls
const numbers = [1, 2, 3, 4, 5];
const max = Math.max(...numbers);
console.log(max);

// Spread in objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4));

// Rest in destructuring
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head, tail);

// Rest in object destructuring
const { a, ...restObj } = { a: 1, b: 2, c: 3 };
console.log(a, restObj);

// Spread with strings
const chars = [..."hello"];
console.log(chars); // ['h', 'e', 'l', 'l', 'o']

// Spread with sets
const set = new Set([1, 2, 3]);
const arr = [...set];
console.log(arr);
Advanced
24. What is metaprogramming in PHP?

PHP supports metaprogramming through magic methods, eval, and reflection for dynamic code manipulation.

  • eval: eval('echo 1+2;')
  • Magic methods: __call, __set, __get
  • Reflection: ReflectionClass
  • Dynamic calls: Variable functions
  • Attributes: Metadata (PHP 8.0+)
javascript
// Template Literals in JavaScript
// Basic template literal
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);

// Multi-line strings
const multiLine = `
  This is a
  multi-line
  string
`;
console.log(multiLine);

// Expression interpolation
const a = 5, b = 10;
console.log(`${a} + ${b} = ${a + b}`);

// Nested templates
const isAdmin = true;
const message = `User is ${isAdmin ? `an admin` : `a regular user`}`;
console.log(message);

// Tagged templates
function highlight(strings, ...values) {
  return strings.reduce((acc, str, i) => {
    return acc + str + (values[i] ? `<b>${values[i]}</b>` : "");
  }, "");
}
const highlighted = highlight`Hello ${name}, you are ${age} years old`;
console.log(highlighted);

// Raw strings
const raw = String.raw`Hello\nWorld`;
console.log(raw); // Hello\nWorld (not escaped)

// Template literals in loops
const items = ["Apple", "Banana", "Orange"];
const list = items.map(item => `<li>${item}</li>`).join("");
console.log(list);
Advanced
25. How to interface with C in PHP?

PHP provides FFI (Foreign Function Interface) for calling C functions and extensions for deeper integration.

  • FFI: FFI::cdef
  • C extensions: Write PHP extensions in C
  • Calling C: ffi->printf
  • Structs: FFI::new
  • Memory: Manual management
javascript
// Map and Set in JavaScript
// Map - key-value pairs (any keys)
const map = new Map();

// Set values
map.set("name", "Alice");
map.set(42, "answer");
map.set({ id: 1 }, "object key");

// Get values
console.log(map.get("name")); // Alice
console.log(map.get(42)); // answer

// Check key existence
console.log(map.has("name")); // true

// Delete key
map.delete("name");

// Iterate map
map.forEach((value, key) => {
  console.log(key, value);
});

// Map from array
const mapFromArray = new Map([
  ["name", "Alice"],
  ["age", 25]
]);
console.log(mapFromArray);

// Set - unique values
const set = new Set();

// Add values
set.add(1);
set.add(2);
set.add(3);
set.add(3); // Duplicate ignored

console.log(set.has(2)); // true
console.log(set.size); // 3

// Delete value
set.delete(2);

// Iterate set
set.forEach(value => console.log(value));

// Set from array
const setFromArray = new Set([1, 2, 3, 3, 4]);
console.log(setFromArray); // Set(4) {1, 2, 3, 4}

// Remove duplicates from array
const arr = [1, 2, 3, 3, 4, 4, 5];
const unique = [...new Set(arr)];
console.log(unique);
Advanced
26. How to optimize performance in PHP?

PHP performance can be optimized through type declarations, opcode caching, and efficient code practices.

  • Type declarations: function add(int $a, int $b): int
  • OPcache: Enable opcode caching
  • Preallocate: array_fill
  • Static methods: Class::method()
  • Avoid globals: Use constants
javascript
// WeakMap and WeakSet
// WeakMap - keys must be objects, garbage collected
const weakMap = new WeakMap();
const obj = { id: 1 };
weakMap.set(obj, "value");
console.log(weakMap.get(obj));

// WeakMap does not prevent garbage collection
// If obj is deleted, the entry is automatically removed

// WeakSet - values must be objects
const weakSet = new WeakSet();
const obj2 = { id: 2 };
weakSet.add(obj2);
console.log(weakSet.has(obj2));

// Use cases: caching, private data
// Private data with WeakMap
const privateData = new WeakMap();

class Person {
  constructor(name) {
    privateData.set(this, { name });
  }
  
  getName() {
    return privateData.get(this).name;
  }
}

const p = new Person("Alice");
console.log(p.getName());

// WeakMap for DOM element metadata
const elementData = new WeakMap();
const button = document.createElement("button");
elementData.set(button, { clicks: 0 });
button.addEventListener("click", () => {
  const data = elementData.get(button);
  data.clicks++;
  console.log(`Clicked ${data.clicks} times`);
});
Advanced
27. How to do networking in PHP?

PHP provides networking capabilities through cURL, sockets, and HTTP client libraries.

  • cURL: curl_init, curl_exec
  • HTTP client: Guzzle
  • WebSockets: Ratchet
  • Socket server: socket_create
  • Built-in server: php -S localhost:8080
javascript
// Symbol in JavaScript
// Creating symbols
const sym1 = Symbol();
const sym2 = Symbol("description");
const sym3 = Symbol("description");

console.log(sym2 === sym3); // false

// Symbols as object keys
const uniqueKey = Symbol("key");
const obj = {
  [uniqueKey]: "secret value",
  regular: "normal"
};
console.log(obj[uniqueKey]); // secret value

// Symbol.for - global symbol registry
const globalSym1 = Symbol.for("shared");
const globalSym2 = Symbol.for("shared");
console.log(globalSym1 === globalSym2); // true

// Well-known symbols
// Symbol.iterator
const iterableObj = {
  [Symbol.iterator]: function* () {
    yield 1;
    yield 2;
    yield 3;
  }
};
for (const value of iterableObj) {
  console.log(value);
}

// Symbol.toStringTag
const customObj = {
  [Symbol.toStringTag]: "CustomObject"
};
console.log(Object.prototype.toString.call(customObj)); // [object CustomObject]

// Symbol.toPrimitive
const primitiveObj = {
  [Symbol.toPrimitive](hint) {
    if (hint === "number") return 42;
    if (hint === "string") return "forty-two";
    return null;
  }
};
console.log(+primitiveObj); // 42
console.log(`${primitiveObj}`); // forty-two
Advanced
28. How to work with JSON in PHP?

PHP provides built-in functions for JSON encoding and decoding with support for custom serialization.

  • Encode: json_encode($data)
  • Decode: json_decode($json, true)
  • Pretty print: JSON_PRETTY_PRINT
  • Error handling: json_last_error
  • Custom serialization: JsonSerializable
javascript
// Iterators and Generators
// Custom iterator
const range = {
  start: 0,
  end: 5,
  [Symbol.iterator]() {
    let current = this.start;
    const end = this.end;
    return {
      next() {
        if (current <= end) {
          return { value: current++, done: false };
        }
        return { value: undefined, done: true };
      }
    };
  }
};

for (const num of range) {
  console.log(num);
}

// Generator function
function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
}

const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

// Infinite generator
function* infiniteGenerator() {
  let i = 0;
  while (true) {
    yield i++;
  }
}

const infinite = infiniteGenerator();
console.log(infinite.next().value); // 0
console.log(infinite.next().value); // 1
console.log(infinite.next().value); // 2

// Generator with return
function* generatorWithReturn() {
  yield 1;
  yield 2;
  return 3;
  yield 4;
}

const gen2 = generatorWithReturn();
console.log(gen2.next()); // { value: 1, done: false }
console.log(gen2.next()); // { value: 2, done: false }
console.log(gen2.next()); // { value: 3, done: true }

// Generator delegation
function* generator1() {
  yield 1;
  yield 2;
}

function* generator2() {
  yield* generator1();
  yield 3;
  yield 4;
}

for (const value of generator2()) {
  console.log(value); // 1, 2, 3, 4
}
Advanced
29. How to test code in PHP?

PHP testing is done using PHPUnit for unit testing, with support for data providers and mocking.

  • PHPUnit: vendor/bin/phpunit
  • Assertions: $this->assertEquals
  • Data providers: @dataProvider
  • Mocking: createMock
  • Coverage: --coverage-html
javascript
// Classes in JavaScript
// Class definition
class Person {
  // Constructor
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  // Instance method
  greet() {
    return `Hello, I'm ${this.name}`;
  }
  
  // Getter
  get fullName() {
    return `${this.name} (Age: ${this.age})`;
  }
  
  // Setter
  set fullName(value) {
    this.name = value;
  }
  
  // Static method
  static createAnonymous() {
    return new Person("Anonymous", 0);
  }
  
  // Private field (ES2022)
  #privateField = "private";
  
  // Private method
  #privateMethod() {
    return "private method";
  }
}

// Inheritance
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }
  
  // Override method
  greet() {
    return `${super.greet()} and I'm in grade ${this.grade}`;
  }
}

const person = new Person("Alice", 25);
console.log(person.greet());
console.log(person.fullName);
const student = new Student("Bob", 20, "A");
console.log(student.greet());

// Static method
const anonymous = Person.createAnonymous();
console.log(anonymous.greet());

// Class expression
const Animal = class {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
};
Advanced
30. How to debug in PHP?

PHP provides debugging through var_dump, error_log, assertions, and Xdebug for step debugging.

  • var_dump: var_dump($variable)
  • print_r: print_r($array)
  • error_log: error_log('message')
  • Assertions: assert($condition)
  • Xdebug: Step debugging
javascript
// Modules in JavaScript (ES6)
// Exporting
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }

// Default export
export default class Calculator {
  multiply(a, b) { return a * b; }
}

// Named export with alias
export { add as sum };

// Importing
// main.js
import Calculator, { PI, add, subtract, sum } from './math.js';

// Import all
import * as MathUtils from './math.js';

// Import with alias
import { add as addition } from './math.js';

// Dynamic import
const module = await import('./math.js');

// Import for side effects
import './styles.css';

// Re-exporting
export { add, subtract } from './math.js';
export * from './math.js';

// Module scope
// Variables in modules are scoped to the module
// "use strict" is applied automatically

// Module loading
// <script type="module" src="main.js"></script>
// <script type="module">
//   import { add } from './math.js';
// </script>

// Top-level await
const data = await fetch('/api/data');
const json = await data.json();
console.log(json);
Advanced
31. What are abstract classes and interfaces in PHP?

Abstract classes and interfaces define contracts for classes to implement, with abstract methods and type definitions.

  • Abstract class: abstract class Animal { ... }
  • Interface: interface Animal { ... }
  • Implementation: class Dog extends Animal
  • Multiple interfaces: implements Interface1, Interface2
  • Type checking: instanceof
javascript
// Prototypes in JavaScript
// Prototype chain
const parent = { name: "Parent", greet() { return "Hello"; } };
const child = Object.create(parent);
child.name = "Child";
console.log(child.name); // Child
console.log(child.greet()); // Hello (inherited)

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

const person2 = new Person("Alice", 25);
console.log(person2.greet());

// Prototype inheritancefunction Student(name, age, grade) {
  Person.call(this, name, age);
  this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.study = function() {
  return `${this.name} is studying`;
};

const student2 = new Student("Bob", 20, "A");
console.log(student2.greet());
console.log(student2.study());

// hasOwnProperty
console.log(person2.hasOwnProperty("name")); // true
console.log(person2.hasOwnProperty("greet")); // false

// __proto__ (deprecated)
console.log(person2.__proto__ === Person.prototype); // true

// Object.getPrototypeOf
console.log(Object.getPrototypeOf(person2) === Person.prototype); // true

// instanceof
console.log(person2 instanceof Person); // true
console.log(person2 instanceof Object); // true
Advanced
32. What are generics and type hints in PHP?

PHP supports type hints and union types, but true generics are not available. Static analysis tools provide generic-like behavior.

  • Type hints: function add(int $a, int $b): int
  • Union types: int|float
  • Mixed type: mixed
  • Iterable: iterable
  • PHPStan/Psalm: Static analysis
javascript
// Prototypal Inheritance
// Object.create for inheritance
const animal = {
  speak() {
    return `${this.name} makes a sound`;
  },
  eat() {
    return `${this.name} is eating`;
  }
};

const dog = Object.create(animal);
dog.name = "Rex";
dog.speak = function() {
  return `${this.name} barks!`;
};

console.log(dog.speak()); // Rex barks!
console.log(dog.eat()); // Rex is eating

// Multiple inheritance with mixins
const flyable = {
  fly() {
    return `${this.name} is flying`;
  }
};
const swimmable = {
  swim() {
    return `${this.name} is swimming`;
  }
};

function mixin(target, ...sources) {
  Object.assign(target, ...sources);
}

const duck = { name: "Donald" };
mixin(duck, flyable, swimmable);
console.log(duck.fly()); // Donald is flying
console.log(duck.swim()); // Donald is swimming

// Class-based inheritance (ES6)
class Animal2 {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog2 extends Animal2 {
  speak() {
    return `${this.name} barks!`;
  }
}

const rex = new Dog2("Rex");
console.log(rex.speak()); // Rex barks!
Advanced
33. What are traits and composition in PHP?

Traits provide a mechanism for code reuse in single inheritance languages like PHP.

  • Definition: trait Logger { ... }
  • Use: use Logger;
  • Multiple traits: use Logger, Timestamp;
  • Conflict resolution: insteadof, as
  • Properties: Traits can have properties
javascript
// Currying in JavaScript
// Basic currying
function add(a) {
  return function(b) {
    return a + b;
  };
}
const add5 = add(5);
console.log(add5(3)); // 8
console.log(add(5)(3)); // 8

// Currying with arrow functions
const multiply = a => b => a * b;
const multiplyBy2 = multiply(2);
console.log(multiplyBy2(5)); // 10

// Currying with multiple arguments
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    }
    return function(...more) {
      return curried.apply(this, args.concat(more));
    };
  };
}

function sum(a, b, c) {
  return a + b + c;
}
const curriedSum = curry(sum);
console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(1, 2)(3)); // 6
console.log(curriedSum(1)(2, 3)); // 6

// Practical example: discount calculation
function calculateDiscount(discount) {
  return function(price) {
    return price * (1 - discount);
  };
}

const tenPercentOff = calculateDiscount(0.10);
const twentyPercentOff = calculateDiscount(0.20);
console.log(tenPercentOff(100)); // 90
console.log(twentyPercentOff(100)); // 80

// Partial application
function greet(greeting, name) {
  return `${greeting}, ${name}!`;
}
const sayHello = greet.bind(null, "Hello");
console.log(sayHello("Alice")); // Hello, Alice!
Advanced
34. What are generators and coroutines in PHP?

Generators in PHP provide a simple way to implement iterators, and coroutines enable cooperative multitasking.

  • Generator: function gen() { yield 1; yield 2; }
  • Yield from: yield from [3, 4, 5]
  • Send: $gen->send(10)
  • Return: return 'done'
  • Task scheduler: Coroutine support
javascript
// Debouncing in JavaScript
// Debounce function
function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// Usage: debounced search
const searchInput = document.getElementById("search");
const debouncedSearch = debounce((query) => {
  console.log("Searching for:", query);
  // API call here
}, 500);

searchInput.addEventListener("input", (e) => {
  debouncedSearch(e.target.value);
});

// Debounce with immediate execution
function debounceImmediate(func, delay, immediate = false) {
  let timeoutId;
  return function(...args) {
    const callNow = immediate && !timeoutId;
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      timeoutId = null;
      if (!immediate) {
        func.apply(this, args);
      }
    }, delay);
    if (callNow) {
      func.apply(this, args);
    }
  };
}

// Usage: debounced save
const saveButton = document.getElementById("save");
const debouncedSave = debounceImmediate(() => {
  console.log("Saving data...");
}, 1000, true);

saveButton.addEventListener("click", debouncedSave);

// Debounce with leading and trailing options
function debounceAdvanced(func, delay, options = { leading: false, trailing: true }) {
  let timeoutId;
  let lastCallTime;
  return function(...args) {
    const now = Date.now();
    const isFirstCall = !lastCallTime;
    lastCallTime = now;
    
    if (options.leading && isFirstCall) {
      func.apply(this, args);
      return;
    }
    
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      if (options.trailing) {
        func.apply(this, args);
      }
    }, delay);
  };
}
Advanced
35. What are advanced array operations in PHP?

PHP provides advanced array operations including matrix operations, element-wise operations, and various transformations.

  • Matrix ops: matMul
  • Element-wise: array_map
  • Transpose: transpose
  • Norm: Frobenius norm
  • Trace/Diagonal: trace, diag
javascript
// Throttling in JavaScript
// Throttle function
function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// Usage: throttled scroll
const throttledScroll = throttle(() => {
  console.log("Scroll position:", window.scrollY);
}, 200);

window.addEventListener("scroll", throttledScroll);

// Throttle with trailing execution
function throttleTrailing(func, limit) {
  let inThrottle;
  let lastFunc;
  let lastRan;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      lastRan = Date.now();
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
      }, limit);
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(() => {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(this, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

// Throttle with leading and trailing options
function throttleAdvanced(func, limit, options = { leading: true, trailing: true }) {
  let inThrottle;
  let lastRan;
  let lastFunc;
  
  return function(...args) {
    const now = Date.now();
    
    if (!inThrottle) {
      if (options.leading) {
        func.apply(this, args);
      }
      lastRan = now;
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
        if (options.trailing && lastFunc) {
          func.apply(this, args);
          lastFunc = null;
        }
      }, limit);
    } else {
      if (options.trailing) {
        clearTimeout(lastFunc);
        lastFunc = setTimeout(() => {
          func.apply(this, args);
        }, limit - (now - lastRan));
      }
    }
  };
}
Advanced
36. How to handle missing data in PHP?

PHP handles missing data using null values, with operators and functions for safe handling.

  • Null coalescing: $value ?? 'default'
  • Null coalescing assignment: $value ??= 'default'
  • Null check: is_null($value)
  • Filter: array_filter($data, fn($x) => $x !== null)
  • Optional: ?string $value
javascript
// Event Loop in JavaScript
// Basic event loop example
console.log("Start");

setTimeout(() => {
  console.log("Timeout callback");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise callback");
});

console.log("End");

// Output:
// Start
// End
// Promise callback
// Timeout callback

// Microtasks vs Macrotasks
console.log("1");

setTimeout(() => console.log("2"), 0);

Promise.resolve().then(() => {
  console.log("3");
});

console.log("4");

// Output: 1, 4, 3, 2
// Microtasks (Promises) execute before Macrotasks (setTimeout)

// Event loop with async/await
async function asyncFunction() {
  console.log("A");
  await Promise.resolve();
  console.log("B");
}

console.log("C");
asyncFunction();
console.log("D");

// Output: C, A, D, B

// Event loop visualization
setTimeout(() => console.log("Timeout 1"), 0);
setTimeout(() => console.log("Timeout 2"), 100);

Promise.resolve()
  .then(() => console.log("Promise 1"))
  .then(() => console.log("Promise 2"));

console.log("Sync code");

// Output: Sync code, Promise 1, Promise 2, Timeout 1, Timeout 2
Advanced
37. How to do sorting and searching in PHP?

PHP provides built-in sorting functions and custom search implementations.

  • Sort: sort($arr)
  • Custom sort: usort($arr, fn($a, $b) => $a <=> $b)
  • Associative sort: asort, ksort
  • Search: array_filter, in_array
  • Binary search: Custom implementation
javascript
// call(), apply(), bind() Methods
const person = {
  name: "Alice",
  greet(greeting) {
    return `${greeting}, I'm ${this.name}`;
  }
};

// call()
const bob = { name: "Bob" };
console.log(person.greet.call(bob, "Hello")); // Hello, I'm Bob

// apply()
console.log(person.greet.apply(bob, ["Hi"])); // Hi, I'm Bob

// bind()
const greetBob = person.greet.bind(bob);
console.log(greetBob("Hey")); // Hey, I'm Bob

// Partial application with bind
function multiply(a, b) {
  return a * b;
}
const double = multiply.bind(null, 2);
console.log(double(5)); // 10

// Borrowing methods
const arr = [1, 2, 3];
const arrLike = { 0: "a", 1: "b", 2: "c", length: 3 };
const result = Array.prototype.slice.call(arrLike);
console.log(result); // ['a', 'b', 'c']

// Using apply with Math.max
const numbers = [1, 5, 3, 9, 2];
const max = Math.max.apply(null, numbers);
console.log(max); // 9

// Using bind with event handlers
class Button {
  constructor(text) {
    this.text = text;
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    console.log(`${this.text} clicked`);
  }
}

const btn = new Button("Save");
// btn.handleClick(); // Save clicked
Advanced
38. What are mathematical operations in PHP?

PHP provides extensive mathematical functions for arithmetic, trigonometry, statistics, and linear algebra.

  • Arithmetic: +, -, *, /, %
  • Trigonometric: sin, cos, tan
  • Random: rand, mt_rand
  • Statistics: array_sum, custom stats
  • Linear algebra: Custom implementations
javascript
// Memory Leaks in JavaScript
// Common memory leak sources

// 1. Global variables
function leak() {
  globalVar = "I'm global"; // Implicit global
}
leak();

// 2. Forgotten timers
function timerLeak() {
  let element = document.getElementById("leak");
  setInterval(() => {
    console.log(element.id);
  }, 1000);
}

// 3. Event listeners not removed
function eventListenerLeak() {
  let element = document.getElementById("leak");
  element.addEventListener("click", function handler() {
    console.log("Clicked");
  });
  // element removed but listener remains
}

// 4. Closures holding references
function closureLeak() {
  let largeData = new Array(1000000);
  return function() {
    console.log(largeData.length);
  };
}
const leakyClosure = closureLeak();

// 5. DOM references
function domReferenceLeak() {
  let element = document.getElementById("leak");
  document.body.removeChild(element);
  // element still holds reference
}

// Prevention
// 1. Use 'use strict'
// 2. Clear timers
clearTimeout(timeoutId);
clearInterval(intervalId);

// 3. Remove event listeners
element.removeEventListener("click", handler);

// 4. Nullify references
element = null;

// 5. Use WeakMap and WeakSet
const cache = new WeakMap();
const obj = {};
cache.set(obj, "value");
// When obj is garbage collected, entry is removed
Advanced
39. How to do data serialization in PHP?

PHP provides various serialization methods including serialize, JSON, and XML for data exchange.

  • serialize: serialize($data)
  • JSON: json_encode, json_decode
  • var_export: var_export($data, true)
  • XML: SimpleXMLElement
  • CSV: fputcsv, fgetcsv
javascript
// ES6 Modules Advanced
// module.js
export const data = { id: 1, name: "Alice" };
export function process() { return "processing"; }

// Default export
export default class User {
  constructor(name) { this.name = name; }
}

// Import with alias
import User, { data as userData, process } from './module.js';

// Re-exporting
export { data, process } from './module.js';
export * from './module.js';

// Import namespace
import * as Module from './module.js';
console.log(Module.data);

// Dynamic import (lazy loading)
async function loadModule() {
  const module = await import('./module.js');
  console.log(module.default);
}

// Module import for side effects
import './styles.css';

// JSON imports (with import assertions)
import data from './data.json' assert { type: "json" };
console.log(data);

// Module variables
console.log(import.meta.url); // Current module URL
console.log(import.meta); // Module metadata

// Exporting types
export interface User {
  name: string;
  age: number;
}

// Export with dynamic binding
export let counter = 0;
export function increment() {
  counter++;
}
Advanced
40. How to interface with external systems in PHP?

PHP can interface with databases, Redis, Memcached, SOAP services, and execute shell commands.

  • Database: PDO, MySQLi
  • Redis: Redis extension
  • Memcached: Memcached extension
  • SOAP: SoapClient
  • Shell: exec, shell_exec
javascript
// IIFE (Immediately Invoked Function Expression)
// Basic IIFE
(function() {
  console.log("IIFE executed!");
})();

// IIFE with parameters
(function(name) {
  console.log(`Hello, ${name}!`);
})("Alice");

// Arrow function IIFE
(() => {
  console.log("Arrow IIFE");
})();

// IIFE with return value
const result = (function() {
  let count = 0;
  return {
    increment() { count++; },
    decrement() { count--; },
    getCount() { return count; }
  };
})();

// IIFE for private variables
const counterModule = (function() {
  let privateCounter = 0;
  
  function changeBy(val) {
    privateCounter += val;
  }
  
  return {
    increment() { changeBy(1); },
    decrement() { changeBy(-1); },
    value() { return privateCounter; }
  };
})();

// IIFE for module pattern
const myModule = (function() {
  // Private
  const privateData = [];
  
  // Public
  return {
    add(item) {
      privateData.push(item);
    },
    get() {
      return [...privateData];
    }
  };
})();

// IIFE in loops (pre-ES6)
for (var i = 0; i < 3; i++) {
  (function(index) {
    setTimeout(() => {
      console.log(index);
    }, 100);
  })(i);
}

// With let (no IIFE needed)
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
Coding Round
41. Reverse a string

Reverse a string using strrev, manual iteration, or recursion.

  • Built-in: strrev($s)
  • Manual: for ($i = strlen($s)-1; $i >= 0; $i--)
  • Recursive: reverseStringRecursive
  • Array: implode('', array_reverse(str_split($s)))
javascript
// Reverse a string
function reverseString(str) {
  return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // "olleh"

// Alternative with spread
const reverse = str => [...str].reverse().join('');
console.log(reverse("world")); // "dlrow"
Coding Round
42. Check palindrome

Check if a string is a palindrome by comparing characters from both ends.

  • Built-in: $s === strrev($s)
  • Manual: Two-pointer comparison
  • Recursive: isPalindromeRecursive
  • Case insensitive: strtolower
javascript
// Check palindrome
function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return cleaned === cleaned.split('').reverse().join('');
}
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false
Coding Round
43. Find max in array

Find the maximum value using max, iteration, or recursion.

  • Built-in: max($arr)
  • Manual: foreach iteration
  • Recursive: findMaxRecursive
  • Reduce: array_reduce
javascript
// Find max in array
function findMax(arr) {
  return Math.max(...arr);
}
console.log(findMax([1, 5, 3, 9, 2])); // 9

// Without spread
function findMaxManual(arr) {
  return arr.reduce((max, curr) => curr > max ? curr : max, -Infinity);
}
Coding Round
44. Remove duplicates

Remove duplicates using array_unique, manual loop, or array keys.

  • Built-in: array_unique($arr)
  • Manual: in_array check
  • Set: Using array keys
  • Preserve order: array_values
javascript
// Remove duplicates
function removeDuplicates(arr) {
  return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 3, 4])); // [1, 2, 3, 4]

// With filter
function removeDuplicatesFilter(arr) {
  return arr.filter((item, index) => arr.indexOf(item) === index);
}
Coding Round
45. Merge arrays

Merge arrays using array_merge, spread operator, or manual merge.

  • array_merge: array_merge($arr1, $arr2)
  • Spread: [...$arr1, ...$arr2]
  • Sorted merge: mergeSorted
  • Unique: array_unique(array_merge($arr1, $arr2))
javascript
// Merge arrays
function mergeArrays(arr1, arr2) {
  return [...arr1, ...arr2];
}
console.log(mergeArrays([1, 2], [3, 4])); // [1, 2, 3, 4]

// Alternative
function mergeArraysConcat(arr1, arr2) {
  return arr1.concat(arr2);
}
Coding Round
46. Convert string to number

Convert string to number using floatval, intval, or type casting.

  • Float: floatval($s)
  • Int: intval($s)
  • Casting: (float)$s, (int)$s
  • Safe: is_numeric check
javascript
// Convert string to number
function stringToNumber(str) {
  return Number(str);
}
console.log(stringToNumber("42")); // 42

// Alternative
function stringToNumberParse(str) {
  return parseInt(str, 10);
}
console.log(stringToNumberParse("42")); // 42
Coding Round
47. Loop through dictionary

Iterate through associative arrays using foreach or array_keys.

  • foreach: foreach ($dict as $key => $value)
  • Keys: array_keys with foreach
  • Values: array_values for values only
  • Find key: $dict[$key] ?? null
javascript
// Loop through object
function loopObject(obj) {
  // for...in
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      console.log(key, obj[key]);
    }
  }
  
  // Object.keys
  Object.keys(obj).forEach(key => {
    console.log(key, obj[key]);
  });
  
  // Object.entries
  Object.entries(obj).forEach(([key, value]) => {
    console.log(key, value);
  });
}

const person = { name: "Alice", age: 25 };
loopObject(person);
Coding Round
48. Delay function execution

Delay execution using sleep or usleep for blocking delays.

  • Seconds: sleep($seconds)
  • Microseconds: usleep($microseconds)
  • Async: Using pcntl_fork
  • Callback: delayWithCallback
javascript
// Delay function execution
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function delayedExecution() {
  console.log("Start");
  await delay(2000);
  console.log("After 2 seconds");
}

delayedExecution();

// SetTimeout
function delayCallback(callback, ms) {
  setTimeout(callback, ms);
}

delayCallback(() => console.log("Delayed"), 1000);
Coding Round
49. HTTP GET request

Make HTTP requests using cURL, file_get_contents, or Guzzle.

  • cURL: curl_init, curl_exec
  • file_get_contents: With stream context
  • Guzzle: $client->get()
  • Error handling: Try-catch
javascript
// Fetch API example
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}

// POST request
async function postData(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    });
    return await response.json();
  } catch (error) {
    console.error('POST error:', error);
    throw error;
  }
}

// With AbortController
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

fetch('https://api.example.com/data', {
  signal: controller.signal
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
  if (error.name === 'AbortError') {
    console.log('Request aborted');
  }
})
.finally(() => clearTimeout(timeoutId));
Coding Round
50. Create a promise-like task

Create promise-like behavior using a custom Promise class with then, catch, and all methods.

  • Promise class: Custom implementation
  • then: Chain callbacks
  • catch: Error handling
  • all: Multiple promises
javascript
// Create a promise
function createPromise(shouldResolve) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldResolve) {
        resolve("Success!");
      } else {
        reject("Failed!");
      }
    }, 1000);
  });
}

// Using the promise
createPromise(true)
  .then(result => console.log("Resolved:", result))
  .catch(error => console.error("Rejected:", error));

// Promise with parameters
function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) {
        resolve({ id, name: `User${id}` });
      } else {
        reject("Invalid ID");
      }
    }, 1000);
  });
}

fetchUser(1)
  .then(user => console.log(user))
  .catch(error => console.error(error));
Coding Round
51. Factorial

Calculate factorial using recursion, iteration, or tail recursion.

  • Recursive: function fact($n) { return $n <= 1 ? 1 : $n * fact($n-1); }
  • Iterative: for ($i = 2; $i <= $n; $i++)
  • Tail recursive: factTail($n, 1)
  • Edge cases: 0! = 1
javascript
// Factorial
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5)); // 120

// Iterative
function factorialIterative(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}
Coding Round
52. Fibonacci

Calculate Fibonacci numbers using recursion, iteration, or memoization.

  • Recursive: function fib($n) { return $n <= 1 ? $n : fib($n-1) + fib($n-2); }
  • Iterative: for ($i = 2; $i <= $n; $i++)
  • Memoized: Static cache
  • Generator: Yield sequence
javascript
// Fibonacci
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(8)); // 21

// Iterative
function fibonacciIterative(n) {
  let a = 0, b = 1;
  for (let i = 2; i <= n; i++) {
    [a, b] = [b, a + b];
  }
  return n ? b : a;
}
Coding Round
53. FizzBuzz

Print numbers with FizzBuzz logic using conditional statements or match expression.

  • If-else: if ($i % 15 == 0)
  • Match: PHP 8.0+ match expression
  • Array: fizzbuzzArray
  • Edge cases: n >= 1
javascript
// FizzBuzz
function fizzBuzz(n) {
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) console.log("FizzBuzz");
    else if (i % 3 === 0) console.log("Fizz");
    else if (i % 5 === 0) console.log("Buzz");
    else console.log(i);
  }
}
fizzBuzz(15);
Coding Round
54. Find missing number

Find missing number using sum formula or XOR operation.

  • Sum: ($n * ($n + 1) / 2) - array_sum($arr)
  • XOR: $xor_all ^ $xor_arr
  • Edge cases: Empty array
  • Time: O(n)
javascript
// Find missing number
function findMissing(arr) {
  const n = arr.length + 1;
  const total = n * (n + 1) / 2;
  const sum = arr.reduce((acc, x) => acc + x, 0);
  return total - sum;
}
console.log(findMissing([1, 2, 4, 5, 6])); // 3
Coding Round
55. Find duplicates

Find duplicates using array_count_values, array_filter, or manual tracking.

  • Count: array_count_values
  • Manual: in_array check
  • Set: Array keys
  • Time: O(n)
javascript
// Find duplicates
function findDuplicates(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 [...duplicates];
}
console.log(findDuplicates([1, 2, 3, 2, 4, 3])); // [2, 3]
Coding Round
56. Sum of array

Sum array elements using array_sum, manual loop, or reduce.

  • Built-in: array_sum($arr)
  • Manual: foreach ($arr as $v) $sum += $v
  • Reduce: array_reduce($arr, fn($c, $v) => $c + $v, 0)
  • Empty array: Returns 0
javascript
// Sum of array
function sumArray(arr) {
  return arr.reduce((acc, x) => acc + x, 0);
}
console.log(sumArray([1, 2, 3, 4, 5])); // 15
Coding Round
57. Average of array

Calculate average by dividing sum by count. Handle empty arrays.

  • Method: array_sum($arr) / count($arr)
  • Float: array_sum($arr) / count($arr)
  • Integer: intdiv(array_sum($arr), count($arr))
  • Empty: Return 0
javascript
// Average of array
function averageArray(arr) {
  return arr.reduce((acc, x) => acc + x, 0) / arr.length;
}
console.log(averageArray([1, 2, 3, 4, 5])); // 3
Coding Round
58. Sort array ascending

Sort arrays using sort or custom usort.

  • Non-mutating: Copy then sort
  • Mutating: sort($arr)
  • Custom: usort($arr, fn($a, $b) => $a <=> $b)
  • Associative: asort for values
javascript
// Sort array ascending
function sortAscending(arr) {
  return [...arr].sort((a, b) => a - b);
}
console.log(sortAscending([5, 2, 8, 1, 9])); // [1, 2, 5, 8, 9]
Coding Round
59. Sort array descending

Sort descending using rsort or custom comparator.

  • Non-mutating: Copy then rsort
  • Mutating: rsort($arr)
  • Custom: usort($arr, fn($a, $b) => $b <=> $a)
  • Associative: arsort
javascript
// Sort array descending
function sortDescending(arr) {
  return [...arr].sort((a, b) => b - a);
}
console.log(sortDescending([5, 2, 8, 1, 9])); // [9, 8, 5, 2, 1]
Coding Round
60. Flatten nested array

Flatten nested arrays using recursion or iterative stack approach.

  • Recursive: function flatten($arr) { ... }
  • Iterative: Stack-based
  • One level: array_merge(...$arr)
  • Depth: Handle arbitrary depth
javascript
// Flatten nested array
function flattenArray(arr) {
  return arr.reduce((acc, val) => 
    Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), 
    []
  );
}
console.log(flattenArray([1, [2, [3, 4], 5], 6])); // [1, 2, 3, 4, 5, 6]

// ES2019 flat
const flat = arr.flat(Infinity);
Coding Round
61. Chunk array

Split array into chunks using array_chunk or manual slicing.

  • Built-in: array_chunk($arr, $size)
  • Manual: array_slice in loop
  • Predicate: chunkByPredicate
  • Use case: Batch processing
javascript
// Chunk array
function chunkArray(arr, size) {
  const result = [];
  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size));
  }
  return result;
}
console.log(chunkArray([1, 2, 3, 4, 5, 6], 2)); // [[1,2], [3,4], [5,6]]
Coding Round
63. Quick sort

Implement quick sort with partitioning and recursion.

  • Recursive: quickSort
  • In-place: quickSortInPlace
  • Pivot: Last element
  • Time: O(n log n) average
javascript
// Quick sort
function quickSort(arr) {
  if (arr.length <= 1) return arr;
  const pivot = arr[0];
  const left = arr.slice(1).filter(x => x < pivot);
  const right = arr.slice(1).filter(x => x >= pivot);
  return [...quickSort(left), pivot, ...quickSort(right)];
}
console.log(quickSort([5, 3, 8, 4, 2, 7, 1, 6]));
Coding Round
64. Merge sort

Implement merge sort with divide and conquer approach.

  • Divide: array_slice
  • Merge: merge function
  • In-place: mergeSortInPlace
  • Time: O(n log n)
javascript
// Merge sort
function mergeSort(arr) {
  if (arr.length <= 1) return arr;
  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));
  return merge(left, right);
}

function merge(left, right) {
  const result = [];
  let i = 0, j = 0;
  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) result.push(left[i++]);
    else result.push(right[j++]);
  }
  return [...result, ...left.slice(i), ...right.slice(j)];
}
Coding Round
65. Bubble sort

Implement bubble sort with optimization to stop early if no swaps occur.

  • Basic: for ($i = 0; $i < $n-1; $i++)
  • Optimized: $swapped flag
  • Time: O(n²) worst case
  • Use case: Small datasets
javascript
// Bubble sort
function bubbleSort(arr) {
  const sorted = [...arr];
  for (let i = 0; i < sorted.length - 1; i++) {
    for (let j = 0; j < sorted.length - 1 - i; j++) {
      if (sorted[j] > sorted[j + 1]) {
        [sorted[j], sorted[j + 1]] = [sorted[j + 1], sorted[j]];
      }
    }
  }
  return sorted;
}
Coding Round
66. Intersection of arrays

Find intersection using array_intersect or manual filtering.

  • Built-in: array_intersect($arr1, $arr2)
  • Manual: in_array check
  • Set: array_flip for lookup
  • Multiple: array_intersect with multiple
javascript
// Intersection of arrays
function intersection(arr1, arr2) {
  return arr1.filter(x => arr2.includes(x));
}
console.log(intersection([1, 2, 3, 4], [3, 4, 5, 6])); // [3, 4]
Coding Round
67. Union of arrays

Union arrays using array_merge with array_unique.

  • Built-in: array_unique(array_merge($arr1, $arr2))
  • Manual: in_array check
  • Set: array_flip
  • Preserve keys: array_merge with keys
javascript
// Union of arrays
function union(arr1, arr2) {
  return [...new Set([...arr1, ...arr2])];
}
console.log(union([1, 2, 3], [3, 4, 5])); // [1, 2, 3, 4, 5]
Coding Round
68. Difference of arrays

Find difference using array_diff or manual filtering.

  • Built-in: array_diff($arr1, $arr2)
  • Symmetric: array_diff both ways
  • Manual: in_array check
  • Multiple: array_diff with multiple
javascript
// Difference of arrays
function difference(arr1, arr2) {
  return arr1.filter(x => !arr2.includes(x));
}
console.log(difference([1, 2, 3, 4], [3, 4, 5, 6])); // [1, 2]
Coding Round
69. Group by property

Group array elements by a property using loops and arrays.

  • Method: groupBy($arr, $key)
  • Callback: groupByCallback($arr, $callback)
  • Aggregation: groupAndSum
  • Use case: Data aggregation
javascript
// Group by property
function groupBy(arr, key) {
  return arr.reduce((acc, item) => {
    const group = item[key];
    if (!acc[group]) acc[group] = [];
    acc[group].push(item);
    return acc;
  }, {});
}
const data = [{type: 'fruit', name: 'apple'}, {type: 'fruit', name: 'banana'}, {type: 'veg', name: 'carrot'}];
console.log(groupBy(data, 'type'));
Coding Round
70. Deep clone object

Create deep copies of objects using recursion to clone nested structures.

  • Method: deepClone
  • Objects: clone $obj
  • Arrays: Recursive copy
  • Custom: deepCloneObject
javascript
// Deep clone object
function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}
const original = { a: 1, b: { c: 2 } };
const cloned = deepClone(original);
cloned.b.c = 3;
console.log(original.b.c); // 2

// With circular reference handling
function deepCloneAdvanced(obj, seen = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (seen.has(obj)) return seen.get(obj);
  const clone = Array.isArray(obj) ? [] : {};
  seen.set(obj, clone);
  for (const key in obj) {
    clone[key] = deepCloneAdvanced(obj[key], seen);
  }
  return clone;
}
Coding Round
71. Immutable update

Perform immutable updates on nested data structures using path-based updates.

  • Method: updateImmutable($array, $path, $value)
  • Path: Dot notation
  • Recursive: Helper function
  • Use case: State management
javascript
// Immutable update
function updateImmutable(obj, path, value) {
  const keys = path.split('.');
  if (keys.length === 1) {
    return { ...obj, [keys[0]]: value };
  }
  const [first, ...rest] = keys;
  return {
    ...obj,
    [first]: updateImmutable(obj[first] || {}, rest.join('.'), value)
  };
}
const state = { user: { name: 'Alice', age: 25 } };
const newState = updateImmutable(state, 'user.age', 26);
console.log(state.user.age); // 25
console.log(newState.user.age); // 26
Coding Round
72. Pipe function

Implement pipe function for left-to-right function composition.

  • Method: pipe(...$fns)
  • Implementation: array_reduce
  • Direction: Left to right
  • Use case: Function chaining
javascript
// Pipe function
function pipe(...fns) {
  return (value) => fns.reduce((acc, fn) => fn(acc), value);
}

const double = x => x * 2;
const addTen = x => x + 10;
const square = x => x * x;

const process = pipe(double, addTen, square);
console.log(process(5)); // (5*2+10)^2 = 400
Coding Round
73. Compose function

Implement compose function for right-to-left function composition.

  • Method: compose(...$fns)
  • Implementation: array_reduce with reversed order
  • Direction: Right to left
  • Use case: Function composition
javascript
// Compose function
function compose(...fns) {
  return (value) => fns.reduceRight((acc, fn) => fn(acc), value);
}

const process2 = compose(square, addTen, double);
console.log(process2(5)); // (5*2+10)^2 = 400
Coding Round
74. Memoization

Implement memoization to cache function results based on arguments.

  • Method: memoize($fn)
  • Cache: array
  • Limit: memoizeWithLimit
  • Multiple args: memoizeMultiple
javascript
// Memoization
function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

const factorialMemo = memoize(function(n) {
  if (n <= 1) return 1;
  return n * factorialMemo(n - 1);
});
console.log(factorialMemo(5)); // 120
Coding Round
75. Once function

Implement once function that ensures a function is called only once.

  • Method: once($fn)
  • Flag: $called
  • Reset: onceWithReset
  • Result: Cached result
javascript
// Once function
function once(fn) {
  let called = false;
  let result;
  return function(...args) {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

const initialize = once(() => {
  console.log("Initialized");
  return { id: 1, name: "App" };
});

initialize(); // Prints "Initialized"
initialize(); // Returns cached result
Coding Round
76. Debounce with leading edge

Implement debounce with leading edge execution using timers.

  • Method: debounceLeading
  • State: $lastCall
  • Timer: usleep or sleep
  • Use case: Rate limiting
javascript
// Debounce with leading edge
function debounceLeading(func, delay) {
  let timeoutId;
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall < delay) {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        lastCall = Date.now();
        func.apply(this, args);
      }, delay);
    } else {
      lastCall = now;
      func.apply(this, args);
    }
  };
}
Coding Round
77. Throttle with leading edge

Implement throttle with leading edge execution based on time since last call.

  • Method: throttleLeading
  • State: $lastCall
  • Skipped: Track skipped calls
  • Trailing: throttleWithTrailing
javascript
// Throttle with leading edge
function throttleLeading(func, delay) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func.apply(this, args);
    }
  };
}
Coding Round
78. Deep equal

Implement deep equality comparison for nested structures.

  • Method: deepEqual($obj1, $obj2)
  • Primitive: ===
  • Arrays: Recursive compare
  • Objects: Compare properties
javascript
// Deep equal
function deepEqual(obj1, obj2) {
  if (obj1 === obj2) return true;
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || 
      obj1 === null || obj2 === null) return false;
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) return false;
  for (const key of keys1) {
    if (!keys2.includes(key)) return false;
    if (!deepEqual(obj1[key], obj2[key])) return false;
  }
  return true;
}
Coding Round
79. Observable pattern

Implement observable pattern with subscription and notification.

  • Observable: Observable class
  • Subscribe: subscribe($callback)
  • Notify: notify($data)
  • Stateful: StatefulObservable
javascript
// Observable pattern
class Observable {
  constructor() {
    this.subscribers = [];
  }
  
  subscribe(callback) {
    this.subscribers.push(callback);
    return () => {
      this.subscribers = this.subscribers.filter(cb => cb !== callback);
    };
  }
  
  notify(data) {
    this.subscribers.forEach(cb => cb(data));
  }
}

const observable = new Observable();
const unsubscribe = observable.subscribe(data => console.log('Received:', data));
observable.notify('Hello'); // Received: Hello
unsubscribe();
observable.notify('World'); // Nothing happens
Coding Round
80. Singleton pattern

Implement singleton pattern to ensure only one instance exists.

  • Class: Singleton class
  • Instance: static $instance
  • Private: Constructor, clone, wakeup
  • Closure: createSingleton
javascript
// Singleton pattern
class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = this;
    this.data = {};
    return this;
  }
  
  set(key, value) {
    this.data[key] = value;
  }
  
  get(key) {
    return this.data[key];
  }
}

const s1 = new Singleton();
const s2 = new Singleton();
s1.set('name', 'Alice');
console.log(s2.get('name')); // Alice
console.log(s1 === s2); // true
Coding Round
81. Factory pattern

Implement factory pattern for creating objects without specifying concrete classes.

  • Interface: User
  • Factory: UserFactory
  • Create: create($type, $name)
  • Specific: createAdmin, createGuest
javascript
// Factory pattern
class UserFactory {
  createUser(type, name) {
    switch(type) {
      case 'admin':
        return new Admin(name);
      case 'guest':
        return new Guest(name);
      default:
        return new User(name);
    }
  }
}

class User {
  constructor(name) { this.name = name; this.type = 'user'; }
}
class Admin extends User {
  constructor(name) { super(name); this.type = 'admin'; }
}
class Guest extends User {
  constructor(name) { super(name); this.type = 'guest'; }
}

const factory = new UserFactory();
const admin = factory.createUser('admin', 'Alice');
console.log(admin.type); // admin
Coding Round
82. Strategy pattern

Implement strategy pattern with interchangeable payment methods.

  • Strategy: PaymentStrategy
  • Context: PaymentContext
  • Execute: executePayment
  • Decorator: DiscountDecorator
javascript
// Strategy pattern
class PaymentStrategy {
  pay(amount) { throw new Error('Must implement pay'); }
}

class CreditCardStrategy extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} with Credit Card`);
  }
}

class PayPalStrategy extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} with PayPal`);
  }
}

class CryptoStrategy extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} with Crypto`);
  }
}

class PaymentContext {
  constructor(strategy) {
    this.strategy = strategy;
  }
  
  setStrategy(strategy) {
    this.strategy = strategy;
  }
  
  executePayment(amount) {
    this.strategy.pay(amount);
  }
}

const context = new PaymentContext(new CreditCardStrategy());
context.executePayment(100);
context.setStrategy(new PayPalStrategy());
context.executePayment(50);
Coding Round
83. Observer pattern

Implement observer pattern with subject and observer interfaces.

  • Subject: ConcreteSubject
  • Observer: ConcreteObserver
  • Attach: attach($observer)
  • Notify: setState($state)
javascript
// Observer pattern
class Subject {
  constructor() {
    this.observers = [];
  }
  
  attach(observer) {
    this.observers.push(observer);
  }
  
  detach(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }
  
  notify(data) {
    this.observers.forEach(observer => observer.update(data));
  }
}

class ConcreteObserver {
  constructor(name) {
    this.name = name;
  }
  
  update(data) {
    console.log(`${this.name} received: ${data}`);
  }
}

const subject = new Subject();
const observer1 = new ConcreteObserver('Observer1');
const observer2 = new ConcreteObserver('Observer2');
subject.attach(observer1);
subject.attach(observer2);
subject.notify('Hello World');
Coding Round
84. Decorator pattern

Implement decorator pattern for adding features to coffee.

  • Component: BasicCoffee
  • Decorator: CoffeeDecorator
  • Additions: MilkDecorator, SugarDecorator
  • Chaining: Nested decorators
javascript
// Decorator pattern
class Coffee {
  cost() { return 5; }
  description() { return 'Coffee'; }
}

class MilkDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }
  cost() { return this.coffee.cost() + 2; }
  description() { return this.coffee.description() + ', Milk'; }
}

class SugarDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }
  cost() { return this.coffee.cost() + 1; }
  description() { return this.coffee.description() + ', Sugar'; }
}

let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.description()); // Coffee, Milk, Sugar
console.log(coffee.cost()); // 8
Coding Round
85. Command pattern

Implement command pattern with execute, undo, and redo operations.

  • Command: AddCommand, SubtractCommand
  • History: CommandHistory
  • Macro: MacroCommand
  • Operations: execute, undo, redo
javascript
// Command pattern
class Command {
  execute() {}
  undo() {}
}

class AddCommand extends Command {
  constructor(receiver, value) {
    super();
    this.receiver = receiver;
    this.value = value;
  }
  execute() {
    this.receiver.add(this.value);
  }
  undo() {
    this.receiver.subtract(this.value);
  }
}

class Calculator {
  constructor() {
    this.value = 0;
  }
  add(n) { this.value += n; }
  subtract(n) { this.value -= n; }
  getValue() { return this.value; }
}

const calc = new Calculator();
const addCommand = new AddCommand(calc, 5);
addCommand.execute();
console.log(calc.getValue()); // 5
addCommand.undo();
console.log(calc.getValue()); // 0
Coding Round
86. Memento pattern

Implement memento pattern for state capture and restoration.

  • Originator: Originator
  • Memento: Memento
  • Caretaker: Caretaker
  • Undo/Redo: undo, redo
javascript
// Memento pattern
class Memento {
  constructor(state) {
    this.state = state;
  }
  getState() { return this.state; }
}

class Originator {
  constructor() {
    this.state = '';
  }
  setState(state) {
    this.state = state;
  }
  getState() {
    return this.state;
  }
  saveState() {
    return new Memento(this.state);
  }
  restoreState(memento) {
    this.state = memento.getState();
  }
}

class Caretaker {
  constructor() {
    this.mementos = [];
  }
  addMemento(memento) {
    this.mementos.push(memento);
  }
  getMemento(index) {
    return this.mementos[index];
  }
}
Coding Round
87. Mediator pattern

Implement mediator pattern for centralized communication between colleagues.

  • Mediator: ConcreteMediator
  • Colleague: User
  • Send: send($message)
  • Register: register($colleague)
javascript
// Mediator pattern
class Mediator {
  constructor() {
    this.colleagues = [];
  }
  register(colleague) {
    this.colleagues.push(colleague);
  }
  send(message, sender) {
    this.colleagues.forEach(colleague => {
      if (colleague !== sender) {
        colleague.receive(message);
      }
    });
  }
}

class Colleague {
  constructor(mediator, name) {
    this.mediator = mediator;
    this.name = name;
    this.mediator.register(this);
  }
  send(message) {
    this.mediator.send(message, this);
  }
  receive(message) {
    console.log(`${this.name} received: ${message}`);
  }
}

const mediator = new Mediator();
const alice = new Colleague(mediator, 'Alice');
const bob = new Colleague(mediator, 'Bob');
alice.send('Hello Bob!');
Coding Round
88. Chain of Responsibility

Implement chain of responsibility with linked handlers.

  • Handler: Handler abstract class
  • Chain: setNext($handler)
  • Processing: handle($request)
  • Concrete: AuthHandler, LoggerHandler
javascript
// Chain of Responsibility
class Handler {
  constructor() {
    this.next = null;
  }
  setNext(handler) {
    this.next = handler;
    return handler;
  }
  handle(request) {
    if (this.next) {
      this.next.handle(request);
    }
  }
}

class AuthHandler extends Handler {
  handle(request) {
    if (request.token) {
      console.log('Authentication passed');
      super.handle(request);
    } else {
      console.log('Authentication failed');
    }
  }
}

class LoggerHandler extends Handler {
  handle(request) {
    console.log(`Logging request: ${request.url}`);
    super.handle(request);
  }
}

const auth = new AuthHandler();
const logger = new LoggerHandler();
auth.setNext(logger);
auth.handle({ token: 'valid', url: '/api' });
Coding Round
89. State pattern

Implement state pattern with context and state transitions.

  • State: State interface
  • Context: Context
  • Transitions: handle($context)
  • Data: StatefulContext
javascript
// State pattern
class State {
  handle() {}
}

class ReadyState extends State {
  handle() {
    console.log('Ready: Waiting for input');
  }
}

class ProcessingState extends State {
  handle() {
    console.log('Processing: Working on task');
  }
}

class CompletedState extends State {
  handle() {
    console.log('Completed: Task finished');
  }
}

class Context {
  constructor() {
    this.state = new ReadyState();
  }
  setState(state) {
    this.state = state;
  }
  request() {
    this.state.handle();
  }
}

const context2 = new Context();
context2.request(); // Ready: Waiting for input
context2.setState(new ProcessingState());
context2.request(); // Processing: Working on task
context2.setState(new CompletedState());
context2.request(); // Completed: Task finished
Coding Round
90. Proxy pattern

Implement proxy pattern for access control and lazy initialization.

  • Subject: RealSubject
  • Proxy: Proxy
  • Logging: LoggingProxy
  • Auth: AuthProxy
javascript
// Proxy pattern
class RealSubject {
  request() {
    console.log('RealSubject: Handling request');
  }
}

class Proxy {
  constructor(realSubject) {
    this.realSubject = realSubject;
  }
  request() {
    if (this.checkAccess()) {
      this.realSubject.request();
      this.logAccess();
    }
  }
  checkAccess() {
    console.log('Proxy: Checking access');
    return true;
  }
  logAccess() {
    console.log('Proxy: Logging access');
  }
}

const real = new RealSubject();
const proxy = new Proxy(real);
proxy.request();
Coding Round
91. Flyweight pattern

Implement flyweight pattern for sharing objects to save memory.

  • Flyweight: Flyweight
  • Factory: FlyweightFactory
  • Get: getFlyweight($sharedState)
  • Operation: operation($uniqueState)
javascript
// Flyweight pattern
class Flyweight {
  constructor(sharedState) {
    this.sharedState = sharedState;
  }
  operation(uniqueState) {
    console.log(`Shared: ${this.sharedState}, Unique: ${uniqueState}`);
  }
}

class FlyweightFactory {
  constructor() {
    this.flyweights = {};
  }
  getFlyweight(sharedState) {
    if (!this.flyweights[sharedState]) {
      this.flyweights[sharedState] = new Flyweight(sharedState);
    }
    return this.flyweights[sharedState];
  }
}
Coding Round
92. Bridge pattern

Implement bridge pattern for separating abstraction from implementation.

  • Implementation: ConcreteImplementationA
  • Abstraction: ExtendedAbstraction
  • Alternative: AlternativeAbstraction
  • Operation: operation()
javascript
// Bridge pattern
class Abstraction {
  constructor(implementation) {
    this.implementation = implementation;
  }
  operation() {
    this.implementation.operation();
  }
}

class RefinedAbstraction extends Abstraction {
  operation() {
    console.log('RefinedAbstraction: Additional logic');
    this.implementation.operation();
  }
}

class ConcreteImplementationA {
  operation() {
    console.log('ConcreteImplementationA: Operation');
  }
}

class ConcreteImplementationB {
  operation() {
    console.log('ConcreteImplementationB: Operation');
  }
}
Coding Round
93. Adapter pattern

Implement adapter pattern for converting interfaces.

  • Target: Target
  • Adaptee: Adaptee
  • Adapter: Adapter
  • Logging: LoggingAdapter
javascript
// Adapter pattern
class Target {
  request() {
    console.log('Target: Request');
  }
}

class Adaptee {
  specificRequest() {
    console.log('Adaptee: Specific Request');
  }
}

class Adapter extends Target {
  constructor(adaptee) {
    super();
    this.adaptee = adaptee;
  }
  request() {
    this.adaptee.specificRequest();
  }
}

const adaptee = new Adaptee();
const adapter = new Adapter(adaptee);
adapter.request();
Coding Round
94. Facade pattern

Implement facade pattern for simplifying complex subsystems.

  • Subsystems: SubsystemA, SubsystemB
  • Facade: Facade
  • Operations: simpleOperation, complexOperation
  • Interface: Simplified API
javascript
// Facade pattern
class SubsystemA {
  operationA() { console.log('SubsystemA: Operation'); }
}

class SubsystemB {
  operationB() { console.log('SubsystemB: Operation'); }
}

class Facade {
  constructor() {
    this.subsystemA = new SubsystemA();
    this.subsystemB = new SubsystemB();
  }
  operation() {
    this.subsystemA.operationA();
    this.subsystemB.operationB();
    console.log('Facade: Complex operation');
  }
}

const facade = new Facade();
facade.operation();
Coding Round
95. Composite pattern

Implement composite pattern for tree structures.

  • Component: Component interface
  • Leaf: Leaf
  • Composite: Composite
  • Operation: operation()
javascript
// Composite pattern
class Component {
  operation() {}
}

class Leaf extends Component {
  operation() {
    console.log('Leaf: Operation');
  }
}

class Composite extends Component {
  constructor() {
    super();
    this.children = [];
  }
  add(component) {
    this.children.push(component);
  }
  remove(component) {
    this.children = this.children.filter(c => c !== component);
  }
  operation() {
    console.log('Composite: Operation');
    this.children.forEach(child => child.operation());
  }
}
Coding Round
96. Visitor pattern

Implement visitor pattern for adding operations to objects.

  • Visitor: Visitor interface
  • Element: ElementA, ElementB
  • Accept: accept($visitor)
  • Counting: CountingVisitor
javascript
// Visitor pattern
class Visitor {
  visitElementA(element) {}
  visitElementB(element) {}
}

class Element {
  accept(visitor) {}
}

class ElementA extends Element {
  accept(visitor) {
    visitor.visitElementA(this);
  }
}

class ElementB extends Element {
  accept(visitor) {
    visitor.visitElementB(this);
  }
}

class ConcreteVisitor extends Visitor {
  visitElementA(element) {
    console.log('Visiting ElementA');
  }
  visitElementB(element) {
    console.log('Visiting ElementB');
  }
}
Coding Round
97. Iterator pattern

Implement iterator pattern for sequential access.

  • Iterator: Iterator class
  • Reverse: ReverseIterator
  • Filter: FilteredIterator
  • Skip: SkipIterator
javascript
// Iterator pattern
class Iterator {
  constructor(collection) {
    this.collection = collection;
    this.index = 0;
  }
  next() {
    return this.collection[this.index++];
  }
  hasNext() {
    return this.index < this.collection.length;
  }
}

class CustomCollection {
  constructor() {
    this.items = [];
  }
  add(item) {
    this.items.push(item);
  }
  getIterator() {
    return new Iterator(this.items);
  }
}

const collection = new CustomCollection();
collection.add('A');
collection.add('B');
collection.add('C');
const iterator = collection.getIterator();
while (iterator.hasNext()) {
  console.log(iterator.next());
}
Coding Round
98. Template Method pattern

Implement template method with customizable steps.

  • Template: Template abstract class
  • Method: templateMethod()
  • Default: DefaultTemplate
  • Logging: LoggingTemplate
javascript
// Template Method pattern
class AbstractClass {
  templateMethod() {
    this.step1();
    this.step2();
    this.step3();
  }
  step1() { console.log('Step 1'); }
  step2() { console.log('Step 2'); }
  step3() { console.log('Step 3'); }
}

class ConcreteClass extends AbstractClass {
  step2() {
    console.log('Concrete Step 2');
  }
}

const concrete = new ConcreteClass();
concrete.templateMethod();
Coding Round
99. Builder pattern

Implement builder pattern for constructing complex objects.

  • Builder: ConcreteBuilder
  • Director: Director
  • Product: Product
  • Build: buildMinimal, buildFull
javascript
// Builder pattern
class Product {
  constructor() {
    this.parts = [];
  }
  add(part) { this.parts.push(part); }
  listParts() { console.log(this.parts.join(', ')); }
}

class Builder {
  reset() {}
  buildStepA() {}
  buildStepB() {}
  getResult() {}
}

class ConcreteBuilder extends Builder {
  constructor() {
    super();
    this.product = new Product();
  }
  reset() {
    this.product = new Product();
  }
  buildStepA() {
    this.product.add('Part A');
  }
  buildStepB() {
    this.product.add('Part B');
  }
  getResult() {
    return this.product;
  }
}

class Director {
  constructor(builder) {
    this.builder = builder;
  }
  buildMinimal() {
    this.builder.buildStepA();
  }
  buildFull() {
    this.builder.buildStepA();
    this.builder.buildStepB();
  }
}
Coding Round
100. Prototype pattern

Implement prototype pattern for cloning objects.

  • Prototype: Prototype
  • Clone: clone()
  • Deep clone: deepClone()
  • Mutable: MutablePrototype
javascript
// Prototype pattern
class Prototype {
  clone() {
    return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
  }
  deepClone() {
    return JSON.parse(JSON.stringify(this));
  }
}

class ConcretePrototype extends Prototype {
  constructor(name) {
    super();
    this.name = name;
    this.nested = { value: 42 };
  }
}

const original2 = new ConcretePrototype('Original');
const copy = original2.clone();
copy.name = 'Copy';
copy.nested.value = 99;
console.log(original2.name); // Original
console.log(original2.nested.value); // 99 (shallow copy)

const deepCopy = original2.deepClone();
deepCopy.nested.value = 100;
console.log(original2.nested.value); // 99 (deep copy)