### Initializing a New Next.js Application with create-next-app Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md These shell commands demonstrate how to quickly initialize a new Next.js application using `create-next-app`. The first command initiates an interactive setup, while the second shows how to start a project based on a specific example from the Next.js examples collection. ```Shell npx create-next-app@latest ``` ```Shell npx create-next-app --example api-routes ``` -------------------------------- ### Starting Next.js Development Server with Yarn (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md Launches the Next.js development server using `yarn dev`. Similar to the npm command, this starts a local server for development, providing real-time updates and a debugging environment for the Next.js application. It requires the project dependencies to be installed. ```Shell yarn dev ``` -------------------------------- ### Starting Next.js Development Server with npm (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md Launches the Next.js development server using `npm run dev`. This command compiles the application and serves it locally, typically on `http://localhost:3000`, enabling features like hot module replacement and live reloading for efficient development. It requires the project dependencies to be installed. ```Shell npm run dev ``` -------------------------------- ### Deploying Next.js Application with Build and Start Commands Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This snippet demonstrates the essential command-line steps for preparing and running a Next.js application in a production environment. The 'next build' command optimizes the application for performance, while 'next start' launches the built application. ```bash next build ``` ```bash next start ``` -------------------------------- ### Running Storybook for Content Bag Components Source: https://github.com/kornerious/frontend-interview/blob/main/ResidentConvensions.md This shell command is used to start the Storybook development server, which provides a living style guide and interactive documentation for the `ContentBag` components. Developers can use Storybook to view examples, test components in isolation, and understand their various configurations and features. ```shell npm run storybook ``` -------------------------------- ### Creating Next.js Project with Yarn (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md Initializes a new Next.js application using `yarn create next-app`. This command uses Yarn's `create` functionality to scaffold a new Next.js project, providing an alternative to npm for project setup. It requires Node.js and Yarn to be installed on the system. ```Shell yarn create next-app ``` -------------------------------- ### Configuring Next.js Development Scripts (JSON) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This JSON snippet shows the standard script configurations added to the `package.json` file when a Next.js application is initialized. These scripts define commands for running the development server (`dev`), building the application for production (`build`), and starting the production server (`start`). ```JSON { "scripts": { "dev": "next", "build": "next build", "start": "next start" } } ``` -------------------------------- ### Creating a New Next.js Application (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This command initializes a new Next.js project with a default setup. It uses `npx` to execute the `create-next-app` package, setting up the necessary files and dependencies for a new Next.js application named 'myapp'. ```Shell npx create-next-app myapp ``` -------------------------------- ### Performing HTTP GET and POST Requests with Fetch API (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example illustrates how to make basic HTTP `GET` and `POST` requests using the JavaScript Fetch API. The `GET` request retrieves data, while the `POST` request sends JSON data to create a new resource, specifying the `Content-Type` header. ```javascript // GET request fetch('/api/users'); ``` ```javascript // POST request fetch('/api/users', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: 'John'}) }); ``` -------------------------------- ### Defining Web App Manifest for PWA Installation (JSON) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This JSON snippet defines a web app manifest, `manifest.json`, which provides metadata about the PWA. It specifies the app's name, short name, start URL, display mode, theme colors, and icons, enabling the app to be added to a user's home screen and appear as a native application. ```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" }] } ``` -------------------------------- ### Creating a Basic 'Hello World' Page in Next.js (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This JavaScript code demonstrates how to create a simple 'Hello World' page in Next.js using a React functional component. Placed in `page.js` within the `app` directory, this component renders a basic HTML structure with a 'Hello, Next.js!' heading, serving as a foundational example for page creation. ```JavaScript // page.js import React from 'react'; const HomePage = () => { return (

Hello, Next.js!

); }; export default HomePage; ``` -------------------------------- ### Creating Next.js Project with npm (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md Initializes a new Next.js application using `npx create-next-app@latest`. This command leverages npm's package runner to execute the latest version of the Next.js project creation tool, setting up the basic project structure and dependencies. It requires Node.js and npm to be installed on the system. ```Shell npx create-next-app@latest ``` -------------------------------- ### Implementing CI/CD Pipeline with GitHub Actions (YAML) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This YAML snippet defines a GitHub Actions workflow for a CI/CD pipeline. It triggers on pushes to `main` and `develop` branches and pull requests to `main`. The `build-test` job checks out code, sets up Node.js, installs dependencies, runs linting, tests, and builds, then uploads the build artifact. The `deploy` job, dependent on `build-test`, downloads the artifact and deploys to Firebase if the branch is `main`. ```yaml # GitHub Actions workflow example 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 }} ``` -------------------------------- ### Illustrating Test-Driven Development (TDD) Cycle in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example demonstrates the three steps of Test-Driven Development: first, writing a failing test for `fetchUser`; second, implementing a minimal function to make the test pass; and third, refactoring to a proper, asynchronous implementation while ensuring the test still passes. It showcases the iterative nature of TDD. ```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(); } ``` -------------------------------- ### Defining Project Scripts and Dependencies with package.json (JSON) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This JSON snippet illustrates a `package.json` file, which is used by package managers like npm or Yarn. It defines project metadata, scripts for common tasks (start, build, test), and lists production dependencies (react, react-dom) and development dependencies (vite, jest) with their version ranges. ```json // package.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" } } ``` -------------------------------- ### Initializing Apollo Client for Next.js GraphQL Integration Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This snippet demonstrates the basic setup for Apollo Client in a Next.js application. It configures the client to connect to a GraphQL endpoint at '/api/graphql' and utilizes 'InMemoryCache' for efficient client-side data caching. ```javascript import { ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: '/api/graphql', cache: new InMemoryCache(), }); ``` -------------------------------- ### Creating Screen Reader Friendly HTML Markup Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This HTML snippet provides examples of best practices for creating screen reader-friendly web content. It demonstrates the use of semantic HTML elements (`header`, `nav`, `main`), a skip link, `aria-label` for navigation, `aria-current` for active links, and `aria-live` for dynamic content updates, enhancing navigability and comprehension for assistive technologies. ```html

Page Title

``` -------------------------------- ### Demonstrating Unit, Component, and E2E Tests in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This snippet illustrates examples of different testing types: a Jest unit test for a pure function, a React Testing Library component test for UI interaction, and a Cypress end-to-end test for a complete user flow. It highlights the distinct scopes and tools used for each testing level. ```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'); }); ``` -------------------------------- ### Illustrating the Virtual DOM Diffing and Reconciliation Process Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This simplified example demonstrates the core steps of the Virtual DOM process in React. It shows how two different virtual DOM trees (`vdom1` and `vdom2`) are compared (diffing) to identify minimal changes, and then how only those specific changes are applied to the real DOM (reconciliation), optimizing rendering performance. ```jsx // Simplified Virtual DOM process // 1. Initial render const vdom1 =

Count: 0

; // React creates real DOM from this virtual representation // 2. State update const vdom2 =

Count: 1

; // 3. Diffing - React compares vdom1 and vdom2 // Only the text content in

needs to change // 4. Reconciliation - React updates only what changed // paragraph.textContent = 'Count: 1'; // No need to recreate entire DOM structure ``` -------------------------------- ### Example Data for Next.js Dynamic Routing (JSON) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This JSON array represents a typical data structure for articles, used to illustrate how Next.js dynamic routing can generate unique pages for each entry based on a 'slug' property. It shows initial data and an example of new data being added. ```JSON [ { "id": 0, "slug": "breaking-news", "title": "Breaking News", "content": "This just in..." }, { "id": 1, "slug": "latest-updates", "title": "Latest Updates", "content": "Here's what's happening now..." } ] ``` ```JSON [ ... { "id": 2, "slug": "new-developments", "title": "New Developments", "content": "Updates on recent events..." } ] ``` -------------------------------- ### Implementing ES6 Modules for Code Organization in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example demonstrates how ES6 modules facilitate code organization through exports and imports. It shows named exports, default exports for classes, and how to import them into another file, including aliasing named imports and performing dynamic imports for lazy loading. ```javascript // math.js (exporting module) export const PI = 3.14159; export function add(a, b) { return a + b; } export function multiply(a, b) { return a * b; } // Default export export default class Calculator { add(a, b) { return a + b; } } // app.js (importing module) import Calculator, { PI, add, multiply as mult } from './math.js'; console.log(PI); // 3.14159 console.log(add(2, 3)); // 5 console.log(mult(2, 3)); // 6 const calc = new Calculator(); console.log(calc.add(2, 3)); // 5 // Dynamic import (lazy loading) async function loadModule() { const math = await import('./math.js'); return math.add(2, 3); } ``` -------------------------------- ### Addressing Common HTML Accessibility Issues Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This HTML example showcases common accessibility pitfalls like missing alt text on images, vague link text, and unlabeled form controls. It then provides improved code demonstrating how to fix these issues by adding `alt` attributes, descriptive link text, and `label` elements linked to inputs, significantly enhancing usability for all users. ```html Click here Company Logo View product details ``` -------------------------------- ### Controlling JavaScript Script Loading with HTML Attributes Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example illustrates the different HTML attributes (`async`, `defer`) used to control how external JavaScript files are loaded and executed. It contrasts the default blocking behavior with parallel downloading and execution timing options, crucial for optimizing page load performance. ```HTML ``` -------------------------------- ### Adjusting Image Quality in Next.js Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This example demonstrates setting the image quality for a Next.js Image component using the `quality` property. Values range from 1 to 100, allowing fine-grained control over image compression and file size. ```JSX Example ``` -------------------------------- ### Creating a Basic GET API Route in Next.js Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This snippet illustrates how to create a simple API endpoint in Next.js within the `pages/api` directory. It defines a default function that handles incoming requests (`req`) and sends responses (`res`), specifically responding to GET requests with a JSON message and returning a 405 status for other HTTP methods. This pattern allows for building serverless functions directly within a Next.js application. ```JavaScript // pages/api/hello.js export default function handler(req, res) { if (req.method === 'GET') { res.status(200).json({ message: "Hello, world!" }); } else { res.status(405).end(); // Method Not Allowed } } ``` -------------------------------- ### Implementing Efficient Responsive Design with CSS and Tailwind Source: https://github.com/kornerious/frontend-interview/blob/main/MyNotes.md Shows how to create responsive designs using a mobile-first approach with CSS media queries and utility frameworks like Tailwind CSS. The CSS example adjusts padding based on screen width, while the Tailwind example applies different padding classes for mobile and medium screens. ```CSS .card { padding: 1rem; } @media (min-width: 768px) { .card { padding: 2rem; } } ``` ```HTML

``` -------------------------------- ### Configuring HTTP Caching Headers Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example shows common HTTP caching headers. `Cache-Control: max-age=31536000, immutable` is used for static assets to allow aggressive caching, while `Cache-Control: no-cache` and `ETag` are used for dynamic content to ensure revalidation with the server. ```http # Static assets Cache-Control: max-age=31536000, immutable ``` ```http # Dynamic content Cache-Control: no-cache ETag: "abc123" ``` -------------------------------- ### Using Custom Array Prototype Methods in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This snippet demonstrates how to use the custom `myMap`, `myFilter`, and `myReduce` methods defined on `Array.prototype`. It shows examples of doubling numbers, filtering even numbers, and summing an array, illustrating their practical application 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 ``` -------------------------------- ### CSS Resetting vs. Normalizing Examples Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md Demonstrates basic examples of CSS reset, which removes all browser defaults, and CSS normalize, which preserves useful defaults while correcting inconsistencies, highlighting their different approaches to cross-browser consistency. ```CSS /* Reset example */ * { margin: 0; padding: 0; box-sizing: border-box; } /* Normalize example (partial) */ html { line-height: 1.15; -webkit-text-size-adjust: 100%; } body { margin: 0; } ``` -------------------------------- ### Configuring Image Sizing and Layout with Next.js Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This example shows how to use `layout="fill"` and `objectFit="contain"` with the Next.js Image component. `layout="fill"` makes the image responsive to its parent container, while `objectFit` controls how the image resizes within that container, crucial for preventing Cumulative Layout Shift (CLS). ```JSX Example ``` -------------------------------- ### Implementing Basic Service Worker Caching (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This JavaScript snippet shows the core implementation of a service worker (`sw.js`) for basic offline caching. During the `install` event, it opens a cache and adds predefined URLs. During the `fetch` event, it intercepts network requests, serving cached responses if available, otherwise fetching from the network. This enables offline functionality for specified assets. ```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)) ); }); ``` -------------------------------- ### Examples of Node.js Host Objects in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This snippet provides examples of host objects specific to the Node.js runtime environment. These objects, such as `fs` (file system), `process` (process information), and `Buffer` (binary data), are part of Node.js's built-in modules and APIs, enabling server-side and command-line operations. ```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 ``` -------------------------------- ### Simplifying State Management with Zustand Source: https://github.com/kornerious/frontend-interview/blob/main/MyNotes.md This example demonstrates a basic Zustand store creation. It defines a `count` state and an `inc` action to increment it, showcasing Zustand's minimalist API for global state management without actions or reducers. ```JavaScript useStore = create(set => ({ count: 0, inc: () => set(s => ({ count: s.count + 1 })) })) ``` -------------------------------- ### Implementing Redux State Management in React Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This code illustrates a basic Redux setup for state management in a React application. It defines a `counterReducer` to handle `INCREMENT` and `DECREMENT` actions, and then shows a `Counter` functional component that uses `useSelector` to access state and `useDispatch` to dispatch actions, demonstrating a typical Redux integration pattern. ```jsx // Redux example const counterReducer = (state = {count: 0}, action) => { switch (action.type) { case 'INCREMENT': return {count: state.count + 1}; case 'DECREMENT': return {count: state.count - 1}; default: return state; } } // Using Redux in component function Counter() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return (
{count}
); } ``` -------------------------------- ### Building a Next.js Docker Image - Bash Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This command builds a Docker image for a Next.js application, tagging it as 'Next.js-docker'. It compiles the application and its dependencies into a portable container image, ready for deployment on container orchestrators or cloud providers. ```bash docker build -t Next.js-docker. ``` -------------------------------- ### Compiling TypeScript Files - Example Source: https://github.com/kornerious/frontend-interview/blob/main/TypeScript.md This snippet demonstrates a basic TypeScript variable declaration and console logging. While the surrounding text explains how to compile a TypeScript file using the 'tsc' command, this code serves as a general TypeScript example. ```typescript const currentStatus: Status = 'active'; console.log(currentStatus); // active ``` -------------------------------- ### Installing ts-node and nodemon for Development Source: https://github.com/kornerious/frontend-interview/blob/main/TypeScript.md This command installs `ts-node` and `nodemon` as local development dependencies using npm. `ts-node` allows direct execution of TypeScript files, while `nodemon` automatically restarts the Node.js application on file changes, streamlining the development workflow. ```Shell npm install --save ts-node nodemon ``` -------------------------------- ### Understanding tsconfig.json - Example Source: https://github.com/kornerious/frontend-interview/blob/main/TypeScript.md This snippet provides a simple TypeScript variable declaration and logging. The context explains that the tsconfig.json file is used to specify compiler options for a TypeScript project, indicating the project root, with this code serving as a general TypeScript example. ```typescript const currentStatus: Status = 'active'; console.log(currentStatus); // active ``` -------------------------------- ### Implementing JavaScript Modules with Import/Export Source: https://github.com/kornerious/frontend-interview/blob/main/MyNotes.md Explains ES Modules, a standard for organizing and reusing JavaScript code through `import` and `export` statements, promoting modularity and maintainability. The example demonstrates exporting a function from one file and importing it into another for use. ```JavaScript // math.js export const add = (a, b) => a + b; // app.js import { add } from './math.js'; console.log(add(2, 3)); ``` -------------------------------- ### Examples of Native JavaScript Objects Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This snippet provides examples of native JavaScript objects, which are defined by the ECMAScript specification and are universally available in any JavaScript environment. These objects form the core building blocks of the language, ensuring consistent behavior across different runtimes. ```JavaScript // Native objects - available everywhere const arr = new Array(1, 2, 3); const date = new Date(); const regex = /[a-z]+/; const promise = new Promise((resolve) => resolve('done')); ``` -------------------------------- ### Navigating Next.js Project Directory (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md Changes the current working directory to the newly created Next.js project folder. The placeholder `your-project-name` should be replaced with the actual name provided during the project creation step. This step is essential before running development commands. ```Shell cd your-project-name ``` -------------------------------- ### Examples of HTML Templating Languages Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This snippet provides examples of two popular HTML templating languages: Handlebars and Pug. Handlebars uses a logic-less syntax with double curly braces for variables and block helpers, while Pug (formerly Jade) uses an indentation-based syntax for concise HTML generation, including conditional rendering. ```Handlebars

{{title}}

{{#if author}}

{{author.name}}

{{/if}}
``` ```Pug div.entry h1= title if author h2= author.name ``` -------------------------------- ### Configuring Environment-Specific CDN in Next.js Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This configuration allows for dynamic CDN usage based on the environment. In a production environment (`NODE_ENV === 'production'`), assets are served from `https://prod-cdn.example.com`, while in other environments, no prefix is applied. This enables different CDN strategies for development and production. ```javascript module.exports = { assetPrefix: process.env.NODE_ENV === 'production' ? 'https://prod-cdn.example.com' : '', } ``` -------------------------------- ### Implementing React Component Lifecycles with Class and Functional Components Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This snippet demonstrates how to manage component lifecycles in React using both class components and functional components with Hooks. The class component uses `componentDidMount` for setup and `componentWillUnmount` for cleanup, while the functional component achieves the same with the `useEffect` Hook. Both examples create a simple timer that updates every second. ```jsx // Class component lifecycle class Timer extends React.Component { constructor(props) { super(props); this.state = { seconds: 0 }; } componentDidMount() { this.timer = setInterval(() => this.setState(state => ({seconds: state.seconds + 1})), 1000); } componentWillUnmount() { clearInterval(this.timer); } render() { return
Seconds: {this.state.seconds}
; } } // Functional component with hooks function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const timer = setInterval(() => setSeconds(s => s + 1), 1000); return () => clearInterval(timer); }, []); return
Seconds: {seconds}
; } ``` -------------------------------- ### Navigating to Next.js Project Directory (Shell) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md After creating a new Next.js application, this command is used to change the current working directory to the newly created project folder, 'myapp'. This is a crucial step before running any development or build commands within the project. ```Shell cd myapp ``` -------------------------------- ### Implementing a Basic Music Player in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/Tasks.md This JavaScript snippet demonstrates the foundational structure for a music player application. It initializes an array of songs, sets up an `Audio` object, and attaches event listeners to UI elements like play, next, and previous buttons, as well as the progress bar. It includes placeholder functions for core functionalities like `playPause`, `nextSong`, `prevSong`, `loadSong`, and `updateProgressBar`, and handles progress bar seeking. ```JavaScript // script.js const songs = [ { title: "Song 1", author: "Artist 1", src: "song1.mp3", img: "cover1.jpg" }, { title: "Song 2", author: "Artist 2", src: "song2.mp3", img: "cover2.jpg" } ]; let currentSongIndex = 0; const audio = new Audio(songs[currentSongIndex].src); document.getElementById("playButton").addEventListener("click", playPause); document.getElementById("nextButton").addEventListener("click", nextSong); document.getElementById("prevButton").addEventListener("click", prevSong); audio.addEventListener("timeupdate", updateProgressBar); function playPause() { // Add pause button implementation } function nextSong() { // Add next button implementation } function prevSong() { // Add previous button implementation } function loadSong(index) { // Add load song implementation } function updateProgressBar() { // Handle when progress bar is updated } document.getElementById("progressBar").addEventListener("input", function () { audio.currentTime = (this.value / 100) * audio.duration; }); // Initial load loadSong(currentSongIndex); ``` -------------------------------- ### Setting Up Git Hooks with Husky (Shell Script) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This shell script snippet demonstrates a Husky Git hook, specifically a `pre-commit` hook. It executes `npm run lint-staged` before a commit is finalized, ensuring that staged files adhere to linting rules and maintaining code quality within the repository. ```shell // Git hooks (Husky) // .husky/pre-commit #!/bin/sh npm run lint-staged ``` -------------------------------- ### Correct Responsive Typography with SX Prop - JSX Source: https://github.com/kornerious/frontend-interview/blob/main/ResidentConvensions.md This example shows the recommended way to implement responsive `` components using the `sx` prop. The `sx` prop allows defining breakpoint-specific styles that are compiled into CSS during build time, which is particularly beneficial for Next.js projects and ensures consistent responsive patterns. ```jsx Hello World! ``` -------------------------------- ### Configuring Webpack Build Tool (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This JavaScript snippet demonstrates a basic Webpack configuration. It defines entry and output paths, specifies rules for processing JavaScript and SCSS files using Babel and style/css/sass loaders, includes an HTMLWebpackPlugin for template generation, and enables hot module replacement for the development server. ```javascript // Webpack configuration module.exports = { entry: './src/index.js', output: { path: path.resolve('dist'), filename: 'bundle.[hash].js' }, module: { rules: [ { test: /\.js$/, use: 'babel-loader' }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] } ] }, plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })], devServer: { hot: true } }; ``` -------------------------------- ### Optimizing Critical Rendering Path with HTML Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This HTML snippet demonstrates techniques to optimize the critical rendering path. It includes resource hints like preconnect and preload for early resource fetching, inline critical CSS to prevent render-blocking, and deferred loading of non-essential stylesheets and scripts to improve initial page render speed. ```HTML > ``` -------------------------------- ### Configuring CORS in Express.js (JavaScript) Source: https://github.com/kornerious/frontend-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 to access resources, and only for `GET` and `POST` HTTP methods. ```javascript // CORS configuration (Express) app.use(cors({ origin: 'https://allowed-site.com', methods: ['GET', 'POST'] })); ``` -------------------------------- ### Configuring Webpack Entry Point for Brand-Specific Builds - JSX Source: https://github.com/kornerious/frontend-interview/blob/main/ResidentConvensions.md This Webpack configuration snippet defines the entry point for the application. It dynamically sets the `app` entry to a specific `init.js` file within a brand's directory, determined by the `PROJECT_DIR` variable. This allows Webpack to build different brand projects from their respective initialization files. ```JSX entry: { app: `./app/react/${PROJECT_DIR}/init.js`, }, ``` -------------------------------- ### Implementing a Multi-Step Form in Vanilla JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/Tasks.md This JavaScript snippet outlines the basic structure for a multi-step registration form. It initializes a 'currentStep' variable, defines placeholder functions for 'showStep', 'nextStep', and '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); ``` -------------------------------- ### Defining Custom HTTP Headers in next.config.js (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This example illustrates how to use the `headers` property in `next.config.js` to define custom HTTP headers for responses served by your Next.js application. This feature is useful for setting caching policies, security-related headers, or other custom headers to control client-browser interactions. ```JavaScript // next.config.js module.exports = { async headers() { return [ { source: '/path/:slug', headers: [ { key: 'Custom-Header', value: 'Custom-Header-Value', }, { key: 'Cache-Control', value: 'public, max-age=3600', } ] } ] }, // other configurations... } ``` -------------------------------- ### Demonstrating Prototypal Inheritance in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md Details prototypal inheritance, where objects inherit properties and methods from their prototype objects via a chain. It illustrates how JavaScript resolves property lookups by traversing this prototype chain, showing an example of a `Dog` constructor inheriting from an `Animal` constructor and overriding a method. ```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(); // "Rex barks" ``` -------------------------------- ### Enhancing String Handling with JavaScript Template Literals Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example illustrates the capabilities of template literals in JavaScript, which use backticks (`). It demonstrates string interpolation for embedding expressions, the creation of multi-line strings without explicit escape characters, and the ability to embed complex expressions directly within strings. ```javascript // String interpolation const name = 'World'; console.log(`Hello, ${name}!`); // 'Hello, World!' // Multi-line strings const multiLine = `This is line one. This is line two. This is line three.`; // Embedded expressions const a = 5, b = 10; console.log(`Sum: ${a + b}, Product: ${a * b}`); ``` -------------------------------- ### Implementing Event Delegation in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md Explains event delegation as a pattern where a single event listener on a parent element manages events for its children, improving memory efficiency and supporting dynamically added elements. The example demonstrates listening for clicks on a `
    ` to detect clicks on `
  • ` children using `e.target.matches()`. ```javascript document.querySelector('ul').addEventListener('click', e => { if (e.target.matches('li')) { console.log('List item clicked:', e.target.textContent); } }); ``` -------------------------------- ### Creating a Simple API Route in Next.js (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This code defines an API route in Next.js by placing `hello.js` in the `pages/api` directory. This file becomes an API endpoint accessible at `/api/hello`. The `handler` function processes incoming requests (`req`) and sends a JSON response (`res`) with a 'Hello, world!' message, demonstrating server-side logic within Next.js. ```javascript // pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello, world!' }); } ``` -------------------------------- ### Implementing CSRF Protection with Tokens (HTML/JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterview.md This example shows two methods for preventing Cross-Site Request Forgery (CSRF) attacks: including a hidden anti-CSRF token in an HTML form and sending it via an `X-CSRF-Token` header in an AJAX `fetch` request. The `credentials: 'same-origin'` option ensures cookies are sent only for same-origin requests. ```html
    ``` ```javascript ``` -------------------------------- ### Example HTTP Request with Conditional Headers Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This HTTP snippet illustrates a GET request utilizing conditional headers, specifically `If-Modified-Since` and `If-None-Match`. These headers are used by the client to ask the server to send the resource only if it has been modified since the specified date or if its ETag does not match the provided value, optimizing bandwidth by leveraging client-side caching. ```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 Advanced Theming with MUI createTheme (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/MyNotes.md Illustrates how to use `createTheme` from `@mui/material/styles` to define a custom theme in MUI v6. This example shows overriding the primary palette color and applying specific style overrides to the `MuiButton` component, such as `borderRadius` and `textTransform`. ```JavaScript import { createTheme } from '@mui/material/styles'; const theme = createTheme({ palette: { primary: { main: '#1976d2', }, }, components: { MuiButton: { styleOverrides: { root: { borderRadius: '12px', textTransform: 'none', }, }, }, }, }); ``` -------------------------------- ### Configuring Basic CDN with Next.js assetPrefix Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This snippet demonstrates the basic configuration for integrating a CDN with a Next.js application. By setting the `assetPrefix` property in `next.config.js` to the CDN's base URL, all static assets will be served from the specified CDN, improving load times and reducing server load. ```javascript module.exports = { // Set assetPrefix to the base URL of your CDN assetPrefix: 'https://cdn.example.com', } ``` -------------------------------- ### Initializing Speech Recognition and Synthesis APIs - JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/Tasks.md This snippet initializes the Speech Recognition API for converting speech to text and the Speech Synthesis API for converting text to speech. These are fundamental objects required for interacting with the browser's speech capabilities. ```JavaScript // Speech Recognition API const recognition = new SpeechRecognition(); // Speech Synthesis API const synthesis = window.speechSynthesis; ``` -------------------------------- ### Configuring ESLint for JavaScript/TypeScript Projects Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md Provides an example '.eslintrc.js' configuration file for ESLint. It sets up environment, extends recommended rules, configures parser options for React and TypeScript, and defines custom rules for console logs and prop types, ensuring consistent code quality. ```JavaScript module.exports = { root: true, env: { browser: true, node: true, es2022: true, }, extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/recommended', 'prettier' // Disables rules that conflict with Prettier ], parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 'latest', sourceType: 'module' }, plugins: ['react', '@typescript-eslint', 'import'], rules: { // Custom rules 'no-console': ['warn', { allow: ['warn', 'error'] }], 'react/react-in-jsx-scope': 'off', // Not needed in React 17+ 'react/prop-types': 'off', // Use TypeScript for prop validation 'import/order': ['error', { groups: ['builtin', 'external', 'internal'] }] }, settings: { react: { version: 'detect' } } }; ``` -------------------------------- ### Implementing a Responsive Layout with CSS Grid Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This example demonstrates how to create a flexible and responsive layout using CSS Grid. It defines a 12-column grid with a gap and assigns specific column spans to elements like `main-content` and `sidebar`, showcasing the power of CSS Grid for two-dimensional layouts. ```css /* CSS Grid example */ .container { display: grid; grid-template-columns: repeat(12, 1fr); gap: 20px; } .main-content { grid-column: span 8; } .sidebar { grid-column: span 4; } ``` -------------------------------- ### Creating a Static Home Route in Next.js (JavaScript) Source: https://github.com/kornerious/frontend-interview/blob/main/Next.md This snippet demonstrates how to create a static route in Next.js by defining a component in `pages/index.js`. This file automatically maps to the root URL (`/`), rendering a simple 'Home Page' div. It serves as the default entry point for the application. ```javascript // pages/index.js const Home = () => { return (
    Home Page
    ); } export default Home; ``` -------------------------------- ### Verifying TypeScript Installation Source: https://github.com/kornerious/frontend-interview/blob/main/TypeScript.md This command checks the installed version of the TypeScript compiler (`tsc`). It's used to confirm that TypeScript has been successfully installed and is accessible in your command-line environment. ```shell tsc --version ``` -------------------------------- ### Implementing Progressive Rendering Techniques in HTML Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This snippet illustrates two progressive rendering techniques: lazy loading images using the 'loading='lazy'' attribute to defer offscreen image loading, and asynchronously loading non-critical CSS using '' combined with 'onload' to prevent render-blocking. ```HTML Description ``` ```HTML ``` -------------------------------- ### Basic TypeScript Example for JSX Modes Source: https://github.com/kornerious/frontend-interview/blob/main/TypeScript.md This snippet provides a generic TypeScript example, appearing in the context of a question about various JSX modes supported by TypeScript (e.g., preserve, react, react-jsx). While the code is a basic variable assignment, it is presented as an example within the discussion of how JSX expressions are compiled. ```TypeScript const currentStatus: Status = 'active'; console.log(currentStatus); // active ``` -------------------------------- ### Styling with CSS Pseudo-elements Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This example demonstrates the use of CSS pseudo-elements to style specific parts of an element without altering the HTML structure. It shows how `::before` can add decorative content, `::first-letter` can style the initial character of text, and `::selection` can customize the appearance of selected text. ```css /* Add a quote mark before blockquotes */ blockquote::before { content: '"'; font-size: 2em; color: #ccc; } /* Style the first letter of paragraphs */ p::first-letter { font-size: 2em; float: left; margin-right: 5px; } /* Style text selection */ ::selection { background-color: #ffb7b7; color: #333; } ``` -------------------------------- ### Explicit Type Annotation Example for `noImplicitAny` in TypeScript Source: https://github.com/kornerious/frontend-interview/blob/main/TypeScript.md This snippet provides a simple example of explicit type annotation in TypeScript. It declares a variable `example` with a `string` type and assigns it a value. This code demonstrates a scenario where `noImplicitAny` would not trigger an error because the type is explicitly defined, contrasting with cases where `any` might be implicitly inferred. ```typescript let example: string = 'TypeScript example'; console.log(example); ``` -------------------------------- ### Monitoring Page Load Events and Performance in JavaScript Source: https://github.com/kornerious/frontend-interview/blob/main/FrontInterviewJob.md This JavaScript code demonstrates how to monitor key events during the web page loading process using `readystatechange`, `DOMContentLoaded`, and `load` event listeners. It also shows how to access and log basic performance timing metrics using the `performance.timing` API to understand different phases of page load. ```JavaScript // Example of events during page load document.addEventListener('readystatechange', function() { console.log(`Document ready state: ${document.readyState}`); }); document.addEventListener('DOMContentLoaded', function() { console.log('DOM fully loaded and parsed'); // Start interacting with the DOM here }); window.addEventListener('load', function() { console.log('Window loaded with all resources'); // Page is fully loaded // Performance metrics const timing = performance.timing; console.log(`DNS lookup: ${timing.domainLookupEnd - timing.domainLookupStart}ms`); console.log(`TCP connection: ${timing.connectEnd - timing.connectStart}ms`); console.log(`DOM interactive: ${timing.domInteractive - timing.navigationStart}ms`); console.log(`DOM complete: ${timing.domComplete - timing.navigationStart}ms`); }); ``` -------------------------------- ### GitHub Actions CI Workflow for Frontend - YAML Source: https://github.com/kornerious/frontend-interview/blob/main/MyNotes.md This YAML snippet defines a GitHub Actions workflow that triggers on push and pull requests. It sets up a Node.js environment, installs dependencies, runs linting, and executes tests, ensuring code quality and functionality before deployment. ```YAML name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18 - run: npm ci - run: npm run lint - run: npm test ```