### Defining Project Scripts and Dependencies in package.json Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This `package.json` example illustrates how to define project metadata, scripts for common tasks like starting, building, and testing, and manage both production (`dependencies`) and development (`devDependencies`) package requirements. It ensures consistent environments and simplifies dependency management. ```json { "name": "my-app", "scripts": { "start": "vite", "build": "vite build", "test": "jest" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "vite": "^4.3.9", "jest": "^29.5.0" } } ``` -------------------------------- ### Creating a Next.js Project with Yarn Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This command initializes a new Next.js project using Yarn. It performs the same setup as the npm command, creating the project directory and installing dependencies, suitable for Yarn users. ```Shell yarn create next-app ``` -------------------------------- ### Defining PWA with Web App Manifest (JavaScript) Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This JSON configuration defines the core properties of a Progressive Web App, including its name, short name, start URL, display mode, theme colors, and icons. It enables the PWA to be discoverable and installable on a user's home screen, providing an app-like experience. ```javascript // web app manifest (manifest.json) { "name": "My PWA App", "short_name": "PWA", "start_url": "/index.html", "display": "standalone", "background_color": "#ffffff", "theme_color": "#2196f3", "icons": [{ "src": "icon-192x192.png", "sizes": "192x192", "type": "image/png" }] } ``` -------------------------------- ### Performing HTTP GET and POST Requests with Fetch API Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This JavaScript snippet demonstrates how to make basic HTTP GET and POST requests using the Fetch API. It shows a simple GET request to retrieve data and a POST request to send JSON data, including setting the `Content-Type` header. ```javascript // GET request fetch('/api/users'); // POST request fetch('/api/users', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: 'John'}) }); ``` -------------------------------- ### Demonstrating Prototypal Inheritance in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This example illustrates JavaScript's prototypal inheritance model, where objects inherit properties and methods from their prototype objects. It shows how to establish an inheritance chain using `Object.create` and `call` for constructor chaining. ```javascript function Animal(name) { this.name = name; } Animal.prototype.speak = function() { return `${this.name} makes a sound`; }; function Dog(name) { Animal.call(this, name); } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.speak = function() { return `${this.name} barks`; }; const dog = new Dog('Rex'); dog.speak(); ``` -------------------------------- ### Implementing CI/CD Pipeline with GitHub Actions for Frontend Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This GitHub Actions workflow defines a CI/CD pipeline triggered on pushes to `main` and `develop` branches and pull requests to `main`. It includes a `build-test` job for installing dependencies, linting, testing, and building the application, and a `deploy` job that deploys the build artifact to Firebase Hosting upon successful completion on the `main` branch. ```yaml name: CI/CD Pipeline on: push: branches: [main, develop] pull_request: branches: [main] jobs: build-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '16' - run: npm ci - run: npm run lint - run: npm test - run: npm run build - uses: actions/upload-artifact@v3 with: name: build path: ./dist deploy: needs: build-test if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/download-artifact@v3 with: name: build - name: Deploy to Firebase uses: FirebaseExtended/action-hosting-deploy@v0 with: firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} ``` -------------------------------- ### Implementing Responsive vs. Mobile-First Design in CSS Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewJob.md This CSS snippet demonstrates the core difference between desktop-first responsive design and a mobile-first approach. The desktop-first example uses `max-width` media queries to scale down from a large screen default, while the mobile-first example uses `min-width` media queries to progressively enhance the layout for larger screens, starting from a small screen default. ```css /* Desktop-first (responsive) approach */ .container { width: 1200px; /* Large screen design by default */ } @media (max-width: 768px) { .container { width: 100%; /* Overrides for smaller screens */ } } /* Mobile-first approach */ .container { width: 100%; /* Small screen design by default */ } @media (min-width: 768px) { .container { width: 750px; /* Enhancements for larger screens */ } } @media (min-width: 1200px) { .container { width: 1170px; /* Enhancements for even larger screens */ } } ``` -------------------------------- ### Starting Next.js Development Server with npm Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This command starts the Next.js development server using npm. It compiles the application and makes it accessible locally, typically at `http://localhost:3000`, enabling real-time development and testing. ```Shell npm run dev ``` -------------------------------- ### Demonstrating HTTP Methods with JavaScript Fetch API Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This snippet illustrates the usage of various HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) using the JavaScript `fetch` API. It shows how to perform common operations like retrieving, creating, updating, and deleting resources, along with a structured example of a RESTful API client. ```javascript // 1. GET: Retrieve data (idempotent, cacheable) // Used for: Reading resources without modification fetch('https://api.example.com/users/123', { method: 'GET' }); // 2. POST: Create new resource or submit data (not idempotent) // Used for: Creating new resources, form submissions fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', email: 'john@example.com' }) }); // 3. PUT: Replace entire resource (idempotent) // Used for: Complete updates, replacing resources fetch('https://api.example.com/users/123', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', email: 'john@example.com' }) }); // 4. PATCH: Partial resource update (not necessarily idempotent) // Used for: Partial updates to resources fetch('https://api.example.com/users/123', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'new-email@example.com' }) }); // 5. DELETE: Remove a resource (idempotent) // Used for: Deleting resources fetch('https://api.example.com/users/123', { method: 'DELETE' }); // 6. HEAD: Same as GET but without response body (idempotent, cacheable) // Used for: Checking if resource exists, getting metadata fetch('https://api.example.com/users/123', { method: 'HEAD' }); // 7. OPTIONS: Get communication options for resource (idempotent) // Used for: CORS preflight, discovering API capabilities fetch('https://api.example.com/users', { method: 'OPTIONS' }); // 8. TRACE: Echo back request (idempotent) // Used for: Debugging, rarely used in production // 9. CONNECT: Establish tunnel to server // Used for: HTTP tunneling, SSL/TLS // RESTful API example with different methods const api = { getUsers: () => fetch('/api/users'), getUser: (id) => fetch(`/api/users/${id}`), createUser: (data) => fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }), updateUser: (id, data) => fetch(`/api/users/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }), patchUser: (id, data) => fetch(`/api/users/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }), deleteUser: (id) => fetch(`/api/users/${id}`, { method: 'DELETE' }) } ``` -------------------------------- ### Creating Screen Reader Friendly HTML Markup Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This HTML snippet provides examples of semantic and accessible markup designed for screen readers. It includes a skip link for keyboard navigation, an ARIA-labeled navigation menu, and a `main` element with `tabindex` and an `aria-live` region for announcing dynamic content changes. ```html

Page Title

``` -------------------------------- ### Usage Examples for Custom Array Prototype Methods in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This snippet demonstrates the practical application of the custom `myMap`, `myFilter`, and `myReduce` methods. It initializes an array of numbers and then uses each custom method to perform common array transformations and aggregations, showcasing their functionality and expected outputs. ```JavaScript const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.myMap(x => x * 2); console.log(doubled); // [2, 4, 6, 8, 10] const evens = numbers.myFilter(x => x % 2 === 0); console.log(evens); // [2, 4] const sum = numbers.myReduce((acc, current) => acc + current, 0); console.log(sum); // 15 ``` -------------------------------- ### Implementing Basic Service Worker Caching (JavaScript) Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This service worker script defines a cache name and a list of URLs to pre-cache during the `install` event. It then intercepts `fetch` requests, serving cached responses if available, otherwise falling back to the network. This enables basic offline functionality for the specified resources. ```javascript // Service worker implementation (sw.js) const CACHE_NAME = 'my-site-cache-v1'; const urlsToCache = [ '/', '/styles/main.css', '/scripts/main.js' ]; self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => cache.addAll(urlsToCache)) ); }); self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => response || fetch(event.request)) ); }); ``` -------------------------------- ### Starting Next.js Development Server with Yarn Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This command starts the Next.js development server using Yarn. Similar to the npm command, it compiles the application and serves it locally, allowing developers to view and interact with their Next.js application during development. ```Shell yarn dev ``` -------------------------------- ### Creating a Next.js Project with npm Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This command initializes a new Next.js project using npm's `npx` utility. It sets up the basic project structure and installs necessary dependencies, preparing the environment for development. ```Shell npx create-next-app@latest ``` -------------------------------- ### Illustrating Test-Driven Development (TDD) Cycle in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This example demonstrates the three steps of Test-Driven Development (TDD): first, writing a failing test; second, implementing minimal code to make the test pass; and third, refactoring the code while ensuring tests remain passing. It shows the iterative nature of TDD for a 'fetchUser' function. ```javascript // Step 1: Write failing test test('fetchUser gets correct data', async () => { const user = await fetchUser(123); expect(user.name).toBe('John'); }); // Step 2: Minimal implementation function fetchUser() { return {id: 123, name: 'John'}; } // Step 3: Proper implementation async function fetchUser(id) { const response = await fetch(`/api/users/${id}`); return response.json(); } ``` -------------------------------- ### Creating and Running a Next.js Application Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This snippet outlines the command-line steps required to initialize a new Next.js project and then start its development server. It uses `npx create-next-app` for scaffolding and `npm run dev` to launch the application locally. ```Shell npx create-next-app ``` ```Shell npm run dev ``` -------------------------------- ### Configuring HTTP Caching Headers Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This snippet provides examples of common HTTP caching headers. It shows `Cache-Control` directives for static assets (long-term caching) and dynamic content (no caching, revalidation required), along with an `ETag` for content versioning. ```text # Static assets Cache-Control: max-age=31536000, immutable # Dynamic content Cache-Control: no-cache ETag: "abc123" ``` -------------------------------- ### Controlling JavaScript Loading with Script Attributes in HTML Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This example illustrates the different ways to load JavaScript files in HTML using `script` tags. It shows the default blocking behavior, `async` for parallel download and immediate execution, and `defer` for parallel download and execution after HTML parsing, optimizing page load. ```HTML ``` -------------------------------- ### Illustrating the JavaScript Event Loop Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This example demonstrates the JavaScript event loop's role in managing execution order, showcasing the interplay between the call stack, callback queue (for `setTimeout`), and microtask queue (for Promises). It clarifies the non-blocking nature of asynchronous operations. ```javascript console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End'); ``` -------------------------------- ### Using Sass for CSS Preprocessing with Variables and Mixins Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This Sass example demonstrates the use of variables (`$primary`) for consistent color values and mixins (`@mixin button`) for reusable style blocks. It also shows nested selectors for cleaner, more organized CSS, enhancing maintainability and reducing redundancy. ```scss $primary: #3498db; @mixin button($bg-color) { background-color: $bg-color; border-radius: 4px; &:hover { opacity: 0.8; } } .container { max-width: 1200px; .header { display: flex; background-color: $primary; } .button { @include button($primary); } } ``` -------------------------------- ### Creating a Basic Next.js API Route Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This example illustrates how to create a simple API route in Next.js within the `pages/api` directory. It defines a default function that handles incoming requests (`req`) and sends responses (`res`), specifically demonstrating a GET request handler and a 405 (Method Not Allowed) response for other methods. ```JavaScript export default function handler(req, res) {\n if (req.method === 'GET') {\n res.status(200).json({ message: "Hello, world!" });\n } else {\n res.status(405).end(); // Method Not Allowed\n }\n} ``` -------------------------------- ### Starting Next.js Application in Production Mode (Shell) Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md After the application has been built for production, this command launches the Next.js application, serving the optimized build to users. It should be run in the production environment. ```Shell next start ``` -------------------------------- ### Demonstrating Different Test Types (Unit, Component, E2E) in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This snippet illustrates three common testing approaches: Unit testing using Jest for a pure function, Component testing with React Testing Library (RTL) for UI interaction, and End-to-End (E2E) testing with Cypress for a complete user flow. Each example highlights the scope and tools typically used for that test type. ```javascript // Unit test (Jest) test('calculates tax correctly', () => { expect(calculateTotal(100, 0.1)).toBe(110); }); // Component test (RTL) test('counter increments', () => { render(); fireEvent.click(screen.getByText('Increment')); expect(screen.getByText(/count: 1/i)).toBeInTheDocument(); }); // E2E test (Cypress) it('checkout flow works', () => { cy.visit('/shop'); cy.get('.product').first().click(); cy.get('.add-to-cart').click(); cy.get('.checkout').click(); cy.url().should('include', '/confirmation'); }) ``` -------------------------------- ### Implementing Layouts with Flexbox and CSS Grid Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewJob.md This snippet showcases the usage of Flexbox for one-dimensional layouts and CSS Grid for two-dimensional page layouts. The Flexbox example demonstrates space distribution and item alignment, while the Grid example illustrates a full page layout using `grid-template-columns`, `grid-template-rows`, `grid-template-areas`, and `gap` for precise element placement. ```CSS /* Flexbox example */ .flex-container { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; } /* Grid example */ .grid-layout { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: auto 1fr auto; grid-template-areas: "header header header" "sidebar content content" "footer footer footer"; gap: 20px; height: 100vh; } .header { grid-area: header; } .sidebar { grid-area: sidebar; } .content { grid-area: content; } .footer { grid-area: footer; } ``` -------------------------------- ### Implementing Resource Hints and Performance Monitoring in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This JavaScript snippet shows how to programmatically add various resource hints like `preconnect`, `prefetch`, `preload`, and `prerender` to optimize page loading. It also includes an example of using the `PerformanceObserver` API to measure and log resource and navigation timings for performance analysis. ```javascript // JavaScript can also trigger preconnect (goes beyond DNS) // This establishes DNS + TCP + TLS connections // Creating a link element programmatically function addPreconnect(domain) { const link = document.createElement('link'); link.rel = 'preconnect'; link.href = domain; document.head.appendChild(link); } // Pre-connecting to domains that will be used soon addPreconnect('https://api.example.com'); addPreconnect('https://cdn.example.com'); // Other resource hints function addResourceHint(type, url) { const link = document.createElement('link'); link.rel = type; link.href = url; document.head.appendChild(link); } // Prefetch - fetch and cache resources for future use addResourceHint('prefetch', 'https://example.com/page-2.html'); // Preload - fetch high-priority resources for current page addResourceHint('preload', 'https://example.com/critical.css'); // Prerender - fetch and render page in the background addResourceHint('prerender', 'https://example.com/likely-next-page.html'); // Performance impact measurement const performanceObserver = new PerformanceObserver((list) => { const entries = list.getEntries(); entries.forEach(entry => { console.log(`${entry.name}: ${entry.duration}ms`); }); }); performanceObserver.observe({ entryTypes: ['resource', 'navigation'] }); ``` -------------------------------- ### Defining Next.js Development Scripts in `package.json` Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This JSON snippet illustrates the standard script configurations within a Next.js project's `package.json` file. The `dev` script starts the development server, `build` compiles the application for production, and `start` runs the production build. These scripts are crucial for managing the application's lifecycle and are executed via `npm run ` or `yarn `. ```JSON { "scripts": { "dev": "next", "build": "next build", "start": "next start" } } ``` -------------------------------- ### Implementing Real-time Communication with WebSockets and SSE Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This JavaScript snippet demonstrates client-side implementations of WebSockets for bi-directional communication and Server-Sent Events (SSE) for one-way server-to-client streaming. It shows how to establish connections and handle incoming messages for both technologies. ```javascript // WebSocket const ws = new WebSocket('wss://example.com/socket'); ws.onmessage = e => console.log('Received:', JSON.parse(e.data)); // SSE const es = new EventSource('/events'); es.onmessage = e => console.log('Update:', e.data); ``` -------------------------------- ### Configuring CORS in Express.js Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This JavaScript snippet shows how to configure Cross-Origin Resource Sharing (CORS) using the `cors` middleware in an Express.js application. It specifies that only requests from 'https://allowed-site.com' are permitted for GET and POST methods. ```javascript // CORS configuration (Express) app.use(cors({ origin: 'https://allowed-site.com', methods: ['GET', 'POST'] })); ``` -------------------------------- ### Using Browser Hints for Resource Optimization (HTML) Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This HTML snippet demonstrates various browser hints to optimize resource loading. `preconnect` establishes early connections, `preload` fetches critical resources like fonts early, and `prefetch` fetches resources likely to be needed on subsequent navigations, improving perceived performance. ```HTML ``` -------------------------------- ### Examples of Node.js-Specific JavaScript Host Objects Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewJob.md This snippet lists examples of host objects found in a Node.js environment. These include `fs` (for file system operations), `process` (for process information), and `Buffer` (for binary data), which are specific to Node.js and extend JavaScript's capabilities for server-side programming. ```JavaScript // Host objects - Node.js environment // const fs = require('fs'); // Node.js module system // process.env.NODE_ENV; // Node.js process object // Buffer.from('hello'); // Node.js Buffer ``` -------------------------------- ### Creating a New Next.js Application with `create-next-app` Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Next.md This shell command initializes a new Next.js project named 'myapp'. It leverages `npx` to execute `create-next-app`, which sets up the necessary project structure, installs dependencies, and configures the basic environment for a Next.js application. This is the first step in setting up a new Next.js development environment. ```Shell npx create-next-app myapp ``` -------------------------------- ### Unit Testing with Jest in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This example demonstrates basic unit testing using the Jest framework. It shows how to define a test suite ('describe') and individual tests ('test') for a simple 'sum' function, asserting expected outcomes. ```javascript function sum(a, b) { return a + b; } describe('sum function', () => { test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); }); test('adds negative numbers correctly', () => { expect(sum(-1, -2)).toBe(-3); }); }); ``` -------------------------------- ### Implementing Graceful Degradation and Progressive Enhancement in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This snippet demonstrates two distinct approaches to cross-browser compatibility: graceful degradation and progressive enhancement. The graceful degradation example shows how to use `IntersectionObserver` for lazy loading images in modern browsers, with a fallback to immediate loading for older browsers. The progressive enhancement example starts with basic form validation, then adds live input validation and real-time asynchronous email validation as enhancements for capable browsers. ```javascript // Graceful Degradation Example // Modern approach with fallback function setupImageGallery() { // Try modern approach first if ('IntersectionObserver' in window) { // Use modern IntersectionObserver for lazy loading const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; observer.unobserve(img); } }); }); document.querySelectorAll('img[data-src]').forEach(img => { observer.observe(img); }); } else { // Fallback for older browsers: load all images immediately document.querySelectorAll('img[data-src]').forEach(img => { img.src = img.dataset.src; }); } } // Progressive Enhancement Example // Start with basic, working experience function setupFormValidation() { const form = document.querySelector('form'); // Basic form submission works everywhere (core experience) form.addEventListener('submit', function(event) { let isValid = validateForm(this); if (!isValid) { event.preventDefault(); showErrors(); } }); // Enhancement: Live validation as user types if ('querySelector' in document && 'addEventListener' in window) { const inputs = form.querySelectorAll('input, select, textarea'); inputs.forEach(input => { input.addEventListener('input', function() { validateField(this); }); }); } // Further enhancement: Real-time async validation if ('fetch' in window) { const emailField = form.querySelector('input[type="email"]'); if (emailField) { emailField.addEventListener('blur', function() { if (this.value) { fetch(`/validate-email?email=${encodeURIComponent(this.value)}`) .then(response => response.json()) .then(data => { if (!data.isValid) { showEmailError(data.message); } }); } }); } } } ``` -------------------------------- ### Simulating Browser Loading Process Steps in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This JavaScript snippet illustrates the key stages involved when a browser loads a website, from URL parsing and DNS resolution to TCP/TLS handshakes, HTTP request/response cycles, and the final rendering pipeline. It provides conceptual functions and objects representing each step of the browser's journey to display a web page. ```javascript // 1. User types "https://example.com" in browser // 2. DNS Lookup (simplified) function dnsResolve(domain) { // Check browser cache // Check OS cache // Check router cache // Check ISP DNS cache // Recursive DNS lookup if needed return '93.184.216.34'; // IP address for example.com } // 3. TCP Connection (3-way handshake) // - Client sends SYN packet // - Server responds with SYN-ACK // - Client sends ACK // 4. TLS Handshake (for HTTPS) // - Client hello with supported cipher suites // - Server hello with chosen cipher // - Certificate exchange and validation // - Key exchange // - Secure connection established // 5. HTTP Request const request = { method: 'GET', path: '/', host: 'example.com', headers: { 'User-Agent': 'Mozilla/5.0...', 'Accept': 'text/html,application/xhtml+xml...', 'Accept-Language': 'en-US,en;q=0.9', 'Cookie': 'session=abc123' } }; // 6. Server Processing // - Web server receives request // - Application server processes request // - Database queries if needed // - Response generated // 7. HTTP Response const response = { status: 200, headers: { 'Content-Type': 'text/html', 'Content-Length': '1234', 'Cache-Control': 'max-age=3600' }, body: '...' }; // 8. Browser Processing // - Parse HTML to construct DOM tree // - Request additional resources (CSS, JavaScript, images) // - Parse CSS to construct CSSOM // - Execute JavaScript // 9. Rendering Pipeline function browserRendering() { // Construct render tree (DOM + CSSOM) // Layout/reflow (calculate positions and dimensions) // Paint (fill in pixels) // Composite layers } // 10. Display final rendered page ``` -------------------------------- ### Distinguishing Spread and Rest Operators in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md Clarifies the usage of the '...' syntax for both spread and rest operators; spread expands iterables into individual elements, while rest collects remaining elements into an array. Examples demonstrate their application in array/object manipulation and function parameters. ```javascript // Spread operator examples const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5] const obj1 = { x: 1, y: 2 }; const obj2 = { ...obj1, z: 3 }; // { x: 1, y: 2, z: 3 } // Function arguments const numbers = [1, 2, 3]; console.log(Math.max(...numbers)); // 3 // Rest parameter examples function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4)); // 10 const [first, ...others] = [1, 2, 3, 4, 5]; console.log(others); // [2, 3, 4, 5] ``` -------------------------------- ### Optimizing Critical Rendering Path with HTML Resource Hints and Inline CSS Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This HTML snippet demonstrates techniques to optimize the critical rendering path. It includes for early connection to origins, for preloading critical resources like fonts, inline ``` -------------------------------- ### Implementing Closures for Data Encapsulation in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This example illustrates closures, where an inner function retains access to variables from its outer lexical scope even after the outer function has finished executing. It shows how closures can be used to create private variables and maintain state. ```javascript function createCounter() { let count = 0; // Private variable return { increment: () => ++count, get: () => count }; } const counter = createCounter(); counter.increment(); ``` -------------------------------- ### Implementing CSRF Protection in HTML and JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This example illustrates two common methods for preventing Cross-Site Request Forgery (CSRF) attacks. It shows how to include a hidden anti-CSRF token in an HTML form and how to send a CSRF token in the headers of an AJAX `fetch` request. ```html
``` -------------------------------- ### End-to-End Testing with Cypress Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This example demonstrates end-to-end testing for a login form using Cypress. It shows how to visit a page, interact with form elements (type, click), and assert URL changes and element content for both successful login and error scenarios. ```javascript // cypress/integration/login.spec.js describe('Login Form', () => { it('logs in successfully with correct credentials', () => { cy.visit('/login'); cy.get('input[name=username]').type('testuser'); cy.get('input[name=password]').type('password123'); cy.get('button[type=submit]').click(); cy.url().should('include', '/dashboard'); cy.get('h1').should('contain', 'Welcome, testuser'); }); it('shows error with incorrect credentials', () => { cy.visit('/login'); cy.get('input[name=username]').type('testuser'); cy.get('input[name=password]').type('wrongpassword'); cy.get('button[type=submit]').click(); cy.get('.error-message').should('be.visible'); cy.get('.error-message').should('contain', 'Invalid credentials'); }); }); ``` -------------------------------- ### Optimizing Website Assets and Resources for Performance Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This comprehensive snippet illustrates various techniques for optimizing website assets and resources, covering image, CSS, JavaScript, font, and server-side optimizations. It provides practical examples for using modern image formats, responsive images, critical CSS, asynchronous JavaScript loading, font display strategies, resource hints, and build process optimizations. ```html // 1. Image optimization strategies // Use modern formats Description // Responsive images Description ``` ```html // 2. CSS optimization // Critical CSS inline in head // Non-critical CSS loaded asynchronously ``` ```javascript // 3. JavaScript optimization // Code splitting and dynamic imports import(/* webpackChunkName: "feature" */ './feature.js') .then(module => { // Use the module }); // Defer non-critical JavaScript ``` ```css // 4. Font optimization // Font display swap @font-face { font-family: 'CustomFont'; src: url('customfont.woff2') format('woff2'); font-display: swap; } ``` ```html // Preload important fonts ``` ```html // 5. Resource hints // Preconnect to important origins // DNS prefetch for later resources ``` ```text // 6. Server optimization // Configure caching headers Cache-Control: max-age=31536000, immutable // Enable compression Content-Encoding: gzip ``` ```javascript // 7. Build process optimization // Tree shaking with ES modules export function used() { console.log('This function will be included'); } export function unused() { console.log('This function will be removed in production build'); } ``` ```javascript // 8. Lazy loading components (React example) const LazyComponent = React.lazy(() => import('./LazyComponent')); ``` -------------------------------- ### Preventing XSS in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This snippet demonstrates methods to prevent Cross-Site Scripting (XSS) attacks in JavaScript. It shows a vulnerable approach using `innerHTML` and safer alternatives like `textContent` to render user input, along with an example of using a sanitization library like DOMPurify. ```javascript // Vulnerable document.getElementById('output').innerHTML = userInput; // Safe document.getElementById('output').textContent = userInput; // With sanitization const sanitized = DOMPurify.sanitize(userInput); ``` -------------------------------- ### Setting Up WebSocket Connection in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This function establishes a WebSocket connection to a specified URL (`wss://example.com/socket`). It defines handlers for `onopen`, `onmessage`, `onclose`, and `onerror` events. It also provides a `sendMessage` utility to send JSON data when the socket is open and includes basic reconnection logic upon closure. ```JavaScript function setupWebSocket() { const socket = new WebSocket('wss://example.com/socket'); socket.onopen = (event) => { console.log('WebSocket connection established'); // Can send data immediately socket.send(JSON.stringify({ type: 'subscribe', channel: 'updates' })); }; socket.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Message from server:', data); // Process data... }; socket.onclose = (event) => { console.log('WebSocket connection closed:', event.code, event.reason); // Reconnect logic setTimeout(setupWebSocket, 3000); }; socket.onerror = (error) => { console.error('WebSocket error:', error); }; // Sending data to server function sendMessage(message) { if (socket.readyState === WebSocket.OPEN) { socket.send(JSON.stringify(message)); } } return { sendMessage, close: () => socket.close() }; } ``` -------------------------------- ### Implementing Responsive Images with HTML srcset and sizes Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This HTML snippet demonstrates two methods for responsive images using `srcset` and `sizes` attributes. The first example uses pixel density descriptors (1x, 2x, 3x) for retina displays, while the second uses width descriptors (600w, 1200w, 2000w) with `sizes` to provide different image sources based on viewport width. ```HTML Responsive image Responsive image ``` -------------------------------- ### Automated Accessibility Testing with Jest and axe-core Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterview.md This JavaScript snippet shows how to integrate automated accessibility testing into a Jest test suite using `jest-axe`. It demonstrates rendering a component and asserting that it has no accessibility violations, providing a basic setup for continuous accessibility checks within a development workflow. ```javascript // Using axe-core for automated testing import { axe } from 'jest-axe'; test('accessibility check', async () => { const { container } = render(); const results = await axe(container); expect(results).toHaveNoViolations(); }); ``` -------------------------------- ### HTTP GET Request with Conditional Headers Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewJob.md This HTTP request example demonstrates the use of `If-Modified-Since` and `If-None-Match` headers. These headers are used by the client to make conditional requests, allowing the server to return a `304 Not Modified` status if the resource hasn't changed, thereby optimizing bandwidth and improving performance. ```http # Request with conditional headers GET /article.html HTTP/1.1 Host: example.com If-Modified-Since: Wed, 21 Oct 2022 07:28:00 GMT If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` -------------------------------- ### Implementing Responsive Design with CSS Media Queries Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This example illustrates how to use CSS media queries to apply different font sizes to the `body` element based on the viewport width. It defines base styles and then overrides them for mobile, tablet, and desktop screen sizes, demonstrating a common approach to responsive typography. ```CSS /* Base styles for all screen sizes */ body { font-size: 16px; } /* Mobile styles */ @media (max-width: 767px) { body { font-size: 14px; } } /* Tablet styles */ @media (min-width: 768px) and (max-width: 1023px) { body { font-size: 15px; } } /* Desktop styles */ @media (min-width: 1024px) { body { font-size: 16px; } } ``` -------------------------------- ### Implementing a Basic Multistep Form in Vanilla JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/Tasks.md This JavaScript snippet outlines the core structure for a multi-step form. It initializes the current step, defines placeholder functions for step navigation (`showStep`, `nextStep`, `prevStep`), and includes an event listener to prevent default form submission and display a success alert. ```JavaScript // script.js let currentStep = 1; function showStep(step) { // Display current step in the UI } function nextStep() { // Handle next step function } function prevStep() { // Handle previous step function } document .getElementById("multiStepForm") .addEventListener("submit", function (event) { event.preventDefault(); alert("🎉 Success"); }); showStep(currentStep); ``` -------------------------------- ### Implementing Basic State with Zustand Source: https://github.com/kornerious/fronted-dev-interview/blob/main/MyNotes.md This example demonstrates how to define a simple store using Zustand's `create` function. It initializes a `count` state and provides an `inc` action to increment the count. Zustand simplifies state management by using direct function calls instead of actions and reducers. ```JavaScript useStore = create(set => ({ count: 0, inc: () => set(s => ({ count: s.count + 1 })) })) ``` -------------------------------- ### Using Static Factory Methods for Object Creation in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This example demonstrates how to instantiate objects using static factory methods, specifically `Person.createFromFullName`. It highlights how these methods can encapsulate complex object creation logic, making the instantiation process cleaner and more flexible. ```JavaScript // Using the factory methods const john = Person.createFromFullName('John Doe'); console.log(john.getFullName()); // "John Doe" ``` -------------------------------- ### Illustrating Synchronous Function Execution in JavaScript Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This synchronous example demonstrates how code execution blocks until a time-consuming operation, represented by `heavyCalculation()`, completes. The `console.log` statements will execute strictly in order: 'Start', then 'Result:', and finally 'End', only after `heavyCalculation()` has finished. This behavior can lead to a frozen user interface if the blocking operation is long-running. ```JavaScript // Synchronous example function syncOperation() { console.log('Start'); // This blocks execution until complete const result = heavyCalculation(); console.log('Result:', result); console.log('End'); } ``` -------------------------------- ### Compiling TypeScript Files with TSC Source: https://github.com/kornerious/fronted-dev-interview/blob/main/TypeScript.md This section explains how to compile a TypeScript (.ts) file into a JavaScript (.js) file using the TypeScript Compiler (tsc) command. It highlights the necessity of having TypeScript installed for successful compilation. The provided code demonstrates a basic TypeScript variable declaration and logging, serving as a general example within a TypeScript context. ```TypeScript const currentStatus: Status = 'active'; console.log(currentStatus); // active ``` -------------------------------- ### Defining Fixed, Fluid, and Responsive CSS Layouts Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This CSS example illustrates three different web layout approaches: fixed, fluid, and responsive. The fixed layout uses a static pixel width, the fluid layout uses percentages for width with a max-width, and the responsive layout combines percentages with media queries to adapt the layout structure for different screen sizes, such as hiding a sidebar or stacking columns on smaller viewports. ```css /* Fixed layout */ .fixed-layout { width: 960px; margin: 0 auto; } /* Fluid layout */ .fluid-layout { width: 90%; max-width: 1200px; margin: 0 auto; } /* Responsive layout */ .responsive-layout { width: 95%; max-width: 1200px; margin: 0 auto; } @media (max-width: 768px) { .responsive-layout { width: 100%; } .sidebar { display: none; /* Hide sidebar on mobile */ } .columns { flex-direction: column; /* Stack columns on mobile */ } } ``` -------------------------------- ### Understanding CSS Selector Matching Order Source: https://github.com/kornerious/fronted-dev-interview/blob/main/FrontInterviewMain.md This example illustrates the right-to-left processing order browsers use for CSS selectors. For `nav ul li a.active`, the browser starts by finding all elements with the class `active`, then filters them down based on their ancestry (``, `
  • `, `