├── .commitlintrc.json ├── .eslintrc.json ├── .github ├── dependabot.yml ├── pull_request_template.md └── workflows │ ├── main-version.yml │ ├── pull-request-test.yml │ └── tag-deploy.yml ├── .gitignore ├── .husky ├── commit-msg └── pre-commit ├── .prettierrc ├── .releaserc ├── .vitepress └── config.mts ├── .yarn └── releases │ └── yarn-4.1.1.cjs ├── .yarnrc.yml ├── CHANGELOG.md ├── CNAME ├── CONTRIBUTING.md ├── README.md ├── docs ├── about │ ├── changelog.md │ ├── contributing.md │ └── index.md ├── index.md ├── javascript │ ├── arrays.md │ ├── classes.md │ ├── functions.md │ ├── index.md │ ├── loops.md │ ├── maps-and-sets.md │ ├── objects.md │ ├── soon.md │ └── variables.md ├── react │ ├── advanced.md │ ├── components.md │ ├── hooks.md │ └── index.md └── typescript │ └── index.md ├── navigation ├── nav-items.ts ├── sidebar.ts └── social-links.ts ├── package.json └── yarn.lock /.commitlintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["@commitlint/config-conventional"], 3 | "rules": {} 4 | } 5 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "env": { 4 | "browser": true, 5 | "es2021": true 6 | }, 7 | "extends": [ 8 | "eslint:recommended", 9 | "plugin:@typescript-eslint/recommended", 10 | "plugin:prettier/recommended" 11 | ], 12 | "ignorePatterns": [ 13 | "dist", 14 | ".eslintrc.cjs" 15 | ], 16 | "parser": "@typescript-eslint/parser", 17 | "rules": {}, 18 | "reportUnusedDisableDirectives": true 19 | } 20 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | 4 | 5 | ## Related Issue 6 | 7 | 8 | 9 | ## Checklist 10 | 11 | - [ ] I have read the [Contribution Guidelines](../docs/about/contributing.md). 12 | - [ ] I have followed the steps mentioned in the Contribution Guidelines for making my contributions. 13 | - [ ] My code follows the project's coding standards. 14 | - [ ] I have tested my changes locally. 15 | - [ ] Title and commit messages are based on [conventional commits](../docs/about/contributing.md#using-conventional-commits). 16 | - [ ] I have added a new [question](../docs/about/contributing.md#adding-a-new-question) to the repository, if applicable. 17 | - [ ] I have updated the existing question, if applicable. 18 | - [ ] I have added a new [topic page](../docs/about/contributing.md#adding-a-new-topic), if applicable. 19 | - [ ] I have added a new [category directory](../docs/about/contributing.md#adding-a-new-category), if applicable. 20 | - [ ] I have updated the [sidebar](../navigation/sidebar.ts), if applicable. 21 | -------------------------------------------------------------------------------- /.github/workflows/main-version.yml: -------------------------------------------------------------------------------- 1 | name: Version 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | workflow_dispatch: 7 | 8 | concurrency: 9 | group: version 10 | cancel-in-progress: false 11 | 12 | jobs: 13 | version: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout Code 17 | uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | 21 | - name: Setup Node 22 | uses: actions/setup-node@v4 23 | with: 24 | node-version: 20 25 | cache: 'yarn' 26 | 27 | - name: Install Dependencies 28 | run: yarn install --immutable 29 | 30 | - name: Lint Code 31 | run: yarn lint 32 | 33 | - name: Build 34 | run: yarn build 35 | 36 | - name: Version 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | HUSKY: 0 40 | run: npx semantic-release 41 | -------------------------------------------------------------------------------- /.github/workflows/pull-request-test.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Test 2 | on: pull_request 3 | 4 | jobs: 5 | lint_and_test: 6 | name: Lint and Test 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout Code 10 | uses: actions/checkout@v4 11 | 12 | - name: Setup Node 13 | uses: actions/setup-node@v4 14 | with: 15 | node-version: 20 16 | cache: 'yarn' 17 | 18 | - name: Install Dependencies 19 | run: yarn install --immutable 20 | 21 | - name: Lint Code 22 | run: yarn lint 23 | 24 | - name: Build 25 | run: yarn build 26 | -------------------------------------------------------------------------------- /.github/workflows/tag-deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | permissions: 9 | contents: read 10 | pages: write 11 | id-token: write 12 | 13 | concurrency: 14 | group: pages 15 | cancel-in-progress: false 16 | 17 | jobs: 18 | build: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Checkout Code 22 | uses: actions/checkout@v4 23 | with: 24 | fetch-depth: 0 25 | 26 | - name: Setup Node 27 | uses: actions/setup-node@v4 28 | with: 29 | node-version: 20 30 | cache: 'yarn' 31 | 32 | - name: Install Dependencies 33 | run: yarn install --immutable 34 | 35 | - name: Lint Code 36 | run: yarn lint 37 | 38 | - name: Build 39 | run: yarn build 40 | 41 | - name: Upload artifact 42 | uses: actions/upload-pages-artifact@v3 43 | with: 44 | path: dist 45 | 46 | deploy: 47 | environment: 48 | name: github-pages 49 | url: ${{ steps.deployment.outputs.page_url }} 50 | needs: build 51 | runs-on: ubuntu-latest 52 | name: Deploy 53 | steps: 54 | - name: Deploy to GitHub Pages 55 | id: deployment 56 | uses: actions/deploy-pages@v4 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # dist 12 | dist 13 | 14 | # misc 15 | .DS_Store 16 | *.pem 17 | 18 | # debug 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | .pnpm-debug.log* 23 | 24 | # local env files 25 | .env*.local 26 | .env.development 27 | .env.production 28 | 29 | # vercel 30 | .vercel 31 | 32 | # typescript 33 | *.tsbuildinfo 34 | next-env.d.ts 35 | 36 | # ide 37 | .idea 38 | 39 | # yarn 40 | .pnp.* 41 | .yarn/* 42 | !.yarn/patches 43 | !.yarn/plugins 44 | !.yarn/releases 45 | !.yarn/sdks 46 | !.yarn/versions 47 | 48 | # cache 49 | .vitepress/cache 50 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx --no -- commitlint --edit $1 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | yarn lint 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "arrowParens": "avoid", 4 | "singleQuote": true, 5 | "printWidth": 80, 6 | "useTabs": true, 7 | "trailingComma": "all" 8 | } 9 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "branches": [ 3 | "main" 4 | ], 5 | "repositoryUrl": "https://github.com/armancodv/frontend-interview.git", 6 | "plugins": [ 7 | [ 8 | "@semantic-release/commit-analyzer", 9 | { 10 | "preset": "conventionalcommits" 11 | } 12 | ], 13 | "@semantic-release/release-notes-generator", 14 | "@semantic-release/changelog", 15 | "@semantic-release/git", 16 | "@semantic-release/github" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /.vitepress/config.mts: -------------------------------------------------------------------------------- 1 | import {defineConfig} from 'vitepress' 2 | import {navItems} from "../navigation/nav-items"; 3 | import {sidebar} from "../navigation/sidebar"; 4 | import {socialLinks} from "../navigation/social-links"; 5 | 6 | // https://vitepress.dev/reference/site-config 7 | export default defineConfig({ 8 | title: "Frontend Interview Questions", 9 | description: "List of frontend interview questions", 10 | base: '/', 11 | srcDir: 'docs', 12 | outDir: 'dist', 13 | ignoreDeadLinks: true, 14 | themeConfig: { 15 | nav: navItems, 16 | sidebar: sidebar, 17 | socialLinks: socialLinks, 18 | search: {provider: 'local'}, 19 | editLink: { 20 | pattern: 'https://github.com/armancodv/frontend-interview/edit/main/docs/:path', 21 | text: 'Edit this page on GitHub' 22 | }, 23 | lastUpdated: { 24 | text: 'Updated at', 25 | formatOptions: { 26 | dateStyle: 'full', 27 | } 28 | }, 29 | }, 30 | sitemap: { 31 | hostname: 'https://interview.armanko.com/', 32 | }, 33 | markdown: { 34 | container: { 35 | tipLabel: 'Key Notes', 36 | warningLabel: 'Hint', 37 | } 38 | } 39 | }) 40 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | yarnPath: .yarn/releases/yarn-4.1.1.cjs 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [1.3.0](https://github.com/armancodv/frontend-interview/compare/v1.2.0...v1.3.0) (2024-04-15) 2 | 3 | 4 | ### Features 5 | 6 | * add javascript arrays and functions questions and answers ([1c59b1f](https://github.com/armancodv/frontend-interview/commit/1c59b1fefb72a768cf1fcef9975e8116d25744ce)) 7 | 8 | # [1.2.0](https://github.com/armancodv/frontend-interview/compare/v1.1.0...v1.2.0) (2024-04-13) 9 | 10 | 11 | ### Features 12 | 13 | * add numbering to react home page ([15710b0](https://github.com/armancodv/frontend-interview/commit/15710b0894093233b2df55265296a3c88f5a97ea)) 14 | 15 | # [1.1.0](https://github.com/armancodv/frontend-interview/compare/v1.0.0...v1.1.0) (2024-04-13) 16 | 17 | 18 | ### Features 19 | 20 | * add change log ([ed76175](https://github.com/armancodv/frontend-interview/commit/ed76175aeafdb00bdf6841a50a5796dd0bf1be39)) 21 | 22 | # 1.0.0 (2024-04-13) 23 | 24 | 25 | ### Bug Fixes 26 | 27 | * ignore dead links ([3b4b45a](https://github.com/armancodv/frontend-interview/commit/3b4b45a7309e6751cad63e28c84d3457358fbabe)) 28 | 29 | 30 | ### Features 31 | 32 | * arrays questions and answers ([3f25330](https://github.com/armancodv/frontend-interview/commit/3f2533001138585f82682d6895efe10d2a061432)) 33 | * home content ([1e73f91](https://github.com/armancodv/frontend-interview/commit/1e73f91933ebddcd8d1bc0a2de31dff9399f46ee)) 34 | * javascript ([edcd7e2](https://github.com/armancodv/frontend-interview/commit/edcd7e2e9c6687df757793a9204d232e8a02f6be)) 35 | * react advanced ([bae1e9f](https://github.com/armancodv/frontend-interview/commit/bae1e9f613ed5279c1ec82988118211260f10929)) 36 | * react components ([56f6e8c](https://github.com/armancodv/frontend-interview/commit/56f6e8c78522c51854008c50d3199f8f9df2846f)) 37 | * react hooks ([de17e2b](https://github.com/armancodv/frontend-interview/commit/de17e2b44f12dd09da6e8f85c94e9cda1a05be44)) 38 | * react introduction ([e046e25](https://github.com/armancodv/frontend-interview/commit/e046e254fd8f0a901a50d6af7fe300bb35db7e88)) 39 | * update javascript questions, add objects, classes, maps and sets ([47470a9](https://github.com/armancodv/frontend-interview/commit/47470a945934ba664ea091e39d88f91d5197fa77)) 40 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | interview.armanko.com -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Welcome to the **Frontend Interview** repository! We appreciate your interest in contributing to our project. Please take a moment to review the following guidelines before making contributions. 4 | 5 | ## How to Contribute 6 | 7 | 1. **Fork the repository to your GitHub account.** 8 | - You can fork the repository by clicking the **Fork** button located at the top right corner of the [repository page](https://github.com/armancodv/frontend-interview). 9 | 10 | 2. **Clone the forked repository to your local machine:** 11 | ```bash 12 | git clone https://github.com/[your-username]/frontend-interview.git 13 | ``` 14 | - Replace `[your-username]` with your GitHub username. 15 | 16 | 3. **Install the project dependencies:** 17 | ```bash 18 | yarn install 19 | ``` 20 | - If you don't have Yarn installed, you can download it [here](https://yarnpkg.com/). 21 | 22 | 4. **Create a new branch for your contribution:** 23 | ```bash 24 | git checkout -b [feature-branch] 25 | ``` 26 | - Replace `[feature-branch]` with a descriptive branch name reflecting the changes you plan to make. 27 | 28 | 5. **Make your changes and test them locally.** 29 | - Start the development server with: 30 | ```bash 31 | yarn dev 32 | ``` 33 | - Open [http://localhost:5173/](http://localhost:5173/) in your browser to see the result. 34 | 35 | 6. **Run the linter and fix any issues:** 36 | ```bash 37 | yarn lint 38 | ``` 39 | 40 | 7. **Commit your changes:** 41 | ```bash 42 | git add . 43 | git commit -m "feat: Add a concise commit message describing your changes" 44 | ``` 45 | - Please use conventional commit messages. You can find more information about conventional commits [here](#using-conventional-commits). 46 | 47 | 8. **Push the changes to your forked repository:** 48 | ```bash 49 | git push origin [feature-branch] 50 | ``` 51 | - Replace `[feature-branch]` with a descriptive branch name reflecting the changes you plan to make. 52 | 53 | 9. **Open a pull request on the [main repository](https://github.com/armancodv/frontend-interview/compare) from your feature branch on your forked repository.** 54 | - Provide a clear title and description for your pull request. 55 | - Include the related issue number in the PR description. 56 | - Utilize the PR template for your PR. 57 | 58 | ## Adding a New Question 59 | 60 | To add a new question to the repository, follow these steps: 61 | 62 | 1. Navigate to the `docs` directory. 63 | 2. Find the appropriate category for your question. 64 | 3. Add a new question at the end of the file in the following format: 65 | ```markdown 66 | ## Question Title 67 | 68 | Answer to the question. 69 | 70 | 71 | ::: tip 72 | - Key point 1 73 | - Key point 2 74 | ::: 75 | ``` 76 | You can use the `tip` block to provide additional information or key points related to the question. 77 | Refer to the markdown guide [here](https://vitepress.dev/guide/markdown). 78 | 79 | ## Adding a New Topic 80 | 81 | To add a new topic to the repository, follow these steps: 82 | 83 | 1. Navigate to the `docs` directory. 84 | 2. Create a new markdown file with the name of the topic in the appropriate directory. 85 | 3. Fill the file with content in the following format: 86 | ```markdown 87 | # Topic Title 88 | 89 | Introduction to the topic. 90 | 91 | ## Question Title 92 | 93 | Answer to the question. 94 | 95 | 96 | ::: tip 97 | - Key point 1 98 | - Key point 2 99 | ::: 100 | ``` 101 | 102 | 4. Add the path to the new file in the [navigation/sidebar.ts](https://github.com/armancodv/frontend-interview/blob/main/navigation/sidebar.ts) configuration. 103 | 104 | ## Adding a New Category 105 | 106 | To add a new category to the repository, follow these steps: 107 | 108 | 1. Navigate to the `docs` directory. 109 | 2. Create a new directory with the name of the category. 110 | 3. Inside the new directory, create a markdown file named `index.md`. 111 | 4. Fill the `index.md` file with content similar to [Adding a New Topic](#adding-a-new-topic). 112 | 113 | ## Issues 114 | 115 | If you encounter any issues or have suggestions for improvement, please don't hesitate to report them [here](https://github.com/armancodv/frontend-interview/issues/new). 116 | 117 | Please use the issue template to report the issue. This helps us understand the problem and resolve it quickly. 118 | 119 | Before creating a new issue, please check the existing ones [here](https://github.com/armancodv/frontend-interview/issues) to avoid duplicates. 120 | 121 | ## New Features 122 | 123 | If you plan to work on a new feature, please open an issue beforehand to discuss the feature and get feedback from the maintainers and the community. This ensures that your contribution aligns with the project's goals and avoids duplication of efforts. 124 | 125 | ## Tech Stack 126 | 127 | The project is built using the following technologies: 128 | 129 | - [VitePress](https://vitepress.dev/) 130 | - [Markdown](https://vitepress.dev/guide/markdown) 131 | - [TypeScript](https://www.typescriptlang.org/) 132 | - [EsLint](https://eslint.org/) 133 | - [Prettier](https://prettier.io/) 134 | - [Yarn](https://yarnpkg.com/) 135 | 136 | ## Using Conventional Commits 137 | 138 | Conventional commits provide a structured way to format commit messages, making it easier to understand the purpose of each commit at a glance. Below is a breakdown of different conventional commit types and their meanings: 139 | 140 | | Type | Description | 141 | |----------|-----------------------------------------------------------------------------------------------| 142 | | feat | Represents the addition of a new feature. | 143 | | fix | Indicates a bug fix. | 144 | | docs | Pertains to documentation changes. | 145 | | style | Covers changes in code formatting, whitespace, or semicolons, without affecting code meaning. | 146 | | refactor | Denotes code refactoring that neither fixes a bug nor adds a feature. | 147 | | perf | Signifies performance improvements. | 148 | | test | Involves adding or correcting tests. | 149 | | build | Relates to changes affecting the build system or external dependencies. | 150 | | ci | Involves changes to Continuous Integration configuration files and scripts. | 151 | | chore | Encompasses other changes that don't modify source or test files. | 152 | | revert | Reverts a previous commit. | 153 | 154 | When using conventional commits, it's essential to structure commit messages in a specific format. Here's an example of a conventional commit message: 155 | 156 | ``` 157 | feat: add user authentication functionality 158 | ``` 159 | 160 | In this example: 161 | - `feat` represents the type of commit, which is adding a new feature. 162 | - The message following the colon describes the feature added in a concise and descriptive manner. 163 | 164 | By following the conventional commit format, it becomes easier to manage and track changes within a project, enhancing collaboration and communication among contributors. 165 | 166 | For more information, refer to the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification. 167 | 168 | ## Thank You 169 | 170 | Thank you for contributing to this project! Your contributions are invaluable, and they help make this project better for everyone. 🚀 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Frontend Interview Questions 2 | 3 | Welcome to the Frontend Interview Questions repository! This repository aims to provide a comprehensive list of frontend interview questions to help you prepare for your next interview. 4 | 5 | ## Live Documentation 6 | 7 | You can explore the live documentation here: 8 | 9 | [Frontend Interview Questions](https://interview.armanko.com/) 10 | 11 | ## Issues 12 | 13 | If you encounter any issues or have suggestions for improvement, please don't hesitate to report them [here](https://github.com/armancodv/frontend-interview/issues/new). 14 | 15 | > Your contributions are invaluable! Feel free to contribute by creating a pull request for any reported issues or suggested enhancements. 16 | 17 | > Before creating a new issue, please check the existing ones [here](https://github.com/armancodv/frontend-interview/issues) to avoid duplicates. 18 | 19 | ## Feedback 20 | 21 | If you find this project helpful, consider showing your support by starring the repository. Your support motivates us to enhance and expand this project further. ❤️ 22 | 23 | ## Contributing 24 | 25 | We welcome contributions from everyone! Check out [contributing page](https://interview.armanko.com/about/contributing.html) to learn how you can contribute. 26 | 27 | Alternatively, you can find the contributing guidelines [here](docs/about/contributing.md) 28 | 29 | ## Run Locally 30 | 31 | To run this project locally, follow these simple steps: 32 | 33 | 1. Clone the project: 34 | 35 | ```bash 36 | git clone https://github.com/armancodv/frontend-interview.git 37 | ``` 38 | 39 | 2. Navigate to the project directory: 40 | 41 | ```bash 42 | cd frontend-interview 43 | ``` 44 | 45 | 3. Install dependencies: 46 | 47 | ```bash 48 | yarn install 49 | ``` 50 | 51 | > If you don't have Yarn installed, you can download it [here](https://yarnpkg.com/). 52 | 53 | 4. Start the server: 54 | 55 | ```bash 56 | yarn dev 57 | ``` 58 | 59 | 5. Open [http://localhost:5173/](http://localhost:5173/) in your browser to see the result. 60 | 61 | ## License 62 | 63 | This project is licensed under the [MIT License](https://choosealicense.com/licenses/mit/). 64 | -------------------------------------------------------------------------------- /docs/about/changelog.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/about/contributing.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/about/index.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | # https://vitepress.dev/reference/default-theme-home-page 3 | layout: home 4 | 5 | hero: 6 | name: "Frontend Interview" 7 | text: "List of frontend interview questions" 8 | tagline: Javascript, Typescript, React, and more 9 | actions: 10 | - theme: brand 11 | text: React 12 | link: /react/ 13 | - theme: alt 14 | text: Javascript 15 | link: /javascript/ 16 | - theme: alt 17 | text: Typescript 18 | link: /typescript/ 19 | 20 | features: 21 | - title: Comprehensive list of questions 22 | details: You can find questions on Javascript, Typescript, React, and more 23 | - title: Simple answers 24 | details: Answers are simple and easy to understand for every level of experience 25 | - title: Open source 26 | details: You can edit the answers and contribute to this project on Github 27 | --- 28 | 29 | -------------------------------------------------------------------------------- /docs/javascript/classes.md: -------------------------------------------------------------------------------- 1 | # Classes 2 | 3 | ## 1. What is Class in JavaScript? 4 | 5 | In JavaScript, a class is like a blueprint or a template for creating objects. It helps organize and structure code by defining the properties and behaviors that objects of that class will have. Think of it as a set of instructions for making objects with similar characteristics. Here's a simple example of a class in JavaScript: 6 | 7 | ```javascript 8 | class Animal { 9 | constructor(name, age) { 10 | this.name = name; 11 | this.age = age; 12 | } 13 | 14 | speak() { 15 | console.log(`${this.name} makes a sound.`); 16 | } 17 | } 18 | 19 | // Creating an object of the Animal class 20 | const myAnimal = new Animal("Dog", 3); 21 | 22 | // Accessing properties and calling methods of the object 23 | console.log(myAnimal.name); // Output: Dog 24 | console.log(myAnimal.age); // Output: 3 25 | myAnimal.speak(); // Output: Dog makes a sound. 26 | ``` 27 | 28 | In this example, the `Animal` class has properties `name` and `age`, and a method `speak()`. We create an object `myAnimal` from this class and can access its properties and call its methods. 29 | 30 | ::: tip 31 | - A class in JavaScript is like a blueprint for creating objects. 32 | - It defines the properties and behaviors that objects of that class will have. 33 | ::: 34 | 35 | ## 2. What are the differences between objects and classes in JavaScript? 36 | 37 | In JavaScript, objects and classes are both used to create reusable code, but they work a bit differently. An object is like a container that holds data and functions related to that data. You can think of it as a single thing with properties and behaviors. Here's a simple example of creating an object: 38 | 39 | ```javascript 40 | let car = { 41 | brand: "Toyota", 42 | model: "Corolla", 43 | year: 2022, 44 | start: function() { 45 | console.log("Engine started!"); 46 | } 47 | }; 48 | ``` 49 | 50 | On the other hand, a class is like a blueprint for creating objects. It defines the properties and behaviors that objects created from it will have. Think of a class as a template for creating objects of the same type. Here's a simple example of defining a class and creating objects from it: 51 | 52 | ```javascript 53 | class Car { 54 | constructor(brand, model, year) { 55 | this.brand = brand; 56 | this.model = model; 57 | this.year = year; 58 | } 59 | 60 | start() { 61 | console.log("Engine started!"); 62 | } 63 | } 64 | 65 | let myCar = new Car("Toyota", "Corolla", 2022); 66 | ``` 67 | 68 | So, the main difference is that objects are created directly, while classes are used as blueprints for creating objects. 69 | 70 | ::: tip 71 | - An object is like a single thing with properties and behaviors. 72 | - A class is a blueprint for creating objects with similar properties and behaviors. 73 | - Objects are created directly, while classes are used to create objects. 74 | ::: 75 | 76 | ## 3. How to get the class name of an object in JavaScript? 77 | 78 | In JavaScript, you can get the class name of an object by using the `constructor.name` property. This property returns the name of the constructor function that created the object. Here's a simple example: 79 | 80 | ```javascript 81 | class MyClass { 82 | constructor() { 83 | // constructor code 84 | } 85 | } 86 | 87 | const obj = new MyClass(); 88 | console.log(obj.constructor.name); // Output: "MyClass" 89 | ``` 90 | 91 | In this example, `obj.constructor.name` will return `"MyClass"`, which is the name of the class used to create the `obj` object. 92 | 93 | ::: tip 94 | - You can get the class name of an object in JavaScript using the `constructor.name` property. 95 | ::: 96 | 97 | ## 4. What is constructor in JavaScript? 98 | 99 | In JavaScript, a constructor is like a blueprint for creating objects of a certain type. It's typically defined within a class. When you create a new object using this blueprint, the constructor function is automatically called to initialize the object's properties and methods. It's like a special function that runs when you make a new instance of an object. Here's a simple example: 100 | 101 | ```javascript 102 | // Define a class 103 | class Person { 104 | constructor(name, age) { // Constructor function 105 | this.name = name; 106 | this.age = age; 107 | } 108 | } 109 | 110 | // Create a new object using the constructor 111 | let person1 = new Person('John', 30); 112 | 113 | // Now person1 has properties name and age initialized 114 | console.log(person1.name); // Output: John 115 | console.log(person1.age); // Output: 30 116 | ``` 117 | 118 | ::: tip 119 | - A constructor in JavaScript is a special function that initializes objects created from a class. 120 | - It's defined within a class and is automatically called when a new object is created. 121 | - The constructor function sets up the initial state of the object by assigning values to its properties. 122 | ::: 123 | 124 | ## 5. What is a static property or method in JavaScript? 125 | 126 | In JavaScript, a static property or method is a property or method that belongs to the class itself rather than to instances of the class. This means that you can access static properties or methods without creating an object from the class. They are shared among all instances of the class. Here's a simple example in JavaScript: 127 | 128 | ```javascript 129 | class MyClass { 130 | static myStaticProperty = 'Hello'; 131 | 132 | static myStaticMethod() { 133 | return 'World'; 134 | } 135 | } 136 | 137 | console.log(MyClass.myStaticProperty); // Output: Hello 138 | console.log(MyClass.myStaticMethod()); // Output: World 139 | ``` 140 | 141 | In this example, `myStaticProperty` is a static property and `myStaticMethod` is a static method of the `MyClass` class. They can be accessed directly using the class name without creating an instance of the class. 142 | 143 | ::: tip 144 | - A static property or method in JavaScript belongs to the class itself, not to instances of the class. 145 | - They are shared among all instances of the class. 146 | - You can access static properties or methods using the class name without creating an object. 147 | ::: 148 | 149 | ## 6. What is extending a class in JavaScript? 150 | 151 | Extending a class in JavaScript means creating a new class that inherits properties and methods from another class. This is often done to reuse code and add new functionalities. Let's say we have a class called `Animal` with properties like `name` and methods like `makeSound()`. Now, if we want to create a more specific class, say `Dog`, which shares some characteristics of `Animal` but also has its own unique properties and methods, we can extend the `Animal` class. Here's a simple example in JavaScript: 152 | 153 | ```javascript 154 | // Parent class 155 | class Animal { 156 | constructor(name) { 157 | this.name = name; 158 | } 159 | 160 | makeSound() { 161 | console.log("Some generic sound"); 162 | } 163 | } 164 | 165 | // Child class extending Animal 166 | class Dog extends Animal { 167 | constructor(name, breed) { 168 | super(name); 169 | this.breed = breed; 170 | } 171 | 172 | // Method specific to Dog 173 | wagTail() { 174 | console.log("Wagging tail!"); 175 | } 176 | } 177 | 178 | // Creating an instance of Dog 179 | const myDog = new Dog("Buddy", "Golden Retriever"); 180 | console.log(myDog.name); // Output: Buddy 181 | myDog.makeSound(); // Output: Some generic sound 182 | myDog.wagTail(); // Output: Wagging tail! 183 | ``` 184 | 185 | In this example, `Dog` extends `Animal`, inheriting its properties and methods like `name` and `makeSound()`. Additionally, `Dog` introduces its own property `breed` and method `wagTail()`. 186 | 187 | ::: tip 188 | - Extending a class in JavaScript means creating a new class that inherits properties and methods from another class. 189 | - It allows you to reuse code and add new functionalities. 190 | - The child class can access the properties and methods of the parent class. 191 | ::: 192 | 193 | ## 7. What is the difference between `super()` and `super.method()` in JavaScript? 194 | 195 | In JavaScript, `super()` is used to call the constructor of the parent class when you're making a subclass. It's like saying, `Do whatever you need to do in the constructor of the parent class`. On the other hand, `super.method()` is used to call a method from the parent class. It's like saying, `Go to the parent class and execute this specific method`. Here's a simple example to illustrate the difference: 196 | 197 | ```javascript 198 | class Parent { 199 | constructor() { 200 | console.log('Parent constructor called'); 201 | } 202 | 203 | greet() { 204 | console.log('Hello from parent'); 205 | } 206 | } 207 | 208 | class Child extends Parent { 209 | constructor() { 210 | super(); // calling parent constructor 211 | console.log('Child constructor called'); 212 | } 213 | 214 | greet() { 215 | super.greet(); // calling parent's greet method 216 | console.log('Hello from child'); 217 | } 218 | } 219 | 220 | const child = new Child(); 221 | child.greet(); 222 | ``` 223 | 224 | Here, `super()` calls the constructor of the `Parent` class, while `super.greet()` calls the `greet()` method of the `Parent` class. 225 | 226 | ::: tip 227 | - `super()` is used to call the constructor of the parent class in a subclass. 228 | - `super.method()` is used to call a specific method from the parent class in a subclass. 229 | ::: 230 | 231 | ## 8. What is the difference between `extends` and `implements` in JavaScript? 232 | 233 | In JavaScript, `extends` and `implements` are both used in object-oriented programming, but they serve different purposes. 234 | 235 | `extends` is used to create a new class that inherits properties and methods from another class. This means the new class gets all the functionalities of the parent class. Here's a simple example: 236 | 237 | ```javascript 238 | class Animal { 239 | constructor(name) { 240 | this.name = name; 241 | } 242 | 243 | speak() { 244 | console.log(`${this.name} makes a noise.`); 245 | } 246 | } 247 | 248 | class Dog extends Animal { 249 | speak() { 250 | console.log(`${this.name} barks.`); 251 | } 252 | } 253 | 254 | const dog = new Dog('Buddy'); 255 | dog.speak(); // Output: Buddy barks. 256 | ``` 257 | 258 | On the other hand, `implements` is not a native feature in JavaScript, but it's often used in TypeScript, a superset of JavaScript. It's used to declare that a class must have certain methods or properties. However, in vanilla JavaScript, there's no direct equivalent. 259 | 260 | ::: tip 261 | - `extends` is used to create a new class that inherits properties and methods from another class. 262 | - `implements` is not a native feature in JavaScript but is used in TypeScript to declare that a class must have certain methods or properties. 263 | ::: 264 | 265 | ## 9. What is the difference between `instanceof` and `typeof` in JavaScript? 266 | 267 | In JavaScript, `typeof` is used to check the type of a variable or expression, returning a string indicating the data type. It's handy for determining whether a variable is a number, string, boolean, object, function, or undefined. For example: 268 | 269 | ```javascript 270 | typeof 42; // returns "number" 271 | typeof "hello"; // returns "string" 272 | typeof true; // returns "boolean" 273 | ``` 274 | 275 | On the other hand, `instanceof` is used to check if an object is an instance of a particular class or constructor function. It returns `true` if the object is an instance of the specified class, otherwise `false`. Here's a simple example: 276 | 277 | ```javascript 278 | class Animal {} 279 | class Dog extends Animal {} 280 | 281 | const dog = new Dog(); 282 | 283 | console.log(dog instanceof Dog); // returns true 284 | console.log(dog instanceof Animal); // returns true, because Dog extends Animal 285 | console.log(dog instanceof Object); // returns true, because all objects inherit from Object 286 | ``` 287 | 288 | So, in summary, `typeof` checks the data type of a variable or expression, while `instanceof` checks if an object is an instance of a particular class or constructor function. 289 | 290 | ::: tip 291 | - `typeof` is used to check the data type of a variable or expression. 292 | - `instanceof` is used to check if an object is an instance of a particular class or constructor function. 293 | - `typeof` returns a string indicating the data type, while `instanceof` returns `true` or `false`. 294 | ::: 295 | -------------------------------------------------------------------------------- /docs/javascript/functions.md: -------------------------------------------------------------------------------- 1 | # Functions 2 | 3 | ## 1. What are functions in JavaScript? 4 | 5 | Functions in JavaScript are blocks of code that perform a specific task or return a value. They are reusable pieces of code that can be called multiple times within a program. Functions help in organizing code, making it more readable and maintainable. They can take input parameters, process them, and return a result. Functions in JavaScript can be defined using the `function` keyword or as arrow functions (`=>`) introduced in ES6. 6 | 7 | ::: tip 8 | - Functions in JavaScript are blocks of code that perform a specific task or return a value. 9 | - They help in organizing code and making it more readable and maintainable. 10 | - Functions can take input parameters, process them, and return a result. 11 | - JavaScript functions can be defined using the `function` keyword or as arrow functions (`=>`). 12 | ::: 13 | 14 | ## 2. How do you define a function in JavaScript? 15 | 16 | In JavaScript, you can define a function using the `function` keyword followed by the function name, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces. Here's an example of a simple function that adds two numbers: 17 | 18 | ```javascript 19 | function add(a, b) { 20 | return a + b; 21 | } 22 | ``` 23 | 24 | In ES6, you can also define functions using arrow function syntax. Arrow functions are more concise and provide a more straightforward way to define functions. Here's the same `add` function using arrow function syntax: 25 | 26 | ```javascript 27 | const add = (a, b) => a + b; 28 | ``` 29 | 30 | ::: tip 31 | - In JavaScript, you can define a function using the `function` keyword or arrow function syntax. 32 | - The `function` keyword syntax includes the function name, parameters, and function body. 33 | - Arrow functions provide a more concise way to define functions introduced in ES6. 34 | ::: 35 | 36 | ## 3. What are arguments and parameters in a function? 37 | 38 | In JavaScript, parameters are variables listed in the function definition, representing the values that the function expects to receive when it is called. Arguments, on the other hand, are the actual values passed to the function when it is called. When a function is called, the arguments are assigned to the corresponding parameters based on their order. 39 | 40 | Here's an example to illustrate the difference between parameters and arguments: 41 | 42 | ```javascript 43 | function greet(name) { 44 | console.log(`Hello, ${name}!`); 45 | } 46 | 47 | greet('Alice'); // 'Alice' is the argument passed to the function greet 48 | ``` 49 | 50 | In this example, `name` is the parameter defined in the `greet` function, and `'Alice'` is the argument passed to the function when it is called. 51 | 52 | ::: tip 53 | - Parameters are variables listed in the function definition. 54 | - Arguments are the actual values passed to the function when it is called. 55 | - Parameters and arguments allow functions to accept input values and perform tasks based on them. 56 | ::: 57 | 58 | ## 4. What is the difference between function declaration and function expression? 59 | 60 | In JavaScript, there are two ways to define functions: function declarations and function expressions. 61 | 62 | - **Function Declaration**: A function declaration defines a named function using the `function` keyword. Function declarations are hoisted, which means they are available for use before they are defined in the code. 63 | 64 | ```javascript 65 | function greet(name) { 66 | return `Hello, ${name}!`; 67 | } 68 | ``` 69 | 70 | - **Function Expression**: A function expression defines a function as part of an expression, such as assigning it to a variable. Function expressions are not hoisted, and they must be defined before they are used. 71 | 72 | ```javascript 73 | const greet = function(name) { 74 | return `Hello, ${name}!`; 75 | }; 76 | ``` 77 | 78 | The key difference between function declarations and function expressions is hoisting. Function declarations are hoisted, while function expressions are not. 79 | 80 | ::: tip 81 | - Function declarations define named functions using the `function` keyword. 82 | - Function expressions define functions as part of an expression, such as assigning them to variables. 83 | - Function declarations are hoisted, while function expressions are not. 84 | ::: 85 | 86 | ## 5. What is a callback function? 87 | 88 | A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of action or operation. Callback functions are commonly used in JavaScript for asynchronous tasks, event handling, and other scenarios where you want to execute code after a specific task is completed. 89 | 90 | Here's an example of a callback function used with the `setTimeout` function: 91 | 92 | ```javascript 93 | function greet(name, callback) { 94 | console.log(`Hello, ${name}!`); 95 | callback(); 96 | } 97 | 98 | function sayGoodbye() { 99 | console.log('Goodbye!'); 100 | } 101 | 102 | greet('Alice', sayGoodbye); 103 | ``` 104 | 105 | In this example, `sayGoodbye` is a callback function passed to the `greet` function, which is invoked after the greeting message is displayed. 106 | 107 | ::: tip 108 | - A callback function is a function passed as an argument to another function. 109 | - Callback functions are commonly used for asynchronous tasks and event handling. 110 | - They allow you to execute code after a specific task is completed. 111 | - Callback functions help in managing the flow of asynchronous operations in JavaScript. 112 | ::: 113 | 114 | ## 6. What is a higher-order function? 115 | 116 | A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. Higher-order functions are a powerful concept in functional programming and are commonly used in JavaScript to create abstractions and compose functions. 117 | 118 | Here's an example of a higher-order function that takes a function as an argument: 119 | 120 | ```javascript 121 | function applyOperation(a, b, operation) { 122 | return operation(a, b); 123 | } 124 | 125 | function add(a, b) { 126 | return a + b; 127 | } 128 | 129 | console.log(applyOperation(5,2, add)); // Output: 7 130 | ``` 131 | 132 | In this example, `applyOperation` is a higher-order function that takes an operation function as an argument and applies it to the given arguments `a` and `b`. 133 | 134 | ::: tip 135 | - A higher-order function is a function that takes one or more functions as arguments or returns a function. 136 | - Higher-order functions are commonly used in functional programming to create abstractions and compose functions. 137 | ::: 138 | 139 | ## 7. What is a pure function? 140 | 141 | A pure function is a function that always produces the same output for the same input and has no side effects. Pure functions are deterministic, meaning they do not depend on external state or modify state outside their scope. They are predictable, testable, and easier to reason about compared to impure functions. 142 | 143 | Here's an example of a pure function: 144 | 145 | ```javascript 146 | function add(a, b) { 147 | return a + b; 148 | } 149 | ``` 150 | 151 | In this example, the `add` function is pure because it always returns the same result for the same input values `a` and `b`. 152 | 153 | ::: tip 154 | - A pure function always produces the same output for the same input and has no side effects. 155 | - Pure functions are deterministic, predictable, and easier to reason about. 156 | - They do not depend on external state or modify state outside their scope. 157 | - Pure functions are essential in functional programming and help in writing clean and maintainable code. 158 | ::: 159 | 160 | ## 8. What are default parameters in a function? 161 | 162 | Default parameters in a function allow you to specify default values for parameters if no argument is provided when the function is called. Default parameters help in handling cases where arguments are missing or `undefined`, providing a fallback value for the parameter. 163 | 164 | Here's an example of a function with default parameters: 165 | 166 | ```javascript 167 | function greet(name = 'World') { 168 | console.log(`Hello, ${name}!`); 169 | } 170 | 171 | greet(); // Output: Hello, World! 172 | greet('Alice'); // Output: Hello, Alice! 173 | ``` 174 | 175 | In this example, the `greet` function has a default parameter `name` set to `'World'`. If no argument is provided, the default value `'World'` is used. 176 | 177 | ::: tip 178 | - Default parameters in a function allow you to specify default values for parameters. 179 | - They provide a fallback value if no argument is provided when the function is called. 180 | ::: 181 | 182 | ## 9. How to get the list of arguments passed to a function? 183 | 184 | In JavaScript, you can access the list of arguments passed to a function using the `arguments` object or the rest parameter syntax (`...args`). The `arguments` object is an array-like object that contains all the arguments passed to the function, while the rest parameter syntax allows you to capture a variable number of arguments as an array. 185 | 186 | Here's an example using the `arguments` object: 187 | 188 | ```javascript 189 | function sum() { 190 | let total = 0; 191 | for (let i = 0; i < arguments.length; i++) { 192 | total += arguments[i]; 193 | } 194 | return total; 195 | } 196 | 197 | console.log(sum(1,2,3)) // Output: 6 198 | ``` 199 | 200 | And here's an example using the rest parameter syntax: 201 | 202 | ```javascript 203 | function sum(...args) { 204 | return args.reduce((acc, val) => acc + val, 0); 205 | } 206 | 207 | console.log(sum(1,2,3)); // Output: 6 208 | ``` 209 | 210 | In both examples, the `sum` function calculates the sum of all arguments passed to it. 211 | 212 | ::: tip 213 | - You can access the list of arguments passed to a function using the `arguments` object or the rest parameter syntax. 214 | - The `arguments` object is an array-like object containing all the arguments passed to the function. 215 | - The rest parameter syntax allows you to capture a variable number of arguments as an array. 216 | - Both methods help in handling functions with a variable number of arguments in JavaScript. 217 | - The rest parameter syntax is preferred over the `arguments` object for its simplicity and flexibility. 218 | - The `arguments` object is not available in arrow functions. 219 | - The rest parameter syntax is more versatile and recommended for modern JavaScript code. 220 | ::: 221 | 222 | ## 10. What is a recursive function? 223 | 224 | A recursive function is a function that calls itself within its definition to solve a smaller instance of the same problem. Recursive functions are useful for solving problems that can be broken down into smaller subproblems of the same type. They follow the principle of divide and conquer, where a complex problem is divided into simpler subproblems until a base case is reached. 225 | 226 | Here's an example of a recursive function to calculate the factorial of a number: 227 | 228 | ```javascript 229 | function factorial(n) { 230 | if (n === 0) { 231 | return 1; 232 | } else { 233 | return n * factorial(n - 1); 234 | } 235 | } 236 | 237 | console.log(factorial(5)); // Output: 120 238 | ``` 239 | 240 | In this example, the `factorial` function calls itself to calculate the factorial of a number by reducing the problem to a smaller subproblem until the base case is reached. 241 | 242 | ::: tip 243 | - A recursive function is a function that calls itself within its definition to solve a smaller instance of the same problem. 244 | - Recursive functions are useful for solving problems that can be broken down into smaller subproblems of the same type. 245 | ::: 246 | 247 | ## 11. What is unary function? 248 | 249 | A unary function is a function that takes exactly one argument. The term `unary` comes from the Latin word `unarius`, meaning `consisting of one`. Unary functions are common in mathematics and computer science, where they operate on a single input value to produce an output. 250 | 251 | Here's an example of a unary function in JavaScript: 252 | 253 | ```javascript 254 | const square = (x) => x * x; 255 | 256 | console.log(square(5)); // Output: 25 257 | ``` 258 | 259 | In this example, the `square` function is a unary function that takes a single argument `x` and returns the square of that argument. 260 | 261 | ::: tip 262 | - A unary function is a function that takes exactly one argument. 263 | ::: 264 | 265 | ## 12. What is a variadic function? 266 | 267 | A variadic function is a function that can accept a variable number of arguments. The term `variadic` comes from the Latin word `variabilis`, meaning `variable`. Variadic functions are flexible and can handle different numbers of arguments passed to them. 268 | 269 | Here's an example of a variadic function in JavaScript using the rest parameter syntax: 270 | 271 | ```javascript 272 | function sum(...args) { 273 | return args.reduce((acc, val) => acc + val, 0); 274 | } 275 | 276 | console.log(sum(1,2,3)); // Output: 6 277 | console.log(sum(1,2,3,4,5)); // Output: 15 278 | ``` 279 | 280 | In this example, the `sum` function can accept any number of arguments and calculates the sum of all arguments passed to it. 281 | 282 | ::: tip 283 | - A variadic function is a function that can accept a variable number of arguments. 284 | ::: 285 | 286 | ## 13. What is a curried function? 287 | 288 | A curried function is a function that takes multiple arguments one at a time, returning a series of new functions that each take the next argument. Currying allows you to transform a function that takes multiple arguments into a sequence of functions that each take a single argument. 289 | 290 | Here's an example of a curried function in JavaScript: 291 | 292 | ```javascript 293 | function add(a) { 294 | return function(b) { 295 | return a + b; 296 | }; 297 | } 298 | 299 | console.log(add(2)(3)); // Output: 5 300 | ``` 301 | 302 | In this example, the `add` function is curried, allowing you to call it with one argument at a time to perform addition. 303 | 304 | ::: tip 305 | - A curried function is a function that takes multiple arguments one at a time. 306 | - It returns a series of new functions that each take the next argument. 307 | - Currying allows you to transform a function that takes multiple arguments into a sequence of functions that each take a single argument. 308 | ::: 309 | 310 | ## 14. What is a memoized function? 311 | 312 | A memoized function is a function that caches the results of its computations based on the arguments passed to it. Memoization is a technique used to optimize functions by storing the results of expensive function calls and returning the cached result when the same inputs occur again. 313 | 314 | Here's an example of a memoized function in JavaScript: 315 | 316 | ```javascript 317 | function memoize(fn) { 318 | const cache = new Map(); 319 | return function(...args) { 320 | const key = args.join(','); 321 | if (cache.has(key)) { 322 | return cache.get(key); 323 | } else { 324 | const result = fn(...args); 325 | cache.set(key, result); 326 | return result; 327 | } 328 | }; 329 | } 330 | 331 | function factorial(n) { 332 | if (n === 0) { 333 | return 1; 334 | } else { 335 | return n * factorial(n - 1); 336 | } 337 | } 338 | 339 | const memoizedFactorial = memoize(factorial); 340 | 341 | console.log(memoizedFactorial(5)); // Output: 120 342 | 343 | console.log(memoizedFactorial(5)); // Output: 120 (cached result) 344 | ``` 345 | 346 | In this example, the `memoize` function wraps the `factorial` function, caching the results of the factorial computation based on the input arguments. 347 | 348 | ::: tip 349 | - A memoized function is a function that caches the results of its computations based on the arguments passed to it. 350 | - Memoization is a technique used to optimize functions by storing the results of expensive function calls and returning the cached result when the same inputs occur again. 351 | ::: 352 | 353 | ## 15. What is a generator function? 354 | 355 | A generator function is a special type of function in JavaScript that can pause its execution and yield multiple values one at a time. Generator functions are defined using the `function*` syntax and use the `yield` keyword to produce values. They allow you to create iterators that can generate a sequence of values lazily. 356 | 357 | Here's an example of a generator function in JavaScript: 358 | 359 | ```javascript 360 | function* generateSequence() { 361 | yield 1; 362 | yield 2; 363 | yield 3; 364 | } 365 | 366 | const sequence = generateSequence(); 367 | 368 | console.log(sequence.next().value); // Output: 1 369 | console.log(sequence.next().value); // Output: 2 370 | console.log(sequence.next().value); // Output: 3 371 | ``` 372 | 373 | In this example, the `generateSequence` function creates an iterator that yields the values 1, 2, and 3 successively. Each time the `next()` method is called on the iterator, it resumes execution of the generator function until the next `yield` statement is encountered, returning the yielded value. 374 | 375 | ::: tip 376 | - A generator function is a special type of function in JavaScript that can pause its execution and yield multiple values one at a time. 377 | - Generator functions are defined using the `function*` syntax and use the `yield` keyword to produce values. 378 | - They allow you to create iterators that can generate a sequence of values lazily. 379 | - Generator functions are useful for creating custom iterators, asynchronous programming, and state management in JavaScript. 380 | ::: 381 | 382 | ## 16. What is an anonymous function? 383 | 384 | An anonymous function is a function without a name that can be defined inline or assigned to a variable. Anonymous functions are commonly used in JavaScript for one-time or short-lived tasks where defining a named function is unnecessary. 385 | 386 | Here's an example of an anonymous function assigned to a variable: 387 | 388 | ```javascript 389 | const greet = function(name) { 390 | console.log(`Hello, ${name}!`); 391 | }; 392 | 393 | greet('Alice'); // Output: Hello, Alice! 394 | ``` 395 | 396 | In this example, the anonymous function takes a `name` parameter and logs a greeting message to the console. 397 | 398 | ::: tip 399 | - An anonymous function is a function without a name that can be defined inline or assigned to a variable. 400 | - Anonymous functions are commonly used for one-time or short-lived tasks where defining a named function is unnecessary. 401 | ::: 402 | 403 | ## 17. What is a thunk function? 404 | 405 | A thunk function is a special type of function that delays the evaluation of an expression or operation until it is needed. Thunks are used to encapsulate computations and defer their execution to a later time, allowing for lazy evaluation and improved performance. 406 | 407 | Here's an example of a thunk function in JavaScript: 408 | 409 | ```javascript 410 | function createThunk(value) { 411 | return function() { 412 | return value; 413 | }; 414 | } 415 | 416 | const delayedValue = createThunk(42); 417 | 418 | console.log(delayedValue()); // Output: 42 419 | ``` 420 | 421 | In this example, the `createThunk` function creates a thunk that encapsulates the value `42`. The thunk function delays the evaluation of the value until it is called, allowing for lazy evaluation. 422 | 423 | ::: tip 424 | - A thunk function is a special type of function that delays the evaluation of an expression or operation until it is needed. 425 | - Thunks are used to encapsulate computations and defer their execution to a later time, allowing for lazy evaluation and improved performance. 426 | ::: 427 | 428 | ## 18. What is the return statement in a function? 429 | 430 | The `return` statement in a function specifies the value that the function should return when it is called. The `return` statement can be used to exit the function early and return a value, or it can be used to return the result of a computation or operation. 431 | 432 | Here's an example of a function with a `return` statement: 433 | 434 | ```javascript 435 | function add(a, b) { 436 | return a + b; 437 | } 438 | 439 | const result = add(2, 3); 440 | 441 | console.log(result); // Output: 5 442 | ``` 443 | 444 | In this example, the `add` function returns the sum of the two arguments `a` and `b` using the `return` statement. 445 | 446 | ::: tip 447 | - The `return` statement in a function specifies the value that the function should return when it is called. 448 | - The `return` statement can be used to exit the function early and return a value, or it can be used to return the result of a computation or operation. 449 | ::: 450 | 451 | ## 19. What is the context of a function? 452 | 453 | The context of a function in JavaScript refers to the value of the `this` keyword inside the function. The `this` keyword in JavaScript refers to the object that the function is a method of or the object that the function is called on. The context of a function determines which object the function has access to and which properties and methods it can use. 454 | 455 | Here's an example of a function and its context: 456 | 457 | ```javascript 458 | const person = { 459 | name: 'Alice', 460 | greet: function() { 461 | console.log(`Hello, ${this.name}!`); 462 | } 463 | }; 464 | 465 | person.greet(); // Output: Hello, Alice! 466 | ``` 467 | 468 | In this example, the `greet` function is a method of the `person` object, so the context of the function is the `person` object itself. The `this` keyword inside the `greet` function refers to the `person` object, allowing it to access the `name` property. 469 | 470 | ::: tip 471 | - The context of a function in JavaScript refers to the value of the `this` keyword inside the function. 472 | - The `this` keyword in JavaScript refers to the object that the function is a method of or the object that the function is called on. 473 | ::: 474 | 475 | ## 20. What is bind method in a function? 476 | 477 | Binding in a function refers to the process of associating a function with a specific context or object. In JavaScript, functions are first-class citizens, meaning they can be passed around as values and executed in different contexts. Binding allows you to control the value of `this` inside a function and specify the context in which the function should be executed. 478 | 479 | Here's an example of binding a function to a specific context using the `bind` method: 480 | 481 | ```javascript 482 | const person = { 483 | name: 'Alice', 484 | greet: function() { 485 | console.log(`Hello, ${this.name}!`); 486 | } 487 | }; 488 | 489 | person.greet(); // Output: Hello, Alice! 490 | 491 | const anotherPerson = { 492 | name: 'Bob' 493 | }; 494 | 495 | const greetAnotherPerson = person.greet.bind(anotherPerson); 496 | 497 | greetAnotherPerson.call(anotherPerson); // Output: Hello, Bob! 498 | ``` 499 | 500 | In this example, the `greet` function is bound to the `person` object using the `bind` method, allowing it to access the `name` property of the `person` object. 501 | 502 | ::: tip 503 | - Binding in a function refers to the process of associating a function with a specific context or object. 504 | - Binding allows you to control the value of `this` inside a function and specify the context in which the function should be executed. 505 | ::: 506 | 507 | ## 21. What is call method in a function? 508 | 509 | The `call` method in JavaScript is used to call a function with a specific context or object as the first argument. The `call` method allows you to specify the value of `this` inside a function explicitly and pass arguments to the function as individual parameters. 510 | 511 | Here's an example of using the `call` method to call a function with a specific context: 512 | 513 | ```javascript 514 | const person = { 515 | name: 'Alice', 516 | greet: function() { 517 | console.log(`Hello, ${this.name}!`); 518 | } 519 | }; 520 | 521 | person.greet(); // Output: Hello, Alice! 522 | 523 | const anotherPerson = { 524 | name: 'Bob' 525 | }; 526 | 527 | person.greet.call(anotherPerson); // Output: Hello, Bob! 528 | ``` 529 | 530 | In this example, the `call` method is used to call the `greet` function with the `anotherPerson` object as the context, allowing it to access the `name` property of the `anotherPerson` object. 531 | 532 | ::: tip 533 | - The `call` method in JavaScript is used to call a function with a specific context or object as the first argument. 534 | - The `call` method allows you to specify the value of `this` inside a function explicitly and pass arguments to the function as individual parameters. 535 | ::: 536 | 537 | ## 22. What is apply method in a function? 538 | 539 | The `apply` method in JavaScript is used to call a function with a specific context or object as the first argument and an array of arguments as the second argument. The `apply` method allows you to specify the value of `this` inside a function explicitly and pass arguments to the function as an array. 540 | 541 | Here's an example of using the `apply` method to call a function with a specific context and arguments: 542 | 543 | ```javascript 544 | const person = { 545 | name: 'Alice', 546 | greet: function(greeting) { 547 | console.log(`${greeting}, ${this.name}!`); 548 | } 549 | }; 550 | 551 | person.greet('Hello'); // Output: Hello, Alice! 552 | 553 | const anotherPerson = { 554 | name: 'Bob' 555 | }; 556 | 557 | person.greet.apply(anotherPerson, ['Hi']); // Output: Hi, Bob! 558 | ``` 559 | 560 | In this example, the `apply` method is used to call the `greet` function with the `anotherPerson` object as the context and the greeting message as an array of arguments. 561 | 562 | ::: tip 563 | - The `apply` method in JavaScript is used to call a function with a specific context or object as the first argument and an array of arguments as the second argument. 564 | - The `apply` method allows you to specify the value of `this` inside a function explicitly and pass arguments to the function as an array. 565 | ::: 566 | 567 | ## 23. What are differences between bind, call, and apply methods in a function? 568 | 569 | The `bind`, `call`, and `apply` methods in JavaScript are used to control the value of `this` inside a function and specify the context in which the function should be executed. While all three methods allow you to call a function with a specific context, they differ in how they accept arguments and pass them to the function. 570 | 571 | Here are the key differences between the `bind`, `call`, and `apply` methods: 572 | 573 | - **`bind` Method**: The `bind` method creates a new function with a specific context and returns the new function without calling it. The `bind` method allows you to bind a function to a specific context permanently, making it useful for creating bound functions that can be called later. 574 | 575 | ```javascript 576 | const boundFunction = originalFunction.bind(context); 577 | ``` 578 | 579 | - **`call` Method**: The `call` method calls a function with a specific context and passes arguments to the function as individual parameters. The `call` method allows you to specify the value of `this` inside a function explicitly and pass arguments to the function dynamically. 580 | 581 | ```javascript 582 | originalFunction.call(context, arg1, arg2, ...); 583 | ``` 584 | 585 | - **`apply` Method**: The `apply` method calls a function with a specific context and passes arguments to the function as an array. The `apply` method allows you to specify the value of `this` inside a function explicitly and pass arguments to the function as an array. 586 | 587 | ```javascript 588 | originalFunction.apply(context, [arg1, arg2, ...]); 589 | ``` 590 | 591 | The key differences between the `bind`, `call`, and `apply` methods are in how they accept arguments and pass them to the function. The `bind` method creates a new function with a specific context, while the `call` and `apply` methods call the function with a specific context and pass arguments to the function. 592 | 593 | ::: tip 594 | - The `bind` method creates a new function with a specific context and returns the new function without calling it. 595 | - The `call` method calls a function with a specific context and passes arguments to the function as individual parameters. 596 | - The `apply` method calls a function with a specific context and passes arguments to the function as an array. 597 | ::: 598 | 599 | ## 24. What is callback hell? 600 | 601 | Callback hell is a term used to describe the situation where multiple nested callback functions are used in asynchronous JavaScript code, leading to complex and hard-to-read code. Callback hell occurs when asynchronous operations are nested inside each other, making the code difficult to understand and maintain. 602 | 603 | Here's an example of callback hell in JavaScript: 604 | 605 | ```javascript 606 | asyncOperation1(function(result1) { 607 | asyncOperation2(result1, function(result2) { 608 | asyncOperation3(result2, function(result3) { 609 | // More nested callbacks... 610 | }); 611 | }); 612 | }); 613 | ``` 614 | 615 | In this example, multiple asynchronous operations are nested inside each other, creating a pyramid of callbacks that can be challenging to manage and debug. 616 | 617 | ::: tip 618 | - Callback hell is a term used to describe the situation where multiple nested callback functions are used in asynchronous JavaScript code. 619 | - Callback hell occurs when asynchronous operations are nested inside each other, leading to complex and hard-to-read code. 620 | - Modern JavaScript features like promises and async/await help in reducing callback hell and improving the readability of asynchronous code. 621 | ::: 622 | 623 | 624 | -------------------------------------------------------------------------------- /docs/javascript/index.md: -------------------------------------------------------------------------------- 1 | # Javascript 2 | 3 | ## 1. What is Javascript? 4 | 5 | JavaScript is a type of computer programming language that's commonly used to make websites interactive. It works alongside HTML and CSS to bring web pages to life by adding things like animations, interactive forms, and dynamic content. JavaScript can be thought of as the language that makes websites do cool stuff when you click on buttons, submit forms, or scroll through a page. It's versatile and powerful, allowing developers to create all sorts of features that make websites more engaging and user-friendly. 6 | 7 | ::: tip 8 | - JavaScript is a programming language used for making websites interactive. 9 | - It works alongside HTML and CSS to create dynamic web pages. 10 | - It's responsible for making things happen on a webpage when users interact, like clicking buttons or submitting forms. 11 | ::: 12 | 13 | ## 2. What are the key features of JavaScript? 14 | 15 | JavaScript, often called JS, has some key features that make it unique. Firstly, it's versatile, meaning it can run in various environments like web browsers, servers, or even in hardware like robots. Secondly, it's dynamic, allowing changes to be made while a program is running, making it very flexible. Another important feature is its event-driven nature, meaning it can respond to actions like clicks or inputs from users. Additionally, JavaScript supports functions, which are blocks of code that can be reused, making programs easier to manage. Lastly, it's an interpreted language, meaning it doesn't need to be compiled before running, making it quick to develop and test code. These features combined make JavaScript a powerful language for creating interactive and dynamic web pages. 16 | 17 | ::: tip 18 | - Versatility: JavaScript can run in various environments such as web browsers, servers, and hardware. 19 | - Dynamic: Allows changes to be made while a program is running, enhancing flexibility. 20 | - Event-driven: Capable of responding to user actions like clicks or inputs. 21 | - Functions: Supports reusable blocks of code, aiding in program organization and management. 22 | - Interpreted: Doesn't require compilation before running, facilitating quick development and testing of code. 23 | ::: 24 | 25 | ## 3. What kind of language is JavaScript? 26 | 27 | JavaScript is a type of programming language. It's considered high-level, which means it's easier for people to understand compared to lower-level languages that computers can directly understand. It follows a set of rules called the ECMAScript standard. JavaScript can change its data type while the program is running, which is called dynamic typing. It's built around creating objects based on other objects, and it treats functions as special objects, allowing them to be used in many different ways. You can use it in different programming styles like event-driven, functional, and imperative. It also provides tools for working with text, dates, and organizing web pages. 28 | 29 | ::: tip 30 | - JavaScript is a high-level programming language. 31 | - It conforms to the ECMAScript standard. 32 | - JavaScript uses dynamic typing, meaning it can change data types during runtime. 33 | - It is prototype-based for object-orientation. 34 | - Functions are treated as first-class citizens, allowing for versatile use. 35 | - Supports multiple programming paradigms including event-driven, functional, and imperative. 36 | - Provides APIs for tasks such as working with text, dates, regular expressions, standard data structures, and manipulating the Document Object Model (DOM). 37 | ::: 38 | 39 | ## 4. What is dynamic typing in programming languages? 40 | 41 | Dynamic typing in programming languages like JavaScript means that you don't have to declare the data type of a variable explicitly when you create it. Instead, the type of the variable is determined automatically based on the type of value it holds. This allows for flexibility because you can assign different types of values to the same variable without any strict rules about data types. For example, a variable could hold a number at one point and then hold a string or an object at another point in the program. Dynamic typing simplifies coding because you don't need to worry about specifying data types, but it also requires careful attention to avoid unexpected behavior due to type mismatches. 42 | 43 | ::: tip 44 | - Dynamic typing in JavaScript means you don't have to specify the data type of a variable when you create it. 45 | - The type of the variable is automatically determined based on the type of value it holds at runtime. 46 | - This flexibility allows variables to hold different types of values during the execution of a program. 47 | - You can assign numbers, strings, objects, or other types of data to the same variable without declaring its type explicitly. 48 | - While dynamic typing simplifies coding by removing the need to specify data types, it requires careful attention to prevent unexpected behavior caused by type mismatches. 49 | ::: 50 | 51 | ## 5. What is prototype-based programming? 52 | 53 | In programming, particularly in JavaScript (js), a prototype-based language means that objects are created based on existing objects, rather than using classes as in traditional object-oriented languages. In simpler terms, you can make new objects by starting with old ones and changing or adding things to them. Each object in JavaScript has a prototype property which points to another object. When you try to access a property or method on an object and it's not found, JavaScript looks at the object's prototype to see if the property or method exists there. This concept allows for flexible and dynamic object creation and inheritance in JavaScript programming. 54 | 55 | ::: tip 56 | - Prototype-based programming in JavaScript means objects are created based on existing objects. 57 | - Instead of using classes like in traditional object-oriented languages, new objects are made by modifying existing ones. 58 | - Each object in JavaScript has a prototype property pointing to another object. 59 | - When accessing a property or method on an object, JavaScript checks its prototype if the property or method isn't found directly on the object. 60 | - This approach allows for flexible and dynamic object creation and inheritance in JavaScript. 61 | ::: 62 | 63 | ## 6. What does it mean for a function to be a first-class citizen? 64 | 65 | In JavaScript, when we say a function is a first-class citizen, it means that functions are treated like any other regular data types, such as numbers or strings. This allows us to store functions in variables, pass them as arguments to other functions, and even return them from functions. Basically, functions can be used in the same way we use other types of data in our code. This flexibility makes JavaScript a powerful language for writing programs because it allows for more dynamic and versatile coding possibilities. 66 | 67 | ::: tip 68 | - In JavaScript, a function being a first-class citizen means it's treated like any other regular data type. 69 | - Functions can be stored in variables. 70 | - They can be passed as arguments to other functions. 71 | - Functions can also be returned from other functions. 72 | ::: 73 | 74 | ## 7. What does it mean for a language to be multi-paradigm? 75 | 76 | A multi-paradigm language like JavaScript (JS) means it can be used in different styles or approaches to solve problems. In simpler terms, it's like having multiple tools in one toolbox. In JavaScript, you can use procedural programming, which is like following a step-by-step recipe, or object-oriented programming, where you create and manipulate objects like building blocks. Additionally, you can use functional programming, treating functions as first-class citizens, like pieces of Lego you can combine in various ways. Having all these options in one language makes JavaScript versatile, allowing developers to choose the best approach for different tasks. 77 | 78 | ::: tip 79 | - Multi-paradigm language like JavaScript (JS) means it supports various programming styles. 80 | - JavaScript allows procedural programming, akin to following step-by-step instructions. 81 | - It also facilitates object-oriented programming, where developers work with objects as building blocks. 82 | - Functional programming is another approach in JavaScript, treating functions as primary elements for task execution. 83 | - Having these multiple paradigms in JavaScript makes it versatile, enabling developers to choose the most suitable approach for different tasks. 84 | ::: 85 | 86 | ## 8. What does it mean for a language to be high level? 87 | 88 | When we say a language is high-level like JavaScript (js), it means it's designed to be easy for people to understand and use. High-level languages are closer to human language, so writing code in them is more like writing instructions for people to follow. They come with built-in functions and features that make coding easier and more efficient, without needing to worry about the nitty-gritty details of how the computer works underneath. In simple words, high-level languages like JavaScript help developers focus on solving problems rather than getting lost in technical complexities. 89 | 90 | ::: tip 91 | - A high-level language like JavaScript (js) is easy for people to understand and use. 92 | - It's designed to be closer to human language, making coding feel like giving instructions. 93 | - High-level languages come with built-in functions and features for easier coding. 94 | - Developers can focus on solving problems rather than technical complexities. 95 | - They don't need to worry about how the computer works underneath. 96 | ::: 97 | 98 | 99 | ## 9. What is object-oriented programming (OOP)? 100 | 101 | Object-oriented programming (OOP) is a way of writing computer programs where you organize your code around objects, which are like containers that hold data and functions. Each object can do specific tasks and communicate with other objects. It's like building with Lego bricks, where each brick (object) has its own unique features and can interact with other bricks to create something bigger and more complex. OOP helps make programs easier to understand, modify, and reuse because it breaks down complex problems into smaller, manageable parts. 102 | 103 | ::: tip 104 | - Object-oriented programming (OOP) organizes code around objects, which are containers holding data and functions. 105 | ::: 106 | 107 | ## 10. What are the four principles of object-oriented programming (OOP)? 108 | 109 | In object-oriented programming (OOP), there are four main principles: 110 | 111 | 1. Encapsulation: This means bundling data (variables) and methods (functions) that work on the data into a single unit, called an object. It helps in organizing and controlling access to the data, ensuring that it's only modified in appropriate ways. 112 | 113 | 2. Abstraction: Abstraction involves hiding complex implementation details and showing only the essential features of an object. It allows programmers to focus on what an object does rather than how it does it, making the code more manageable and easier to understand. 114 | 115 | 3. Inheritance: Inheritance enables a new class (called a subclass or derived class) to inherit properties and behaviors (methods) from an existing class (called a superclass or base class). This promotes code reuse and allows for the creation of a hierarchy of classes with shared characteristics. 116 | 117 | 4. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. This means that a single interface can be used to access objects of various types, making the code more flexible and adaptable to different situations. 118 | 119 | ::: tip 120 | - Encapsulation: Bundling data and methods into a single unit (object) to control access and organization. 121 | - Abstraction: Hiding complex implementation details and showing only essential features of an object. 122 | - Inheritance: Enabling a new class to inherit properties and behaviors from an existing class, promoting code reuse. 123 | - Polymorphism: Allowing objects of different classes to be treated as objects of a common superclass, enhancing flexibility. 124 | ::: 125 | 126 | ## 11. What is encapsulation in object-oriented programming (OOP)? 127 | 128 | Encapsulation in JavaScript, especially in Object-Oriented Programming (OOP), is like keeping things safe in a box. It's a way to bundle data and functions together, sort of like putting them in a container. This helps keep things organized and prevents them from being messed up accidentally. In JavaScript, you can create objects that have properties (the data) and methods (the functions), and encapsulation means keeping these properties and methods together within the object, so they work together neatly without interfering with other parts of the code. It's like having a tidy package where everything you need is stored together. 129 | 130 | ::: tip 131 | - Encapsulation in JavaScript involves bundling data and functions together within an object. 132 | ::: 133 | 134 | ## 12. What is inheritance in object-oriented programming (OOP)? 135 | 136 | Inheritance in Object-Oriented Programming (OOP) is a concept where one object can inherit properties and methods from another object. It allows us to create a hierarchy of objects where child objects can reuse and extend the functionality of parent objects. This means that if we have a parent object with certain properties and methods, we can create a new object based on that parent, inheriting all its features, and then add more specific features to it. For example, if we have a "Vehicle" object with properties like "color" and methods like "drive", we can create a "Car" object that inherits from "Vehicle" and adds specific features like "numberOfSeats" or "carType". This helps in organizing and managing code effectively, promoting reusability and scalability. 137 | 138 | ::: tip 139 | - Inheritance in Object-Oriented Programming (OOP) allows one object to inherit properties and methods from another object. 140 | ::: 141 | 142 | ## 13. What is polymorphism in object-oriented programming (OOP)? 143 | 144 | Polymorphism in JavaScript, which stands for Object-Oriented Programming (OOP), refers to the ability of different objects to be treated as if they were the same type. In simpler words, it's like having multiple objects that can do similar things but in their own unique way. For example, imagine you have different shapes like circles, squares, and triangles. Even though they all have different properties and methods, you can still use a general function to calculate their areas because they all share a common characteristic of being shapes. This flexibility and versatility make programming in JavaScript more efficient and adaptable to different situations. 145 | 146 | ::: tip 147 | - Polymorphism in JavaScript refers to the ability of different objects to be treated as if they were the same type. 148 | ::: 149 | 150 | ## 14. What is abstraction in object-oriented programming (OOP)? 151 | 152 | Abstraction in Object-Oriented Programming (OOP) is about hiding the complex inner workings of code and showing only the necessary features to the outside world. It's like using a TV remote without knowing how the circuits inside work. In OOP, abstraction allows us to focus on what an object does rather than how it does it. For instance, when we use a method like `.toFixed()` to round a number to a fixed decimal point, we don't need to know the detailed math behind it; we just use the method and get the result we want. This helps in simplifying code and making it easier to understand and use. 153 | 154 | ::: tip 155 | - Abstraction in Object-Oriented Programming (OOP) involves hiding complex implementation details and showing only essential features of an object. 156 | ::: 157 | -------------------------------------------------------------------------------- /docs/javascript/loops.md: -------------------------------------------------------------------------------- 1 | # Loops 2 | 3 | ## 1. What are loops in JavaScript? 4 | 5 | Loops in JavaScript are used to execute a block of code repeatedly until a certain condition is met. They help automate repetitive tasks and process collections of data efficiently. JavaScript provides several types of loops, such as `for`, `while`, and `do...while`, each with its own syntax and use cases. By using loops, you can iterate over arrays, objects, or other data structures to perform operations on each item without having to write the same code multiple times. 6 | 7 | ::: tip 8 | - Loops in JavaScript help execute code repeatedly. 9 | - JavaScript provides different types of loops, such as `for`, `while`, and `do...while`. 10 | ::: 11 | 12 | ## 2. What is a `for` loop in JavaScript? 13 | 14 | A `for` loop in JavaScript is used to execute a block of code multiple times based on a condition. It consists of three parts: an initialization, a condition, and an iteration statement. Here's a simple example of a `for` loop that prints numbers from 1 to 5: 15 | 16 | ```javascript 17 | for (let i = 1; i <= 5; i++) { 18 | console.log(i); 19 | } 20 | ``` 21 | 22 | In this loop: 23 | - `let i = 1` initializes a variable `i` to 1. 24 | - `i <= 5` is the condition that checks if `i` is less than or equal to 5. 25 | - `i++` increments `i` by 1 after each iteration. 26 | - `console.log(i)` prints the value of `i` to the console. 27 | - The loop runs until the condition `i <= 5` is false. 28 | 29 | ::: tip 30 | - A `for` loop executes a block of code multiple times based on a condition. 31 | - It consists of an initialization, a condition, and an iteration statement. 32 | - The loop runs until the condition becomes false. 33 | ::: 34 | 35 | ## 3. What is a `while` loop in JavaScript? 36 | 37 | A `while` loop in JavaScript is used to execute a block of code as long as a condition is true. It consists of a condition that is evaluated before each iteration. Here's an example of a `while` loop that prints numbers from 1 to 5: 38 | 39 | ```javascript 40 | let i = 1; 41 | while (i <= 5) { 42 | console.log(i); 43 | i++; 44 | } 45 | ``` 46 | 47 | In this loop: 48 | - `let i = 1` initializes a variable `i` to 1. 49 | - `i <= 5` is the condition that checks if `i` is less than or equal to 5. 50 | - `console.log(i)` prints the value of `i` to the console. 51 | - `i++` increments `i` by 1 after each iteration. 52 | - The loop continues to run as long as the condition `i <= 5` is true. 53 | 54 | ::: tip 55 | - A `while` loop executes a block of code as long as a condition is true. 56 | - It evaluates the condition before each iteration. 57 | - The loop continues to run until the condition becomes false. 58 | - Make sure the condition eventually becomes false to avoid an infinite loop. 59 | ::: 60 | 61 | ## 4. What is a `do...while` loop in JavaScript? 62 | 63 | A `do...while` loop in JavaScript is similar to a `while` loop, but it guarantees that the block of code is executed at least once before checking the condition. It consists of a block of code to execute and a condition to check after each iteration. Here's an example of a `do...while` loop that prints numbers from 1 to 5: 64 | 65 | ```javascript 66 | let i = 1; 67 | do { 68 | console.log(i); 69 | i++; 70 | } while (i <= 5); 71 | ``` 72 | 73 | In this loop: 74 | - `let i = 1` initializes a variable `i` to 1. 75 | - The block of code inside the loop prints the value of `i` to the console. 76 | - `i++` increments `i` by 1 after each iteration. 77 | - The loop continues to run as long as the condition `i <= 5` is true. 78 | - The block of code is executed at least once, even if the condition is false initially. 79 | - The condition is checked after the first iteration. 80 | 81 | ::: tip 82 | - A `do...while` loop executes a block of code at least once before checking the condition. 83 | - It evaluates the condition after each iteration. 84 | - The loop continues to run as long as the condition is true. 85 | - Make sure the condition eventually becomes false to avoid an infinite loop. 86 | ::: 87 | 88 | ## 5. What is the difference between `for` and `while` loops in JavaScript? 89 | 90 | The main difference between `for` and `while` loops in JavaScript is how they are structured and when they evaluate the condition. Here are the key differences: 91 | 92 | - **Structure**: A `for` loop consists of an initialization, a condition, and an iteration statement, all in one line. In contrast, a `while` loop has the condition at the beginning and doesn't include an initialization or iteration statement in the loop itself. 93 | - **Initialization**: In a `for` loop, you can initialize the loop variable directly in the loop definition. In a `while` loop, you need to initialize the loop variable before the loop. 94 | - **Use Cases**: Use a `for` loop when you know the number of iterations in advance or need to control the loop variable more explicitly. Use a `while` loop when you want to execute a block of code based on a condition that may change during the loop. 95 | - **Readability**: `for` loops are often more concise and easier to read for iterating over a range of values. `while` loops are more flexible and can be used for more complex looping scenarios. 96 | - **Infinite Loops**: It's easier to create an infinite loop with a `while` loop if you forget to update the loop variable. A `for` loop makes it more explicit where the loop variable is updated. 97 | 98 | ## 6. What is an infinite loop in JavaScript? 99 | 100 | An infinite loop in JavaScript is a loop that continues to execute indefinitely because the loop condition never becomes false. This can happen when the loop condition is not properly defined or when the loop variable is not updated correctly within the loop. Infinite loops can cause your program to hang or crash, consuming excessive CPU resources and memory. 101 | 102 | Here's an example of an infinite loop using a `while` loop: 103 | 104 | ```javascript 105 | while (true) { 106 | console.log('This is an infinite loop!'); 107 | } 108 | ``` 109 | 110 | In this loop, the condition `true` is always true, so the loop continues to run indefinitely, printing the message to the console repeatedly. 111 | 112 | ::: tip 113 | - Avoid creating infinite loops in your code as they can lead to performance issues and crashes. 114 | - Make sure the loop condition eventually becomes false to exit the loop. 115 | - Always update the loop variable to ensure the loop condition can change. 116 | ::: 117 | 118 | ## 7. How do you break out of a loop in JavaScript? 119 | 120 | You can break out of a loop in JavaScript using the `break` statement. The `break` statement allows you to exit the loop prematurely based on a certain condition. When the `break` statement is encountered, the loop is terminated, and the program continues with the next statement after the loop. 121 | 122 | Here's an example of using `break` in a `for` loop to exit the loop when the loop variable `i` is equal to 3: 123 | 124 | ```javascript 125 | for (let i = 1; i <= 5; i++) { 126 | console.log(i); 127 | if (i === 3) { 128 | break; // Exit the loop when i is equal to 3 129 | } 130 | } 131 | ``` 132 | 133 | In this loop: 134 | - The loop prints numbers from 1 to 3. 135 | - When the loop variable `i` is equal to 3, the `break` statement is executed. 136 | - The loop terminates, and the program continues with the next statement after the loop. 137 | 138 | ::: tip 139 | - The `break` statement allows you to exit a loop prematurely. 140 | - Use `break` when you want to stop the loop based on a certain condition. 141 | - The loop terminates immediately when `break` is encountered. 142 | - The program continues with the next statement after the loop. 143 | ::: 144 | 145 | ## 8. How do you skip an iteration in a loop in JavaScript? 146 | 147 | You can skip an iteration in a loop in JavaScript using the `continue` statement. The `continue` statement allows you to skip the current iteration of a loop based on a certain condition and continue with the next iteration. When the `continue` statement is encountered, the loop jumps to the next iteration without executing the remaining code in the loop block. 148 | 149 | Here's an example of using `continue` in a `for` loop to skip the iteration when the loop variable `i` is equal to 3: 150 | 151 | ```javascript 152 | for (let i = 1; i <= 5; i++) { 153 | if (i === 3) { 154 | continue; // Skip the iteration when i is equal to 3 155 | } 156 | console.log(i); 157 | } 158 | ``` 159 | 160 | In this loop: 161 | - The loop prints numbers from 1 to 5, skipping the number 3. 162 | - When the loop variable `i` is equal to 3, the `continue` statement is executed. 163 | - The loop skips the current iteration and continues with the next iteration. 164 | - The number 3 is not printed to the console. 165 | 166 | ::: tip 167 | - The `continue` statement allows you to skip the current iteration of a loop. 168 | - Use `continue` when you want to skip certain iterations based on a condition. 169 | - The loop jumps to the next iteration when `continue` is encountered. 170 | - The remaining code in the loop block is not executed for the current iteration. 171 | ::: 172 | 173 | ## 9. How do you iterate over an array in JavaScript? 174 | 175 | You can iterate over an array in JavaScript using various types of loops, such as `for`, `while`, `for...of`, or `forEach`. Here are examples of iterating over an array using different loop types: 176 | 177 | Using a `for` loop: 178 | 179 | ```javascript 180 | const numbers = [1, 2, 3, 4, 5]; 181 | for (let i = 0; i < numbers.length; i++) { 182 | console.log(numbers[i]); 183 | } 184 | ``` 185 | 186 | Using a `while` loop: 187 | 188 | ```javascript 189 | const numbers = [1, 2, 3, 4, 5]; 190 | let i = 0; 191 | while (i < numbers.length) { 192 | console.log(numbers[i]); 193 | i++; 194 | } 195 | ``` 196 | 197 | Using a `for...of` loop: 198 | 199 | ```javascript 200 | const numbers = [1, 2, 3, 4, 5]; 201 | for (const number of numbers) { 202 | console.log(number); 203 | } 204 | ``` 205 | 206 | Using the `forEach` method: 207 | 208 | ```javascript 209 | const numbers = [1, 2, 3, 4, 5]; 210 | numbers.forEach(number => { 211 | console.log(number); 212 | }); 213 | ``` 214 | 215 | Each of these methods allows you to iterate over the elements of an array and perform operations on each item. 216 | 217 | ::: tip 218 | - You can iterate over an array in JavaScript using `for`, `while`, `for...of`, or `forEach`. 219 | - Choose the loop type based on your specific use case and coding style. 220 | - Use `for...of` or `forEach` for simpler and more concise array iteration. 221 | - Use `for` or `while` loops when you need more control over the loop variable or iteration logic. 222 | ::: 223 | 224 | ## 10. What is the `forEach` method in JavaScript? 225 | 226 | The `forEach` method in JavaScript is used to iterate over the elements of an array and perform a function on each item. It executes a provided function once for each array element, passing the current element, index, and array itself as arguments to the function. The `forEach` method does not return a new array but allows you to perform operations on each element of the array. 227 | 228 | Here's an example of using the `forEach` method to print each element of an array: 229 | 230 | ```javascript 231 | const numbers = [1, 2, 3, 4, 5]; 232 | numbers.forEach(number => { 233 | console.log(number); 234 | }); 235 | ``` 236 | 237 | In this example: 238 | - The `forEach` method iterates over each element of the `numbers` array. 239 | - The arrow function prints each element to the console. 240 | - The function receives the current element as an argument. 241 | - The `forEach` method does not return a new array but allows you to perform operations on each element. 242 | 243 | ::: tip 244 | - The `forEach` method allows you to iterate over the elements of an array. 245 | - It executes a function on each element, passing the element, index, and array as arguments. 246 | ::: 247 | 248 | ## 11. How to iterate over an object in JavaScript? 249 | 250 | You can iterate over an object in JavaScript using a `for...in` loop or `Object.keys()` method. Here are examples of iterating over an object using different methods: 251 | 252 | Using a `for...in` loop: 253 | 254 | ```javascript 255 | const person = { 256 | name: 'Alice', 257 | age: 30, 258 | city: 'New York' 259 | }; 260 | 261 | for (const key in person) { 262 | console.log(`${key}: ${person[key]}`); 263 | } 264 | ``` 265 | 266 | Using `Object.keys()`: 267 | 268 | ```javascript 269 | const person = { 270 | name: 'Alice', 271 | age: 30, 272 | city: 'New York' 273 | }; 274 | 275 | Object.keys(person).forEach(key => { 276 | console.log(`${key}: ${person[key]}`); 277 | }); 278 | ``` 279 | 280 | Both methods allow you to iterate over the properties of an object and access the key-value pairs. 281 | 282 | ::: tip 283 | - You can iterate over an object in JavaScript using a `for...in` loop or `Object.keys()`. 284 | - Use `for...in` when you want to iterate over all enumerable properties of an object. 285 | - Use `Object.keys()` to get an array of object keys and then iterate over them using `forEach`. 286 | ::: 287 | 288 | ## 12. What is the difference between `for...in` and `for...of` loops in JavaScript? 289 | 290 | The main difference between `for...in` and `for...of` loops in JavaScript is what they iterate over and how they work. Here are the key differences: 291 | 292 | - **Iterating Over**: `for...in` iterates over the enumerable properties of an object, including inherited properties from the prototype chain. `for...of` iterates over the values of an iterable object, such as arrays, strings, or collections. 293 | - **Order**: `for...in` does not guarantee the order of iteration over object properties. `for...of` iterates over elements in the order they appear in the iterable object. 294 | - **Use Cases**: Use `for...in` when you want to iterate over object properties and access both keys and values. Use `for...of` when you want to iterate over the values of an iterable object without dealing with keys. 295 | - **Inheritance**: `for...in` iterates over all enumerable properties, including inherited ones. `for...of` does not iterate over inherited properties. 296 | - **Performance**: `for...of` is generally faster and more efficient than `for...in` because it works directly with iterable objects and does not involve prototype chain lookups. 297 | - **Compatibility**: `for...of` is not supported in older browsers like Internet Explorer, while `for...in` is widely supported across all browsers. 298 | 299 | ## 13. What are the differences between `forEach` and `for...of` loops in JavaScript? 300 | 301 | The main differences between the `forEach` method and `for...of` loop in JavaScript are how they work and what they return. Here are the key differences: 302 | 303 | - **Break and Continue**: You cannot use `break` or `continue` statements directly within a `forEach` loop. In contrast, you can use `break` and `continue` within a `for...of` loop to control the iteration flow. 304 | - **Performance**: The `for...of` loop is generally faster and more efficient than the `forEach` method because it works directly with iterable objects and does not involve function calls for each element. 305 | - **Readability**: `forEach` is often more readable and concise for simple array operations that do not require creating a new array. `for...of` is more flexible and can be used for more complex array operations. 306 | 307 | ## 14. How do you loop through a string in JavaScript? 308 | 309 | You can loop through a string in JavaScript using a `for...of` loop or `forEach` method. Here are examples of looping through a string using different methods: 310 | 311 | Using a `for...of` loop: 312 | 313 | ```javascript 314 | const str = 'Hello, World!'; 315 | for (const char of str) { 316 | console.log(char); 317 | } 318 | ``` 319 | 320 | Using the `forEach` method: 321 | 322 | ```javascript 323 | const str = 'Hello, World!'; 324 | Array.from(str).forEach(char => { 325 | console.log(char); 326 | }); 327 | ``` 328 | 329 | Both methods allow you to iterate over each character of a string and perform operations on them. 330 | 331 | ::: tip 332 | - You can loop through a string in JavaScript using a `for...of` loop or `forEach` method. 333 | - Use `for...of` when you want to iterate over each character of the string. 334 | - Use `forEach` with `Array.from()` to convert the string to an array and iterate over each character. 335 | - Strings are iterable objects, so you can use iterable methods to loop through them. 336 | ::: 337 | 338 | ## 15. How to make an object iterable in JavaScript? 339 | 340 | To make an object iterable in JavaScript, you need to implement the iterable protocol by defining a special method called `[Symbol.iterator]()` on the object. The `[Symbol.iterator]()` method should return an iterator object with a `next()` method that defines how to iterate over the object's properties. Here's an example of making an object iterable: 341 | 342 | ```javascript 343 | const person = { 344 | name: 'Alice', 345 | age: 30 346 | }; 347 | 348 | person[Symbol.iterator] = function() { 349 | const keys = Object.keys(this); 350 | let index = 0; 351 | return { 352 | next: () => { 353 | return { 354 | value: this[keys[index++]], 355 | done: index > keys.length 356 | }; 357 | } 358 | }; 359 | }; 360 | 361 | for (const value of person) { 362 | console.log(value); 363 | } 364 | ``` 365 | 366 | In this example: 367 | - The `person` object implements the iterable protocol by defining the `[Symbol.iterator]()` method. 368 | - The `[Symbol.iterator]()` method returns an iterator object with a `next()` method that iterates over the object's properties. 369 | - The `next()` method returns the next property value and a boolean flag `done` indicating if the iteration is complete. 370 | - The `for...of` loop iterates over the object's properties using the iterator. 371 | 372 | ::: tip 373 | - To make an object iterable, define the `[Symbol.iterator]()` method on the object. 374 | - The `[Symbol.iterator]()` method should return an iterator object with a `next()` method. 375 | - The `next()` method defines how to iterate over the object's properties and returns the next value and a `done` flag. 376 | ::: 377 | 378 | ## 16. What are nested loops in JavaScript? 379 | 380 | Nested loops in JavaScript are loops that are placed inside another loop. They are used to perform repetitive tasks that require multiple levels of iteration, such as iterating over a two-dimensional array or generating combinations of values. Nested loops consist of an outer loop and one or more inner loops, each with its own iteration logic. Here's an example of a nested loop: 381 | 382 | ```javascript 383 | for (let i = 1; i <= 3; i++) { 384 | for (let j = 1; j <= 3; j++) { 385 | console.log(`(${i}, ${j})`); 386 | } 387 | } 388 | ``` 389 | 390 | In this example: 391 | - The outer loop iterates over the values `1`, `2`, and `3`. 392 | - For each value of `i`, the inner loop iterates over the values `1`, `2`, and `3`. 393 | - The inner loop prints the combination of `i` and `j` to the console. 394 | - The nested loops generate all possible combinations of values from `1` to `3`. 395 | - Nested loops can be used to solve problems that involve multiple levels of iteration. 396 | 397 | ::: tip 398 | - Nested loops in JavaScript are loops placed inside another loop. 399 | - They are used for tasks that require multiple levels of iteration. 400 | ::: 401 | 402 | ## 17. What are loop control statements in JavaScript? 403 | 404 | Loop control statements in JavaScript are special statements that allow you to control the flow of a loop. They include `break`, `continue`, and `return` statements that help you exit a loop, skip an iteration, or return a value from a loop. Loop control statements provide additional control over the loop execution based on certain conditions. Here's an overview of loop control statements: 405 | 406 | - **`break`**: Exits the loop immediately when encountered, skipping the remaining iterations. 407 | - **`continue`**: Skips the current iteration and jumps to the next iteration of the loop. 408 | - **`return`**: Exits the loop and the enclosing function, returning a value from the loop. 409 | 410 | Loop control statements are useful for handling special cases or conditions within a loop and controlling the iteration flow. 411 | 412 | ::: tip 413 | - Loop control statements in JavaScript help control the flow of a loop. 414 | - Use `break` to exit the loop immediately. 415 | - Use `continue` to skip the current iteration and jump to the next one. 416 | - Use `return` to exit the loop and the enclosing function, returning a value. 417 | ::: 418 | 419 | ## 18. What is the difference between `return` and `break` in JavaScript? 420 | 421 | The main difference between `return` and `break` in JavaScript is what they do and where they can be used. Here are the key differences: 422 | 423 | - **Usage**: `return` is used to exit a function and return a value, while `break` is used to exit a loop and skip the remaining iterations. 424 | - **Scope**: `return` can only be used within a function to exit the function and return a value. `break` can only be used within a loop to exit the loop and continue with the next statement after the loop. 425 | - **Effect**: `return` terminates the function execution and returns a value to the caller. `break` terminates the loop execution and continues with the next statement after the loop. 426 | -------------------------------------------------------------------------------- /docs/javascript/maps-and-sets.md: -------------------------------------------------------------------------------- 1 | # Maps and Sets 2 | 3 | ## 1. What is Map in JavaScript? 4 | 5 | In JavaScript, a Map is a built-in data structure that allows you to store key-value pairs. It's similar to an object, but with some differences. Maps can use any type of value as a key, whereas objects are limited to using strings or symbols as keys. Additionally, Maps maintain the order of elements which means the order in which elements are added is preserved. Here's a simple example of how you can create and use a Map in JavaScript: 6 | 7 | ```javascript 8 | // Creating a Map 9 | let myMap = new Map(); 10 | 11 | // Adding key-value pairs to the Map 12 | myMap.set("name", "John"); 13 | myMap.set("age", 30); 14 | myMap.set("isStudent", false); 15 | 16 | // Getting values from the Map 17 | console.log(myMap.get("name")); // Output: John 18 | console.log(myMap.get("age")); // Output: 30 19 | console.log(myMap.get("isStudent")); // Output: false 20 | ``` 21 | 22 | In this example, we create a Map called `myMap` and add some key-value pairs using the `set` method. Then, we retrieve values from the Map using the `get` method. 23 | 24 | ::: tip 25 | - A Map in JavaScript is a data structure that stores key-value pairs. 26 | - Maps can use any type of value as a key. 27 | - Maps maintain the order of elements, unlike objects. 28 | - You can add, retrieve, and delete key-value pairs in a Map. 29 | ::: 30 | 31 | ## 2. What is WeakMap in JavaScript? 32 | 33 | In JavaScript, a WeakMap is a type of map-like collection that allows you to store key-value pairs where the keys are weakly referenced. This means that if there are no other references to a key stored in a WeakMap, it can be automatically removed by the garbage collector. WeakMap is particularly useful when you want to associate some data with objects without preventing those objects from being garbage collected when they're no longer needed elsewhere in your code. Here's a simple example: 34 | 35 | ```javascript 36 | let weakMap = new WeakMap(); 37 | 38 | let key = {}; // creating an empty object as a key 39 | let value = "Some value"; 40 | 41 | weakMap.set(key, value); // setting a key-value pair in the WeakMap 42 | 43 | console.log(weakMap.get(key)); // retrieving the value associated with the key 44 | 45 | key = null; // removing the reference to the key object 46 | 47 | // At this point, since key is no longer referenced elsewhere, it can be garbage collected 48 | // and the associated entry in the WeakMap might also be automatically removed 49 | ``` 50 | 51 | In this example, `key` is an object used as a key in the WeakMap, and `value` is the associated value. If `key` is no longer referenced anywhere else in the code (after setting the key-value pair in the WeakMap), both `key` and its associated value may be eligible for garbage collection. 52 | 53 | ::: tip 54 | - WeakMap is a collection that allows you to store key-value pairs where the keys are weakly referenced. 55 | - If there are no other references to a key stored in a WeakMap, it can be automatically removed by the garbage collector. 56 | - WeakMap is useful for associating data with objects without preventing those objects from being garbage collected. 57 | - WeakMap is particularly helpful in scenarios where you want to store additional data for objects that are temporary or dynamically created. 58 | ::: 59 | 60 | ## 3. What is Set in JavaScript? 61 | 62 | In JavaScript, a Set is a built-in data structure that lets you store unique values of any type, whether primitive values or object references. It's like an array, but it can only contain unique values. This means you can't have duplicate elements in a Set. Here's a simple example of how to create and use a Set in JavaScript: 63 | 64 | ```javascript 65 | // Creating a Set 66 | let mySet = new Set(); 67 | 68 | // Adding values to the Set 69 | mySet.add(1); 70 | mySet.add(2); 71 | mySet.add(3); 72 | mySet.add(1); // This won't be added because it's a duplicate 73 | 74 | // Checking the size of the Set 75 | console.log("Size of the Set:", mySet.size); // Output: 3 76 | 77 | // Checking if a value exists in the Set 78 | console.log("Does the Set contain 2?", mySet.has(2)); // Output: true 79 | 80 | // Deleting a value from the Set 81 | mySet.delete(2); 82 | 83 | // Checking the size again 84 | console.log("Size of the Set after deleting:", mySet.size); // Output: 2 85 | ``` 86 | 87 | In this example, we create a Set called `mySet`, add some values to it, check its size, verify if a value exists, and then delete a value from it. 88 | 89 | ::: tip 90 | - A Set in JavaScript is a data structure that stores unique values of any type. 91 | - Sets can contain primitive values or object references. 92 | - Duplicate elements are not allowed in a Set. 93 | - You can add, remove, and check for the existence of values in a Set. 94 | ::: 95 | 96 | ## 4. What is WeakSet in JavaScript? 97 | 98 | In JavaScript, a WeakSet is a collection that allows you to store a set of unique objects. Unlike regular sets, WeakSets hold weak references to the objects they contain, meaning that if there are no other references to an object, it can be automatically removed from the WeakSet. This can be useful for managing memory more efficiently, especially when dealing with temporary or dynamically created objects. Here's a simple example of how you can use WeakSet in JavaScript: 99 | 100 | ```javascript 101 | // Creating a WeakSet 102 | let weakSet = new WeakSet(); 103 | 104 | // Creating some objects 105 | let obj1 = {}; 106 | let obj2 = {}; 107 | 108 | // Adding objects to the WeakSet 109 | weakSet.add(obj1); 110 | weakSet.add(obj2); 111 | 112 | // Checking if an object is in the WeakSet 113 | console.log(weakSet.has(obj1)); // Output: true 114 | 115 | // Removing the reference to obj2 116 | obj2 = null; 117 | 118 | // At this point, since obj2 is no longer referenced elsewhere, it can be garbage collected 119 | ``` 120 | 121 | In this example, `obj1` and `obj2` are objects added to the WeakSet. If an object is no longer referenced elsewhere in the code (after being added to the WeakSet), it may be eligible for garbage collection. 122 | 123 | ::: tip 124 | - WeakSet is a collection that allows you to store a set of unique objects. 125 | - WeakSets hold weak references to the objects they contain, allowing objects to be automatically removed if there are no other references to them. 126 | - WeakSets are useful for managing memory efficiently, especially with temporary or dynamically created objects. 127 | ::: 128 | 129 | ## 5. How to check if a value exists in a Set in JavaScript? 130 | 131 | To check if a value exists in a Set in JavaScript, you can use the `has()` method. This method returns `true` if the value is present in the Set, otherwise it returns `false`. Here's a simple example: 132 | 133 | ```javascript 134 | // Creating a Set 135 | let mySet = new Set([1, 2, 3, 4, 5]); 136 | 137 | // Checking if a value exists 138 | let valueExists = mySet.has(3); // Check if value 3 exists in the Set 139 | 140 | // Outputting the result 141 | console.log(valueExists); // This will print true since 3 exists in the Set 142 | ``` 143 | 144 | In this example, `mySet.has(3)` checks if the value `3` exists in the Set `mySet`, and it returns `true` because `3` is present in the Set. 145 | 146 | ::: tip 147 | - To check if a value exists in a Set in JavaScript, use the `has()` method. 148 | ::: 149 | 150 | ## 6. How to remove a value from a Set in JavaScript? 151 | 152 | In JavaScript, removing a value from a Set is straightforward. You can use the `delete()` method available for Sets. Here's a simple example to demonstrate: 153 | 154 | ```javascript 155 | // Creating a Set 156 | let mySet = new Set([1, 2, 3, 4, 5]); 157 | 158 | // Removing a value from the Set 159 | mySet.delete(3); // This will remove the value 3 from the Set 160 | 161 | console.log(mySet); // Output: Set(4) { 1, 2, 4, 5 } 162 | ``` 163 | 164 | In this code, we first create a Set called `mySet` with some initial values. Then, we use the `delete()` method to remove the value `3` from the Set. Finally, we log the Set to the console to verify that the value has been removed. 165 | 166 | ::: tip 167 | - To remove a value from a Set in JavaScript, use the `delete()` method. 168 | ::: 169 | 170 | ## 7. How to iterate over a Set in JavaScript? 171 | 172 | To iterate over a Set in JavaScript, you can use a `for...of` loop or the `forEach()` method. Here's a simple example using both methods: 173 | 174 | ```javascript 175 | // Creating a Set 176 | let mySet = new Set([1, 2, 3, 4, 5]); 177 | 178 | // Using for...of loop 179 | for (let item of mySet) { 180 | console.log(item); 181 | } 182 | 183 | // Using forEach() method 184 | mySet.forEach(item => { 185 | console.log(item); 186 | }); 187 | ``` 188 | 189 | In this code, we first create a Set called `mySet` with some numbers. Then, we iterate over the Set using a `for...of` loop and the `forEach()` method, printing each item in the Set to the console. These are the two common ways to iterate over a Set in JavaScript. 190 | 191 | ::: tip 192 | - To iterate over a Set in JavaScript, you can use a `for...of` loop or the `forEach()` method. 193 | ::: 194 | 195 | ## 8. How to check if a key exists in a Map in JavaScript? 196 | 197 | To check if a key exists in a Map in JavaScript, you can use the `has()` method. This method returns a boolean indicating whether an element with the specified key exists or not. Here's a simple example: 198 | 199 | ```javascript 200 | // Creating a Map 201 | let myMap = new Map(); 202 | 203 | // Adding some key-value pairs to the Map 204 | myMap.set('a', 1); 205 | myMap.set('b', 2); 206 | myMap.set('c', 3); 207 | 208 | // Checking if a key exists 209 | if (myMap.has('b')) { 210 | console.log('Key "b" exists in the Map!'); 211 | } else { 212 | console.log('Key "b" does not exist in the Map.'); 213 | } 214 | ``` 215 | 216 | In this example, `myMap.has('b')` checks if the key `'b'` exists in the Map `myMap`. If it exists, it returns `true`, otherwise `false`. 217 | 218 | ::: tip 219 | - To check if a key exists in a Map in JavaScript, use the `has()` method. 220 | ::: 221 | 222 | ## 9. How to remove a key from a Map in JavaScript? 223 | 224 | In JavaScript, you can remove a key from a Map using the `delete` method. This method allows you to delete the entry associated with a specific key. Here's a simple example: 225 | 226 | ```javascript 227 | // Creating a Map 228 | let myMap = new Map(); 229 | 230 | // Adding some key-value pairs 231 | myMap.set('key1', 'value1'); 232 | myMap.set('key2', 'value2'); 233 | myMap.set('key3', 'value3'); 234 | 235 | // Removing a key from the Map 236 | myMap.delete('key2'); 237 | 238 | console.log(myMap); // Output: Map(2) { 'key1' => 'value1', 'key3' => 'value3' } 239 | ``` 240 | 241 | In this example, the key `'key2'` is removed from the Map using the `delete` method. After deletion, only `'key1'` and `'key3'` remain in the Map. 242 | 243 | ::: tip 244 | - To remove a key from a Map in JavaScript, use the `delete` method. 245 | ::: 246 | 247 | ## 10. How to iterate over a Map in JavaScript? 248 | 249 | To iterate over a Map in JavaScript, you can use the `Map.prototype.forEach()` method. This method executes a provided function once for each key-value pair in the Map, in insertion order. Here's a simple example: 250 | 251 | ```javascript 252 | // Creating a new Map 253 | let myMap = new Map(); 254 | 255 | // Adding key-value pairs to the Map 256 | myMap.set("key1", "value1"); 257 | myMap.set("key2", "value2"); 258 | myMap.set("key3", "value3"); 259 | 260 | // Iterating over the Map using forEach 261 | myMap.forEach((value, key) => { 262 | console.log(`Key: ${key}, Value: ${value}`); 263 | }); 264 | ``` 265 | 266 | This code creates a Map `myMap`, adds some key-value pairs to it, and then iterates over each pair using `forEach()`, printing out the key and value for each pair. 267 | 268 | ::: tip 269 | - To iterate over a Map in JavaScript, use the `Map.prototype.forEach()` method. 270 | ::: 271 | 272 | ## 11. How to convert an Object to a Map in JavaScript? 273 | 274 | To convert an object to a map in JavaScript, you can use the `Map` constructor along with the `Object.entries()` method. First, you need to get an array of key-value pairs from the object using `Object.entries()`, then you can pass this array to the `Map` constructor. Here's a simple code example: 275 | 276 | ```javascript 277 | // Object to be converted to a Map 278 | const myObject = { 279 | key1: 'value1', 280 | key2: 'value2', 281 | key3: 'value3' 282 | }; 283 | 284 | // Converting object to Map 285 | const myMap = new Map(Object.entries(myObject)); 286 | 287 | // Output the Map 288 | console.log(myMap); 289 | ``` 290 | 291 | In this code, `Object.entries(myObject)` converts the object `myObject` into an array of key-value pairs, which is then passed to the `Map` constructor to create a map `myMap`. 292 | 293 | ::: tip 294 | - To convert an object to a Map in JavaScript, use the `Map` constructor along with `Object.entries()`. 295 | ::: 296 | 297 | ## 12. How to convert a Map to an Object in JavaScript? 298 | 299 | To convert a Map to an Object in JavaScript, you can use a simple approach by iterating over the Map entries and constructing a new Object with the same key-value pairs. Here's a sample code demonstrating this: 300 | 301 | ```javascript 302 | // Sample Map 303 | let myMap = new Map(); 304 | myMap.set('a', 1); 305 | myMap.set('b', 2); 306 | myMap.set('c', 3); 307 | 308 | // Convert Map to Object 309 | let myObject = {}; 310 | for (let [key, value] of myMap) { 311 | myObject[key] = value; 312 | } 313 | 314 | console.log(myObject); // Output: { a: 1, b: 2, c: 3 } 315 | ``` 316 | 317 | In this code, we initialize a Map called `myMap` with some key-value pairs. Then, we create an empty Object `myObject`. Next, we iterate over each entry in `myMap` using a `for...of` loop and assign each key-value pair to `myObject`. Finally, we log `myObject`, which now contains the same data as the original Map but in the form of an Object. 318 | 319 | ::: tip 320 | - To convert a Map to an Object in JavaScript, iterate over the Map entries and construct a new Object with the same key-value pairs. 321 | - You can use a `for...of` loop to iterate over the Map entries and assign them to the Object. 322 | ::: 323 | 324 | ## 13. What are the differences between objects and maps in JavaScript? 325 | 326 | In JavaScript, both objects and maps are used to store data, but they have some differences. Objects are collections of key-value pairs where keys are strings or symbols, and values can be of any data type. Objects are widely used and have built-in methods for manipulation. On the other hand, maps are collections of key-value pairs where keys can be of any data type, not just strings or symbols. Maps provide more flexibility in using different types of data as keys, and they maintain the order of insertion, which objects do not. Here's a small sample code illustrating the creation of an object and a map: 327 | 328 | ```javascript 329 | // Object 330 | let myObject = { 331 | name: 'John', 332 | age: 30, 333 | }; 334 | 335 | // Map 336 | let myMap = new Map(); 337 | myMap.set('name', 'John'); 338 | myMap.set('age', 30); 339 | ``` 340 | 341 | In this code, `myObject` is an object with keys `'name'` and `'age'`, while `myMap` is a map with the same key-value pairs. 342 | 343 | ::: tip 344 | - Objects are collections of key-value pairs where keys are strings or symbols, and values can be of any data type. 345 | - Maps are collections of key-value pairs where keys can be of any data type, and they maintain the order of insertion. 346 | ::: 347 | -------------------------------------------------------------------------------- /docs/javascript/soon.md: -------------------------------------------------------------------------------- 1 | # Coming soon 2 | 3 | ::: info 4 | Coming soon 5 | ::: 6 | -------------------------------------------------------------------------------- /docs/javascript/variables.md: -------------------------------------------------------------------------------- 1 | # Javascript Variables and Scope 2 | 3 | ## 1. What are variables in javascript? 4 | 5 | In JavaScript, variables are like containers that hold different kinds of information, such as numbers, texts, or true/false values. They're used to store data that can change or be manipulated throughout a program. When we create a variable, we give it a name and assign a value to it using the '=' sign. This value can be updated or changed as needed during the program's execution. Variables make it easier for developers to work with and manage data within their code, helping to create dynamic and interactive web applications. 6 | 7 | ::: tip 8 | - Variables in JavaScript are containers for storing data. 9 | - They can hold various types of information such as numbers, strings (text), boolean values (true/false), arrays, objects, and more. 10 | - Values can be assigned to variables using the assignment operator '='. 11 | - The value stored in a variable can be changed or updated throughout the program's execution. 12 | ::: 13 | 14 | ## 2. What are the different variable types in JavaScript? 15 | 16 | In JavaScript, variable types are the different kinds of data that a variable can hold. There are several types, including numbers (like `5` or `3.14`), strings (like `hello` or `world`), booleans (`true` or `false), arrays (lists of values), objects (collections of key-value pairs), and more. Each type behaves differently and can be used for different purposes in a JavaScript program. For example, numbers are used for mathematical operations, strings are used for text, and booleans are used for making decisions in code. Understanding variable types is important for writing effective and functional JavaScript programs. 17 | 18 | ::: tip 19 | - Number: Represents numeric values like integers or floating-point numbers. 20 | - String: Represents sequences of characters, enclosed in single or double quotes. 21 | - Boolean: Represents true or false values, used for logical operations. 22 | - Array: Represents ordered collections of values, accessed by index. 23 | - Object: Represents collections of key-value pairs, used for storing structured data. 24 | - Null: Represents the intentional absence of any object value. 25 | - Undefined: Represents variables that have been declared but not initialized with a value. 26 | - Symbol: Represents unique identifiers for object properties. 27 | - BigInt: Represents integers with arbitrary precision, useful for handling large numbers. 28 | ::: 29 | 30 | ## 3. How to declare variables in JavaScript? 31 | 32 | In JavaScript, you declare variables using the `var`, `let`, or `const` keywords followed by the name you want to give to the variable. Here's a simple example: 33 | 34 | ```javascript 35 | var myVar = 10; 36 | let myLet = "Hello"; 37 | const myConst = true; 38 | ``` 39 | 40 | In this code, `myVar` is a variable declared with `var`, `myLet` with `let`, and `myConst` with `const`. `var` is used for declaring variables with function scope, `let` is used for block scope variables that can be reassigned, and `const` is used for constants whose values cannot be reassigned. 41 | 42 | ::: tip 43 | - Use the `var`, `let`, or `const` keyword to declare a variable. 44 | - Follow the keyword with the name you want to give to the variable. 45 | - Assign a value to the variable using the `=` operator. 46 | - Optionally, you can initialize the variable with a value. 47 | ::: 48 | 49 | ## 4. What are the differences between `var`, `let`, and `const` in JavaScript? 50 | 51 | In JavaScript, `var`, `let`, and `const` are all used to declare variables, but they have some differences. `var` is the oldest way to declare variables and has function scope. It means it's accessible throughout the entire function where it's declared. `let` and `const` are newer and have block scope, meaning they're only accessible within the block of code where they're defined (like within loops or if statements). The difference between `let` and `const` is that variables declared with `let` can be reassigned later, while variables declared with `const` cannot be reassigned after they're initially given a value. So, `let` is for variables that might change, while `const` is for ones that won't. 52 | 53 | ::: tip 54 | - `var`: 55 | - Oldest way to declare variables. 56 | - Has function scope. 57 | - Can be accessed throughout the entire function where it's declared. 58 | 59 | - `let`: 60 | - Introduced later than `var`. 61 | - Has block scope. 62 | - Limited to the block of code where it's defined (like within loops or if statements). 63 | - Can be reassigned after declaration. 64 | 65 | - `const`: 66 | - Also introduced later than `var`. 67 | - Has block scope like `let`. 68 | - Cannot be reassigned after declaration. 69 | - Useful for declaring variables that won't change their value. 70 | ::: 71 | 72 | ## 5. What are primitive and referenced types in JavaScript? 73 | 74 | In JavaScript, primitive types are basic data types like numbers, strings, booleans, null, and undefined. They hold simple values directly. For example, a number like `5` or a string like `hello` are primitive types. Referenced types, on the other hand, are more complex data types like objects and arrays. They hold collections of data and are referenced by memory address. For instance, an object like `{ name: "John", age: 25 }` or an array like `[1, 2, 3]` are referenced types. When you work with primitive types, you manipulate the actual value, whereas with referenced types, you manipulate the reference to the value's location in memory. 75 | 76 | ::: tip 77 | - **Primitive types**: 78 | - Basic data types like numbers, strings, booleans, null, and undefined. 79 | - Hold simple values directly. 80 | - **Referenced types**: 81 | - Complex data types like objects and arrays. 82 | - Hold collections of data and are referenced by memory address. 83 | - **Difference**: 84 | - When working with primitive types, you manipulate the actual value. 85 | - With referenced types, you manipulate the reference to the value's location in memory. 86 | ::: 87 | 88 | ## 6. What is the list of primitive types in JavaScript? 89 | 90 | In JavaScript, there are several primitive types. These are basic types of data that the language recognizes. The list includes string, which is for text; number, for numerical values; bigInt, for handling large integers; boolean, which represents true or false values; null, used to signify the absence of any value; undefined, which indicates that a variable has been declared but hasn't been assigned a value yet; and symbol, which is used to create unique identifiers for object properties. These types are the building blocks for creating and manipulating data in JavaScript programs. 91 | 92 | ::: tip 93 | - String: Represents text data. 94 | - Number: Used for numerical values. 95 | - BigInt: Handles large integers. 96 | - Boolean: Represents true or false values. 97 | - Null: Signifies the absence of any value. 98 | - Undefined: Indicates a variable declared but not assigned a value. 99 | - Symbol: Creates unique identifiers for object properties. 100 | ::: 101 | 102 | ## 7. What is `typeof` in JavaScript? 103 | 104 | In JavaScript, `typeof` is a special operator that helps you figure out the type of a value or a variable. It returns a string indicating the type of the operand. For example, if you want to know if a variable named `x` is a number, you can use `typeof x`. It will return `'number'` if `x` is a number. Similarly, if you have a variable `name` and you want to check if it's a string, you can use `typeof name`, and it will return `'string'` if `name` is indeed a string. It's handy when you want to perform different actions based on the type of data you're dealing with in your JavaScript code. 105 | 106 | ::: tip 107 | - `typeof` is a special operator in JavaScript. 108 | - It helps to determine the type of a value or variable. 109 | - It returns a string indicating the type of the operand. 110 | ::: 111 | 112 | ## 8. What are `typeof` different data types in JavaScript? 113 | 114 | In JavaScript, `typeof` is a keyword used to find out the type of a value. Here's a simple explanation for each type: 115 | 116 | - `string`: It represents text. For example: 117 | ```javascript 118 | typeof "hello"; // Output: "string" 119 | ``` 120 | 121 | - `number`: It represents numeric values, like integers or decimals. For example: 122 | ```javascript 123 | typeof 42; // Output: "number" 124 | ``` 125 | 126 | - `bigInt`: It represents large integer values. For example: 127 | ```javascript 128 | typeof 123n; // Output: "bigint" 129 | ``` 130 | 131 | - `boolean`: It represents true or false values. For example: 132 | ```javascript 133 | typeof true; // Output: "boolean" 134 | ``` 135 | 136 | - `null`: It represents an intentional absence of any value. For example: 137 | ```javascript 138 | typeof null; // Output: "object" (This is a quirk in JavaScript) 139 | ``` 140 | 141 | - `undefined`: It represents a variable that has been declared but not assigned a value. For example: 142 | ```javascript 143 | let x; 144 | typeof x; // Output: "undefined" 145 | ``` 146 | 147 | - `symbol`: It represents unique identifiers. For example: 148 | ```javascript 149 | typeof Symbol("foo"); // Output: "symbol" 150 | ``` 151 | 152 | - `object`: It represents collections of data. For example: 153 | ```javascript 154 | typeof { key: "value" }; // Output: "object" 155 | ``` 156 | 157 | - `function`: It represents a block of reusable code. For example: 158 | ```javascript 159 | typeof function() {}; // Output: "function" 160 | ``` 161 | 162 | These examples demonstrate how `typeof` works with different data types in JavaScript. 163 | 164 | ::: tip 165 | - `string`: Represents text. Example: `typeof "hello"; // Output: "string"` 166 | - `number`: Represents numeric values, like integers or decimals. Example: `typeof 42; // Output: "number"` 167 | - `bigInt`: Represents large integer values. Example: `typeof 123n; // Output: "bigint"` 168 | - `boolean`: Represents true or false values. Example: `typeof true; // Output: "boolean"` 169 | - `null`: Represents an intentional absence of any value. Example: `typeof null; // Output: "object"` (This is a quirk in JavaScript) 170 | - `undefined`: Represents a variable that has been declared but not assigned a value. Example: `let x; typeof x; // Output: "undefined"` 171 | - `symbol`: Represents unique identifiers. Example: `typeof Symbol("foo"); // Output: "symbol"` 172 | - `object`: Represents collections of data. Example: `typeof { key: "value" }; // Output: "object"` 173 | - `function`: Represents a block of reusable code. Example: `typeof function() {}; // Output: "function"` 174 | ::: 175 | 176 | ## 9. What are the differences between `null` and `undefined` in JavaScript? 177 | 178 | In JavaScript, `null` and `undefined` are both special values that represent the absence of meaningful data, but they're used in slightly different ways. `Undefined` means a variable has been declared but has not been assigned a value yet. It's like an empty box - there's nothing inside it. On the other hand, `null` is an explicitly assigned value that represents nothing or no value. It's like having a box, but deliberately putting nothing in it. So, while both represent emptiness, `undefined` usually indicates a variable that hasn't been initialized, while `null` is typically assigned to indicate no value on purpose. 179 | 180 | ::: tip 181 | - Undefined indicates that a variable has been declared but not assigned a value. 182 | - Null represents an intentional absence of any value. 183 | ::: 184 | 185 | ## 10. What is scope in JavaScript? 186 | 187 | In JavaScript, scopes define where variables are accessible or visible within your code. When you declare a variable, its scope determines where you can use it. There are mainly two types of scopes: global and local. Global scope means the variable can be accessed from anywhere in your code, while local scope means it's only accessible within a specific block of code, like inside a function. Here's a simple example: 188 | 189 | ```javascript {2,6} 190 | // Global scope 191 | let globalVar = 10; 192 | 193 | function myFunction() { 194 | // Local scope 195 | let localVar = 20; 196 | console.log(globalVar); // Accessible 197 | console.log(localVar); // Accessible 198 | } 199 | 200 | console.log(globalVar); // Accessible 201 | console.log(localVar); // Not accessible (will throw an error) 202 | ``` 203 | 204 | In this example, `globalVar` is accessible both inside and outside the function because it's declared in the global scope. However, `localVar` is only accessible inside the function where it's declared. 205 | 206 | ::: tip 207 | - Scopes in JavaScript define where variables are accessible in your code. 208 | - Two main types of scopes: global and local. 209 | - Global scope: Variables can be accessed from anywhere in the code. 210 | - Local scope: Variables are only accessible within a specific block of code, like inside a function. 211 | - Accessing variables outside their scope results in errors. 212 | ::: 213 | 214 | ## 11. Which blocks create a scope in JavaScript? 215 | 216 | In JavaScript, blocks like functions, loops (like `for` or `while`), and conditional statements (like `if` or `switch`) create what's called a scope. This means that any variables declared inside these blocks are only accessible within that block. Here's a simple example: 217 | 218 | ```javascript {2-5,9-11,15-18} 219 | // Function block scope 220 | function myFunction() { 221 | let x = 10; 222 | console.log(x); // Output: 10 223 | } 224 | console.log(x); // Output: ReferenceError: x is not defined 225 | 226 | // Loop block scope 227 | for (let i = 0; i < 3; i++) { 228 | console.log(i); // Output: 0, 1, 2 229 | } 230 | console.log(i); // Output: ReferenceError: i is not defined 231 | 232 | // Conditional block scope 233 | if (true) { 234 | let y = 20; 235 | console.log(y); // Output: 20 236 | } 237 | console.log(y); // Output: ReferenceError: y is not defined 238 | ``` 239 | 240 | In each of these examples, the variables `x`, `i`, and `y` are only accessible within their respective blocks. If you try to access them outside of those blocks, you'll get an error. 241 | 242 | ::: tip 243 | - Functions: Variables declared inside a function block are accessible only within that function. 244 | - Loops (like `for` or `while`): Variables declared within loop blocks are limited to the scope of that loop. 245 | - Conditional statements (like `if` or `switch`): Variables declared inside conditional blocks are scoped to those conditionals. 246 | ::: 247 | 248 | ## 12. Why is it recommended not to use `var` in JavaScript? 249 | 250 | Using `var` in JavaScript is not recommended because it has a scope that can sometimes be confusing. When you declare a variable with `var`, it can be hoisted to the top of its scope, meaning the variable declaration is moved to the top of the function or global scope. This can lead to unexpected behavior and bugs in your code. Additionally, `var` doesn't respect block scope, which means variables declared inside blocks like if statements or loops can leak out of those blocks. Instead, it's better to use `let` and `const`, introduced in ES6, which have block scope and provide clearer intentions for your code. Here's a simple example: 251 | 252 | ```javascript {3-5,12-14} 253 | // Using var 254 | function exampleVar() { 255 | if (true) { 256 | var message = "Hello!"; 257 | } 258 | console.log(message); // Outputs: Hello! 259 | } 260 | exampleVar(); 261 | 262 | // Using let 263 | function exampleLet() { 264 | if (true) { 265 | let message = "Hello!"; 266 | } 267 | console.log(message); // Throws an error: message is not defined 268 | } 269 | exampleLet(); 270 | ``` 271 | 272 | In the first example with `var`, `message` is accessible outside of the if block, which can lead to unintended consequences. In the second example with `let`, `message` is only accessible within the if block, providing clearer scoping. 273 | 274 | ::: tip 275 | - `var` has function-level scope, which can lead to unexpected behavior due to hoisting, where variable declarations are moved to the top of their scope. 276 | - Variables declared with `var` can be accessed outside of their intended scope, such as leaking out of if statements or loops. 277 | - `let` and `const`, introduced in ES6, offer block-level scoping, making code more predictable and easier to understand. 278 | ::: 279 | 280 | ## 13. What is closure in JavaScript? 281 | 282 | In JavaScript, closure is when a function remembers the variables outside of it, even after the function finishes executing. This means that the function has access to those variables even though they are not directly inside it. Here's a simple example: 283 | 284 | ```javascript 285 | function outerFunction() { 286 | let outerVariable = 'I am outside!'; 287 | 288 | function innerFunction() { 289 | console.log(outerVariable); // This will print 'I am outside!' even though outerVariable is not directly inside innerFunction 290 | } 291 | 292 | return innerFunction; 293 | } 294 | 295 | let closureExample = outerFunction(); 296 | closureExample(); // This will print 'I am outside!' because innerFunction still has access to outerVariable due to closure. 297 | ``` 298 | 299 | In this code, `innerFunction` can access the `outerVariable` even after `outerFunction` has finished executing. This is because `innerFunction` forms a closure over the `outerVariable`, meaning it retains access to it. 300 | 301 | ::: tip 302 | - Closure in JavaScript means a function retains access to variables from its outer scope even after the outer function has finished executing. 303 | - It allows functions to access and manipulate variables that are not directly within their own scope. 304 | - This behavior enables powerful programming patterns like encapsulation and data privacy. 305 | ::: 306 | 307 | ## 14. What is Hoisting? 308 | 309 | Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, regardless of where they are declared in the code. When a variable or function is hoisted, it means they're available for use before they're actually declared in the code. 310 | 311 | For example, let's look at how var, let, and const behave differently when hoisted: 312 | 313 | ```javascript 314 | console.log(x); // undefined 315 | var x = 5; 316 | 317 | console.log(y); // ReferenceError: Cannot access 'y' before initialization 318 | let y = 10; 319 | 320 | console.log(z); // ReferenceError: Cannot access 'z' before initialization 321 | const z = 15; 322 | ``` 323 | 324 | With var, the declaration is hoisted, but the assignment isn't. So, `x` is hoisted and initialized as undefined. With let and const, the variable is hoisted, but it's not initialized, resulting in a ReferenceError when trying to access it before initialization. 325 | 326 | Function declarations are fully hoisted, meaning both the declaration and the function definition are moved to the top of the scope, allowing you to call the function before it's declared: 327 | 328 | ```javascript 329 | hello(); // "Hello!" 330 | 331 | function hello() { 332 | console.log("Hello!"); 333 | } 334 | ``` 335 | 336 | However, function expressions aren't hoisted in the same way. Only the variable declaration gets hoisted, not the function assignment: 337 | 338 | ```javascript 339 | hello(); // TypeError: hello is not a function 340 | 341 | const hello = function() { 342 | console.log("Hello!"); 343 | }; 344 | ``` 345 | 346 | In this case, `hello` is hoisted as undefined, but since it's not yet a function, trying to call it results in a TypeError. 347 | 348 | ::: tip 349 | - **Hoisting**: JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation. 350 | - **Hoisting with var**: Variable declaration is hoisted, but assignment isn't. Variable is initialized as undefined. 351 | - **Hoisting with let and const**: Variable declaration is hoisted, but not initialized, resulting in a ReferenceError when accessed before initialization. 352 | - **Hoisting with function declarations**: Both declaration and function definition are fully hoisted. 353 | - **Hoisting with function expressions**: Only variable declaration is hoisted, not the function assignment. 354 | ::: 355 | -------------------------------------------------------------------------------- /docs/react/advanced.md: -------------------------------------------------------------------------------- 1 | # React Advanced 2 | 3 | ## What is React DOM? 4 | 5 | React DOM is a library in React.js that helps in managing and manipulating the Document Object Model (DOM) of web pages. The DOM represents the structure of a webpage as a tree of objects, allowing programs to interact with the page's content. React DOM makes it easier for developers to create interactive user interfaces by efficiently updating and rendering the DOM elements based on changes in the application's state. In simpler terms, React DOM helps React applications to show and change what you see on a webpage without having to reload the entire page. 6 | 7 | ::: tip 8 | - React DOM is a library in React.js. 9 | - It manages and manipulates the Document Object Model (DOM) of web pages. 10 | ::: 11 | 12 | ## What are the differences between React and React DOM? 13 | 14 | React is a JavaScript library used for building user interfaces (UIs) for web applications. It's like a toolbox with tools to create and manage components, handle state, and deal with events efficiently. On the other hand, React DOM is a specific part of React that deals with rendering those UI components to the web browser. Think of React as the brains behind how things work, while React DOM is responsible for showing those things on the screen. So, React helps you build the UI, and React DOM helps you display it in the browser. They work together to make web development easier and more organized. 15 | 16 | ::: tip 17 | - React helps in creating and managing components, handling state, and managing events efficiently. 18 | - React DOM is a specific part of React. 19 | - React DOM is responsible for rendering UI components to the web browser. 20 | ::: 21 | 22 | ## What is `lazy` in react? 23 | 24 | In React, `lazy` refers to a technique used to improve performance by loading components only when they are needed, rather than loading them all at once. It's like postponing the loading until it's necessary, which can make your app faster because it doesn't have to load everything upfront. For example, let's say you have a large component that's only needed when a user clicks on a specific button. Instead of loading that component when the page loads, you can lazy load it so that it's only loaded when the button is clicked. Here's a simple code snippet demonstrating lazy loading in React: 25 | 26 | ```jsx {4,10-12} 27 | import { lazy, Suspense } from 'react'; 28 | 29 | // Lazy loading the component 30 | const LazyComponent = lazy(() => import('./LazyComponent')); 31 | 32 | // App component 33 | const App = () => { 34 | return ( 35 |
36 | Loading...
}> 37 | 38 | 39 | 40 | ); 41 | }; 42 | ``` 43 | 44 | In this code, `LazyComponent` is loaded lazily using the `lazy` function from React. When `LazyComponent` is needed, React will load it asynchronously. The `Suspense` component is used to show a fallback UI (in this case, 'Loading...') while the component is being loaded. 45 | 46 | ::: tip 47 | - In React, `lazy` helps improve performance by loading components only when they're needed. 48 | - It delays loading components until they're required, making the app faster as it doesn't load everything upfront. 49 | - A fallback UI can be displayed using the `Suspense` component while the lazy-loaded component is being loaded asynchronously. 50 | ::: 51 | 52 | ## What is `Suspense` in react? 53 | 54 | In React, suspense is a feature that helps manage asynchronous operations, like fetching data or code-splitting. When your app needs to load something asynchronously, suspense lets you show a fallback UI (like a loading spinner) until the data or code is ready. It's like telling React to hold on for a moment until everything is prepared, so you can present a smooth experience to your users without freezing or showing blank screens. Suspense keeps your app responsive and ensures users aren't left waiting without any feedback. 55 | 56 | ::: tip 57 | - Suspense in React manages asynchronous operations. 58 | - Suspense allows you to display a fallback UI (like a loading spinner) while waiting for data or code to load. 59 | - It ensures your app remains responsive and provides feedback to users during loading processes. 60 | - Overall, suspense enhances user experience by preventing freezing or blank screens. 61 | ::: 62 | 63 | 64 | ## What is `startTransition` in react? 65 | 66 | In React, `startTransition` is a function used to schedule a low-priority update to the user interface. It tells React to delay rendering the changes until the browser is idle, which helps to keep the app responsive. This function is especially useful when you have a large amount of work to do in response to a user interaction, but you want to ensure that the app remains smooth and responsive during that time. Here's a simple example code snippet demonstrating the usage of `startTransition`: 67 | 68 | ```jsx {8-10} 69 | import { startTransition, useState } from 'react'; 70 | 71 | function MyComponent() { 72 | const [count, setCount] = useState(0); 73 | 74 | const handleClick = () => { 75 | // Use startTransition to delay rendering changes 76 | startTransition(() => { 77 | setCount(count + 1); // Update count 78 | }); 79 | }; 80 | 81 | return ( 82 |
83 |

Count: {count}

84 | 85 |
86 | ); 87 | } 88 | ``` 89 | 90 | In this example, when the button is clicked, `startTransition` is used to delay the rendering of the updated count value until the browser is idle, ensuring a smooth user experience. 91 | 92 | ::: tip 93 | - `startTransition` in React is a function used to schedule low-priority updates to the user interface. 94 | - It helps in delaying rendering changes until the browser is idle, maintaining a smooth and responsive app. 95 | - Particularly useful for scenarios where there's a significant amount of work to be done in response to user interactions. 96 | - Usage involves wrapping the state updates or component changes within `startTransition` to defer rendering. 97 | - Ensures that the app remains responsive even during heavy processing tasks. 98 | ::: 99 | 100 | ## What is `createRoot` in react? 101 | 102 | In React, `createRoot` is a method used to render a React application at the top level of the DOM (Document Object Model). With `createRoot`, you can create a root ReactDOM container for your React application. Here's a simple example: 103 | 104 | ```jsx 105 | import { createRoot } from 'react-dom'; 106 | 107 | // Create a root container for your React application 108 | const root = createRoot(document.getElementById('root')); 109 | 110 | // Render your main component inside the root container 111 | root.render(); 112 | ``` 113 | 114 | In this code, `createRoot` creates a root container in the HTML element with the ID `root`, and then the `` component is rendered inside this root container. 115 | 116 | ::: tip 117 | - `createRoot` is a method in React used for rendering React applications at the top level of the DOM. 118 | - This method creates a root ReactDOM container for the React application. 119 | ::: 120 | 121 | ## What is `hydrateRoot` in react? 122 | 123 | In React, hydrateRoot is a method used to render and hydrate a React application on the client-side. It's similar to createRoot, but it's specifically designed for server-side rendering (SSR) or rehydrating a server-rendered HTML on the client-side. When you render a React app on the server, it generates HTML markup, and when it's sent to the client, hydrateRoot attaches event listeners and sets up the necessary components to make the page interactive. Here's a simple example: 124 | 125 | ```jsx {8} 126 | import { hydrateRoot } from 'react-dom'; 127 | 128 | const App = () => { 129 | return
Hello, World!
; 130 | }; 131 | 132 | // Assuming 'appRoot' is the root element in your HTML where you want to render the React app. 133 | hydrateRoot(document.getElementById('appRoot'), ); 134 | ``` 135 | 136 | In this code, the App component is rendered and hydrated onto the HTML element with the id `appRoot`. It means React will take over the management of that part of the DOM and make it interactive based on the React component's logic. 137 | 138 | ::: tip 139 | - `hydrateRoot` in React is a method used for rendering and hydrating a React application on the client-side. 140 | - It's specifically utilized for server-side rendering (SSR) or rehydrating server-rendered HTML on the client-side. 141 | - When you render a React app on the server, it generates HTML markup, and `hydrateRoot` attaches event listeners and sets up components to make the page interactive. 142 | ::: 143 | 144 | ## What is `renderToString` in react? 145 | 146 | In React, `renderToString` is a function used to convert React components into plain HTML strings. This is often needed when you're working with server-side rendering (SSR) or static site generation (SSG) in React applications. It's useful for scenarios where you want search engines to crawl your content or for improving initial load times by serving pre-rendered HTML to the client. Here's a simple example code showing how `renderToString` is used: 147 | 148 | ```jsx {12} 149 | import { renderToString } from 'react-dom/server'; 150 | 151 | const MyComponent = () => { 152 | return ( 153 |
154 |

Hello, World!

155 |

This is a simple React component.

156 |
157 | ); 158 | }; 159 | 160 | const htmlString = renderToString(); 161 | 162 | console.log(htmlString); // Output: "

Hello, World!

This is a simple React component.

" 163 | ``` 164 | 165 | In this code, `MyComponent` is a simple React component, and `renderToString` converts it into a string of HTML elements. 166 | 167 | ::: tip 168 | - `renderToString` in React is a function used to convert React components into plain HTML strings. 169 | - It is commonly used for server-side rendering (SSR) or static site generation (SSG) in React applications. 170 | - Helps improve search engine optimization (SEO) by providing pre-rendered HTML content. 171 | - Useful for faster initial load times by serving pre-rendered HTML to clients. 172 | ::: 173 | -------------------------------------------------------------------------------- /docs/react/components.md: -------------------------------------------------------------------------------- 1 | # React Components 2 | 3 | 4 | ## What are React Components? 5 | 6 | React components are like building blocks for creating user interfaces in React. Think of them as reusable pieces of code that represent parts of a webpage or application. Each component can have its own functionality and appearance. For example, you might have a component for a button, another for a navigation bar, and so on. Here's a simple example of a React component that represents a basic button: 7 | 8 | ```jsx 9 | export const Button = () => { 10 | return ( 11 | 14 | ); 15 | } 16 | ``` 17 | 18 | In this code, we define a `Button` component that simply renders a button element with the text `Click me`. This component can be used anywhere in our React application by simply importing it and including it in our JSX code. 19 | 20 | ::: tip 21 | - React components are reusable building blocks for creating user interfaces. 22 | - Each component represents a specific part of a webpage or application. 23 | - Components can have their own functionality and appearance. 24 | - Components can be easily reused across different parts of an application. 25 | ::: 26 | 27 | ## Are components in react reusable? 28 | 29 | Yes, components in React are reusable. Think of them like building blocks you can use over and over again in different parts of your application. When you create a component, you're essentially making a custom piece of code that does a specific job. Once you've built it, you can use it wherever you need that functionality without having to rewrite the code each time. This saves time and makes your code easier to manage because you can just plug in the component wherever you need it instead of recreating it from scratch. So, yes, React components are indeed reusable! 30 | 31 | ::: tip 32 | - React components are reusable. 33 | - Components act like building blocks for your application. 34 | - Once created, components can be used multiple times in different parts of the application. 35 | ::: 36 | 37 | ## What are the differences between function components and class components? 38 | 39 | In React, function components and class components are two ways to create reusable parts of a user interface. The main difference between them is how you write them. 40 | 41 | Function components are written as regular JavaScript functions that take in props and return React elements. They are simpler and more concise, making them easier to understand and write. Here's a simple example: 42 | 43 | ```jsx 44 | export const FunctionComponent = () => { 45 | return

Hello, I'm a function component!

; 46 | } 47 | ``` 48 | 49 | On the other hand, class-based components are defined using ES6 classes and must extend the `React.Component` class. They can be more complex and verbose compared to function components. Here's a basic example: 50 | 51 | ```jsx 52 | class ClassComponent extends React.Component { 53 | render() { 54 | return

Hello, I'm a class component!

; 55 | } 56 | } 57 | 58 | export default ClassComponent; 59 | ``` 60 | 61 | Overall, both types of components achieve the same goal of building user interfaces in React, but they differ in syntax. 62 | 63 | ::: tip 64 | - Function components are written as regular JavaScript functions, while class-based components are defined using ES6 classes. 65 | - Function components are simpler and more concise compared to class-based components. 66 | - Function components are easier to understand and write due to their simplicity. 67 | - Both types of components serve the purpose of building user interfaces in React, but they differ in syntax. 68 | ::: 69 | 70 | ::: warning 71 | - You should avoid using class components because they are an older way of writing code in React. 72 | ::: 73 | 74 | ## Why should I avoid using class components? 75 | 76 | You should avoid using class components because they are an older way of writing code in React, which can make your code longer and more complicated. With newer versions of React, functional components with hooks are preferred because they are simpler, shorter, and easier to understand. Functional components also encourage better code organization and can improve performance in your applications. So, if you can, it's better to use functional components instead of class components in React. 77 | 78 | ::: tip 79 | - Class components are an older way of writing code in React. 80 | - They can make your code longer and more complex. 81 | - Functional components with hooks are preferred in newer versions of React. 82 | - Functional components are simpler, shorter, and easier to understand. 83 | - It's better to use functional components instead of class components in React. 84 | ::: 85 | 86 | ## What are props in components? 87 | 88 | In React, props in components are like messages that one part of your app can send to another. They're pieces of information passed from a parent component to a child component. Let's say you have a parent component called `ParentComponent` and a child component called `ChildComponent`. In `ParentComponent`, you can send a prop like this: 89 | 90 | ```jsx 91 | function ParentComponent() { 92 | return ( 93 | 94 | ); 95 | } 96 | ``` 97 | 98 | Then, in `ChildComponent`, you can receive and use this prop like this: 99 | 100 | ```jsx 101 | function ChildComponent(props) { 102 | return

{props.message}

; 103 | } 104 | ``` 105 | 106 | Here, `props` is an object containing all the props passed to the component. So, `props.message` would give you the message sent from `ParentComponent`. That's how props work in React components! 107 | 108 | ::: tip 109 | - Props in React components are like messages or data that can be passed from a parent component to a child component. 110 | - They allow for communication between different parts of a React application. 111 | - Props are received as a parameter in the component and are accessed through an object called `props`. 112 | ::: 113 | 114 | ## What are states in components? 115 | 116 | In React, states in components are like containers that hold data for the component. They help to manage and update information within the component. For example, imagine a simple counter component where you want to display a number that increments each time a button is clicked. You can use state to keep track of the count. Here's a basic example code: 117 | 118 | ```jsx {4,7-8} 119 | import { useState } from 'react'; 120 | 121 | function Counter() { 122 | const [count, setCount] = useState(0); 123 | return ( 124 |
125 |

Count: {count}

126 | 127 |
128 | ); 129 | } 130 | ``` 131 | 132 | In this example, `useState(0)` is used to declare a state variable named `count` with an initial value of 0. `setCount` is a function that allows you to update the value of `count`. When the button is clicked, it calls `setCount` to increment the count by 1, and React re-renders the component with the updated count value. 133 | 134 | ::: tip 135 | - States in components in React are containers for holding data within the component. 136 | - They help manage and update information dynamically. 137 | - Syntax: Utilize the `useState()` hook to declare a state variable and its initial value. 138 | - Use the setter function (`setCount`) returned by `useState()` to update the state. 139 | - React re-renders the component automatically when the state changes. 140 | ::: 141 | 142 | ## What is the difference between state and props? 143 | 144 | In React, the difference between state and props is important to understand. State is like a memory that each component can keep track of. It's data that can change over time, and when it does, React re-renders the component to reflect those changes. Props, on the other hand, are like parameters that you pass to a component when you first create it. They are immutable (which means they cannot be changed by the component itself) and are used to customize or configure a component when it's rendered. So, while state is internal and can change, props are external and can't be changed by the component receiving them. 145 | 146 | ::: tip 147 | - State acts like a memory within a component. 148 | - It Represents data that can change over time. 149 | - Changes to state trigger re-renders of the component. 150 | - Props are parameters passed to a component when it's created. 151 | - They are immutable data received from a parent component. 152 | - They used for customizing or configuring a component during rendering. 153 | - They cannot be changed by the component receiving them. 154 | ::: 155 | 156 | ## When should we use state and when should we use props? 157 | 158 | In React, we use `state` and `props` to manage and pass data around our components. We use `state` when we need to manage data within a component itself that can change over time, like user input or the result of an API call. `props`, short for properties, are used to pass data from a parent component to a child component. We use props when we want to share information from a parent component to its children. So, to decide when to use state or props, remember: state is for managing data within a component, and props are for passing data from parent to child components. 159 | 160 | ::: tip 161 | - Use `state` in React to manage data within a component itself. 162 | - State is suitable for managing data that can change over time, like user input or API responses. 163 | - Use `props` (properties) to pass data from a parent component to a child component. 164 | ::: 165 | 166 | ## How do we handle events in React? 167 | 168 | In React, handling events is like telling your app what to do when something happens, like clicking a button or typing in a text field. To handle events, you create special functions called event handlers. These functions are triggered when an event occurs, and they can perform tasks like updating data or changing what's shown on the screen. Here's a simple example of how you might handle a click event on a button in React: 169 | 170 | ```jsx {2-4,7} 171 | function Button() { 172 | const handleClick = () => { 173 | alert('Button clicked!'); 174 | } 175 | 176 | return ( 177 | 178 | ); 179 | } 180 | ``` 181 | 182 | In this code, we have a React component called `Button`. Inside this component, there's a function called `handleClick`, which simply shows an alert saying 'Button clicked!' when the button is clicked. 183 | 184 | ::: tip 185 | - In React, handling events means defining what happens when users interact with your app, like clicking a button. 186 | - To handle events, you create special functions called event handlers. 187 | - Event handlers can perform tasks like updating data or changing what's displayed on the screen. 188 | - In React, you attach event handlers to elements using special attributes like `onClick`, `onChange`, etc. 189 | ::: 190 | 191 | ## How to render different content based on certain conditions? 192 | 193 | In React components, you can render different content based on certain conditions using conditional rendering. This means you can show different things depending on what's happening in your app. One common way to do this is by using the `if` statement or the ternary operator `? :`. Here's a small example: 194 | 195 | ```jsx 196 | function MyComponent({ isLoggedIn }) { 197 | if (isLoggedIn) { 198 | return

Welcome back!

; 199 | } else { 200 | return

Please log in to continue.

; 201 | } 202 | } 203 | ``` 204 | or using the ternary operator: 205 | 206 | ```jsx 207 | function MyComponent({ isLoggedIn }) { 208 | return

{isLoggedIn ? "Welcome back!" : "Please log in to continue."}

; 209 | } 210 | ``` 211 | 212 | In this code, `isLoggedIn` is a prop that tells us whether the user is logged in or not. If `isLoggedIn` is `true`, it shows `Welcome back!`, and if it's `false`, it shows `Please log in to continue.` This way, the content changes based on the condition provided. 213 | 214 | ::: tip 215 | - In React components, you can render different content based on conditions using conditional rendering. 216 | - Common ways to do this include using the `if` statement or the ternary operator `? :`. 217 | - This allows content to dynamically change based on the provided conditions. 218 | ::: 219 | 220 | ## How to render list of items in react component? 221 | 222 | To render a list of items in a React component, you can use the `map` function. First, you need to have an array containing the items you want to render. Then, inside your component's render method, you can use the `map` function to iterate over each item in the array and return a JSX element for each item. Here's a small sample code demonstrating this: 223 | 224 | ```jsx {7-9} 225 | const MyComponent = () => { 226 | const items = ['Item 1', 'Item 2', 'Item 3']; 227 | return ( 228 |
229 |

List of Items:

230 |
    231 | {items.map((item, index) => ( 232 |
  • {item}
  • 233 | ))} 234 |
235 |
236 | ); 237 | }; 238 | ``` 239 | 240 | In this code, we have an array called `items` containing some sample items. Inside the `ul` element, we use `map` to iterate over each item in the array. For each item, we return a `li` element with the item's content. It's important to include a `key` prop when rendering lists in React to help React identify each list item uniquely. 241 | 242 | ::: tip 243 | - Inside your component's render method, use the `map` function to iterate over each item in the array. 244 | - For each item, return a JSX element (like `li` for a list item) containing the item's content. 245 | - Include a `key` prop for each rendered item to help React identify them uniquely. 246 | ::: 247 | 248 | ## What is `key` prop in react component? 249 | 250 | In React, the `key` prop is a special attribute that you can add to components when you're rendering lists of items. It helps React identify each item in the list uniquely. When you change, add, or remove items in a list, React uses the key prop to efficiently update the DOM without re-rendering the entire list. Here's a simple example: 251 | 252 | ```jsx {6} 253 | function MyListComponent() { 254 | const items = ['apple', 'banana', 'orange']; 255 | return ( 256 |
    257 | {items.map((item) => ( 258 |
  • {item}
  • 259 | ))} 260 |
261 | ); 262 | } 263 | ``` 264 | 265 | In this code, each list item (`
  • `) gets a unique key based on its index in the `items` array. This helps React keep track of each item properly when the list changes. 266 | 267 | ::: tip 268 | - The `key` prop in React components is used for identifying elements uniquely within a list. 269 | - It is particularly useful when rendering dynamic lists of items. 270 | - React uses the `key` prop to efficiently update the DOM when the list changes, avoiding unnecessary re-renders. 271 | - Each item in the list should have a unique `key` prop value. 272 | - Typically, the `key` prop is set using a unique identifier for each item, such as an ID from a database or the item's index in the list. 273 | - Using the `key prop helps React optimize rendering performance and maintain the component's state accurately. 274 | ::: 275 | 276 | ::: warning 277 | - Never use `index` as a key for list items. 278 | ::: 279 | 280 | ## What is `ref` in react components? 281 | 282 | In React components, `ref` is a special attribute used to access the DOM (Document Object Model) nodes or React elements created by JSX. It helps in interacting with these elements directly from the component. For example, if you want to focus on an input field or measure its dimensions, you can use refs. Here's a simple code snippet demonstrating the use of `ref` in a React component: 283 | 284 | ```jsx {4,6,10} 285 | import { useRef } from 'react'; 286 | 287 | const MyComponent = () => { 288 | const myRef = useRef(); 289 | const focusInput = () => { 290 | myRef.current.focus(); 291 | }; 292 | return ( 293 |
    294 | 295 | 296 |
    297 | ); 298 | }; 299 | ``` 300 | 301 | In this example, `useRef` hook is used to create a ref named `myRef`. This ref is attached to the input field using the `ref` attribute. Later, when the button is clicked, the `focusInput` function is called, which focuses on the input field using the `current` property of the ref. 302 | 303 | ::: tip 304 | - In React components, `ref` is a special attribute used to access DOM nodes or React elements created by JSX. 305 | - It facilitates direct interaction with these elements from within the component. 306 | - Common uses of `ref` include focusing on input fields, measuring dimensions, or accessing underlying DOM properties and methods. 307 | - To create a ref in a component, the `useRef` hook is used. 308 | - The ref is then attached to the desired element using the `ref` attribute. 309 | - Accessing the DOM node or React element is done through the `current` property of the ref. 310 | ::: 311 | 312 | ## What are forward refs? 313 | 314 | In React, forward refs allow a component to pass its ref down to a child component. This is useful when a parent component needs to access or control a specific element in its child component. Forwarding refs makes it easier to manage focus, trigger animations, or interact with DOM elements directly. Here's a simple example: 315 | 316 | ```jsx {3,16} 317 | import { forwardRef, useRef } from 'react'; 318 | 319 | const ChildComponent = forwardRef((props, ref) => { 320 | return ; 321 | }); 322 | 323 | const ParentComponent = () => { 324 | const inputRef = useRef(); 325 | 326 | const handleClick = () => { 327 | inputRef.current.focus(); 328 | }; 329 | 330 | return ( 331 |
    332 | 333 | 334 |
    335 | ); 336 | }; 337 | ``` 338 | 339 | In this example, `ChildComponent` forwards the `ref` to the `` element it renders. Then, in `ParentComponent`, we create a ref with `useRef()` and pass it to `ChildComponent`. This allows `ParentComponent` to access and control the `` element inside `ChildComponent`, for example, to focus it when a button is clicked. 340 | 341 | ::: tip 342 | - Forward refs in React allow a component to pass its ref down to a child component. 343 | - Useful for cases where a parent component needs to access or control a specific element in its child component. 344 | - Simplifies tasks like managing focus, triggering animations, or interacting with DOM elements directly. 345 | - Child component uses `forwardRef` to forward the ref to a specific DOM element, like an input field. 346 | ::: 347 | 348 | ## What are controlled components? 349 | 350 | Controlled components in web development are input elements like text fields or checkboxes whose values are controlled by the state of the application. This means that the value of the input is directly linked to a piece of state in the code, typically managed by a framework like React. In simpler terms, when you type something into a text field or select an option in a checkbox, the value you see is directly tied to a variable in the code. Here's a simple example in React: 351 | 352 | ```jsx {4,6-8,14-15} 353 | import { useState } from 'react'; 354 | 355 | function ControlledComponent() { 356 | const [inputValue, setInputValue] = useState(''); 357 | 358 | const handleChange = (event) => { 359 | setInputValue(event.target.value); 360 | }; 361 | 362 | return ( 363 |
    364 | 369 |

    You typed: {inputValue}

    370 |
    371 | ); 372 | } 373 | ``` 374 | 375 | In this code, the `inputValue` is a piece of state managed by React's `useState` hook. The `value` attribute of the `` element is set to this `inputValue`, making it a controlled component. When you type into the input field, the `handleChange` function updates the `inputValue`, which in turn updates what is displayed in the input field and the `

    ` tag below it. 376 | 377 | ::: tip 378 | - Controlled components in web development are input elements whose values are directly tied to the state of the application. 379 | - They are commonly used in frameworks like React to manage the state of user input. 380 | - When you type something into a controlled input field, the value is controlled by a variable in the code. 381 | - This allows for better control and manipulation of user input data. 382 | ::: 383 | 384 | ## What are uncontrolled components? 385 | 386 | In React, uncontrolled components are elements like input fields where their value isn't controlled by React state. Instead, they manage their own state internally. When using uncontrolled components, they refer to those where the value isn't controlled directly by React state but can still be accessed using refs. Here's a simple example of an uncontrolled input component using a ref in React: 387 | 388 | ```jsx {4,7,12} 389 | import { useRef } from 'react'; 390 | 391 | function UncontrolledComponent() { 392 | const inputRef = useRef(null); 393 | 394 | const handleClick = () => { 395 | console.log('Input value:', inputRef.current.value); 396 | }; 397 | 398 | return ( 399 |

    400 | 401 | 402 |
    403 | ); 404 | } 405 | ``` 406 | 407 | In this code, the input element doesn't rely on React state to control its value. Instead, it manages its value internally. We use a ref (`inputRef`) to access its current value when needed, like in the `handleClick` function. 408 | 409 | ::: tip 410 | - Uncontrolled components manage their own state internally, rather than relying on React state. 411 | - Refs are used to access the current value of the uncontrolled component when needed, such as in event handlers or other functions. 412 | ::: 413 | 414 | ## What are lifecycles in functional components? 415 | 416 | In React functional components, lifecycles are like the different stages a component goes through during its existence. They include creation, updating, and destruction. For instance, when a component is created, it may need to set up some initial state or fetch data from a server. During updates, it might react to changes in props or state by rerendering. And when a component is removed from the screen, it could clean up resources or unsubscribe from events. Here's a simple example of a functional component with a basic lifecycle: 417 | 418 | ```jsx {7,10,17} 419 | import { useEffect } from 'react'; 420 | 421 | function ExampleComponent() { 422 | const [count, setCount] = useState(0); 423 | 424 | useEffect(() => { 425 | // This runs when component is mounted 426 | console.log("Component is mounted"); 427 | 428 | // This return function is like componentWillUnmount 429 | return () => { 430 | console.log("Component is unmounted"); 431 | }; 432 | }, []); 433 | 434 | useEffect(() => { 435 | // This runs when count changes 436 | console.log(count); 437 | }, [count]); 438 | 439 | return ( 440 |
    441 |

    You clicked {count} times

    442 | 445 |
    446 | ); 447 | } 448 | ``` 449 | 450 | In this example, `useEffect` hook is used to manage lifecycle events. The first function inside `useEffect` runs when component is mounted, similar to `componentDidMount` in class components. The returned function inside `useEffect` acts like `componentWillUnmount`, executing cleanup when the component is unmounted. The second function inside `useEffect` runs when `count` changes, similar to `componentDidUpdate` in class components. 451 | 452 | ::: tip 453 | - Lifecycles in React functional components are stages a component goes through: creation, updating, and destruction. 454 | - Creation involves setting up initial state or fetching data. 455 | - Updating happens when props or state change, triggering rerendering. 456 | - Destruction occurs when a component is removed from the screen, allowing cleanup of resources. 457 | - An example of managing lifecycles in a functional component is using the `useEffect` hook, which combines `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` functionalities. 458 | ::: 459 | 460 | 461 | ## What are higher order components (HOCs)? 462 | 463 | Higher order components (HOCs) in React are like helper functions that enhance the capabilities of other components. They are functions that take a component and return a new component with added features. For example, imagine we have a simple functional component called `Button`. We can create a higher order component called `withColor` that adds a color property to the `Button`. Here's a basic example: 464 | 465 | ```jsx 466 | // Higher Order Component 467 | const withColor = (WrappedComponent, color) => { 468 | return (props) => ; 469 | }; 470 | 471 | // Original Button Component 472 | const Button = ({ color, onClick }) => ( 473 | 476 | ); 477 | 478 | // Button component enhanced with color 479 | const ColoredButton = withColor(Button, 'blue'); 480 | ``` 481 | 482 | In this example, `withColor` is a higher order component that takes `Button` and a color, then returns a new component `ColoredButton` which has the color property added to it. This allows us to reuse the color logic across multiple components. 483 | 484 | ::: tip 485 | - Higher order components (HOCs) in React are like helper functions that enhance the capabilities of other components. 486 | - They take a component and return a new component with added features. 487 | - HOCs are useful for reusing logic across multiple components. 488 | ::: 489 | 490 | 491 | ## What is `children` prop? 492 | 493 | In React, the `children` prop is a special prop that allows components to pass elements or content to other components nested within them. It's like a doorway through which a parent component can send information to its child components. For example, imagine a `Parent` component wrapping around a `Child` component. The Parent can pass some content or components to the Child using the `children` prop. Here's a simple code snippet to illustrate: 494 | 495 | ```jsx {4} 496 | const ParentComponent = () => { 497 | return ( 498 |
    499 | This is passed from Parent! 500 |
    501 | ); 502 | }; 503 | ``` 504 | 505 | ```jsx {1,5} 506 | const ChildComponent = ({ children }) => { 507 | return ( 508 |
    509 |

    This is the child component.

    510 |
    {children}
    511 |
    512 | ); 513 | }; 514 | ``` 515 | 516 | In this example, the content `This is passed from Parent!` gets sent from the ParentComponent to the ChildComponent through the `children` prop. Then, the ChildComponent can render this content wherever it wants within its own structure. 517 | 518 | ::: tip 519 | - In React, the `children` prop allows components to pass elements or content to other components nested within them. 520 | - The parent component can send information or components to its child components through the `children` prop. 521 | - Child components can access this content using the `children` prop and render it wherever needed within their structure. 522 | ::: 523 | 524 | 525 | ## How to set class and styles in react components? 526 | 527 | In React, setting classes and styles in components is pretty straightforward. You can set classes using the `className` attribute, which works similarly to HTML's `class` attribute. For styles, you can use the `style` attribute, passing in a JavaScript object where keys are CSS properties in camelCase and values are the styles you want to apply. Here's a simple example: 528 | 529 | ```jsx {2-6,9} 530 | const MyComponent = () => { 531 | const customStyle = { 532 | color: 'blue', 533 | fontSize: '18px', 534 | fontWeight: 'bold' 535 | }; 536 | 537 | return ( 538 |
    539 | Hello, World! 540 |
    541 | ); 542 | }; 543 | ``` 544 | 545 | In this code, the `div` element has a class of `myClass and custom styles defined by the `customStyle` object. 546 | 547 | ::: tip 548 | - To set classes in React components, use the `className` attribute, which functions like HTML's `class` attribute. 549 | - Define custom styles using the `style` attribute, passing in a JavaScript object where keys are CSS properties in camelCase and values are the styles you want to apply. 550 | ::: 551 | 552 | ## Why do we use `className` instead of `class`? 553 | 554 | In React, we use `className` instead of `class` because `class` is a reserved keyword in JavaScript used for defining classes in object-oriented programming. Since React code is written in JavaScript, using `class` directly could cause conflicts or confusion. So, to avoid this, React uses `className` to specify CSS classes for HTML elements. This way, we can style our components using CSS while avoiding any clashes with JavaScript's reserved keywords. Essentially, `className` serves the same purpose as `class` in HTML, allowing us to apply styles to elements. 555 | 556 | ::: tip 557 | - In React, `className` is used instead of `class`. 558 | - `class` is a reserved keyword in JavaScript for defining classes. 559 | ::: 560 | 561 | ## How to name components in react? 562 | 563 | In React, naming components is important for clarity and organization in your code. When naming components, it's best to use descriptive names that accurately reflect their purpose or functionality. Make sure to use PascalCase convention for component names, starting with a capital letter. For example, if you're creating a component for a button, you might name it `Button` or `SubmitButton` if it's specifically for submitting forms. Avoid generic names like `Component` or `Item that don't provide much insight into what the component does. Good naming helps you and other developers understand your code better and makes it easier to maintain and work with in the long run. 564 | 565 | ::: tip 566 | - Follow the PascalCase convention, starting with a capital letter. 567 | ::: 568 | 569 | ## What are fragments in react? 570 | 571 | In React, fragments are a way to group multiple elements together without adding extra nodes to the DOM. Normally, when you return multiple elements in React, you need to wrap them in a single parent element. Fragments allow you to avoid this by letting you return a group of elements as siblings. They're useful when you don't want to add an extra div or span just for the sake of structure. Here's a small sample code to illustrate: 572 | 573 | ```jsx 574 | function MyComponent() { 575 | return ( 576 | <> 577 |

    Hello

    578 |

    This is a paragraph.

    579 | 580 | ); 581 | } 582 | ``` 583 | 584 | In this example, the `` tag (`<>` and ``) is used as a wrapper around the `

    ` and `

    ` elements. It allows you to return multiple elements without introducing an unnecessary parent node in the DOM. 585 | 586 | ::: tip 587 | - Fragments in React are used to group multiple elements together without adding extra nodes to the DOM. 588 | - You can use the shorthand syntax `<>` and `` to create fragments, allowing you to return multiple elements cleanly. 589 | ::: 590 | 591 | -------------------------------------------------------------------------------- /docs/react/hooks.md: -------------------------------------------------------------------------------- 1 | # React Hooks 2 | 3 | ## What are react hooks? 4 | 5 | React hooks are a way to add features to functional components in React. They allow you to use state and other React features without writing a class. Think of them as tools that help you manage the state of your app and perform actions like fetching data from a server or handling user input more easily. With hooks, you can organize your code better and make it more reusable, making it simpler to create interactive and dynamic web applications. 6 | 7 | ::: tip 8 | - React hooks are tools for adding features to functional components in React. 9 | - They enable the use of state and other React features without writing a class. 10 | - Hooks help manage the state of the application and perform actions like fetching data or handling user input. 11 | ::: 12 | 13 | ## What are the most common hooks in react? 14 | 15 | In React, some of the most common hooks are useState(), useEffect(), and useContext(). The useState() hook is used to manage state within functional components, allowing you to store and update data dynamically. useEffect() is handy for performing side effects in functional components, like data fetching or subscriptions, after render. Lastly, useContext() helps access data globally across the component tree without prop drilling. These hooks simplify state management, side effects, and context handling in React applications, making development more efficient and organized. 16 | 17 | ::: tip 18 | - useState(): Manages state within functional components 19 | - useEffect(): Performs side effects like data fetching or subscriptions after render 20 | - useContext(): Accesses data globally across the component tree without prop drilling 21 | ::: 22 | 23 | ## What is `useState` in react? 24 | 25 | In React, useState is a hook used to add state to functional components. It allows you to create state variables and update them within your components. Here's a simple example of how to use useState: 26 | 27 | ```jsx {5} 28 | import { useState } from 'react'; 29 | 30 | function Counter() { 31 | // Declare a state variable named "count" and initialize it with the value 0 32 | const [count, setCount] = useState(0); 33 | 34 | return ( 35 |

    36 |

    You clicked {count} times

    37 | {/* When the button is clicked, call setCount to update the count state */} 38 | 41 |
    42 | ); 43 | } 44 | ``` 45 | 46 | In this code, `useState` is used to declare a state variable called `count` and initialize it with the value 0. The setCount function is used to update the value of count` when the button is clicked. 47 | 48 | ::: tip 49 | - `useState` is a hook in React. 50 | - It adds state management capability to functional components. 51 | - It allows you to create state variables and update them within components. 52 | - It takes an initial value as an argument and returns an array with the current state value and a function to update that value. 53 | - When the state is updated using the setter function , React re-renders the component to reflect the new state value. 54 | ::: 55 | 56 | ## What is `useEffect` in react? 57 | 58 | `useEffect` is a special function in React that allows you to perform side effects in your components. Side effects could be anything from fetching data, subscribing to events, or manually changing the DOM. It runs after every render, including the first one. This function takes two arguments: a callback function that represents the side effect you want to perform, and an optional array of dependencies. The dependencies array lets you control when the effect runs. If any of the values in the dependencies array change, the effect will run again. Here's a simple example of how you can use `useEffect` to fetch data when a component mounts: 59 | 60 | ```jsx {6-10} 61 | import { useState, useEffect } from 'react'; 62 | 63 | function MyComponent() { 64 | const [data, setData] = useState(null); 65 | 66 | useEffect(() => { 67 | fetch('[url]') 68 | .then(response => response.json()) 69 | .then(data => setData(data)); 70 | }, []); // Empty dependency array means this effect runs only once when component mounts 71 | 72 | return ( 73 |
    74 | {data &&

    {data}

    } 75 |
    76 | ); 77 | } 78 | ``` 79 | 80 | ::: tip 81 | - `useEffect` in React manages side effects in functional components. 82 | - It executes after every render, including the initial one. 83 | - You provide a callback function as the first argument, representing the side effect you want to perform. 84 | - An optional array of dependencies can be provided as the second argument, controlling when the effect runs. 85 | - If the dependencies array is empty, the effect runs only once after the initial render. 86 | - Common use cases include fetching data, subscribing to events, or manipulating the DOM. 87 | ::: 88 | 89 | ## What are dependencies in useEffect? 90 | 91 | In React, `useEffect` is a hook used for managing side effects in functional components. Dependencies in `useEffect` are variables or values that the effect depends on. When any of these dependencies change, the effect inside `useEffect` runs again. It helps in controlling when the effect should run based on certain conditions. For example, if you have a variable `count` that you want to watch for changes, you include it in the dependency array of `useEffect`. Here's a simple code snippet: 92 | 93 | ```jsx {6-9} 94 | import { useState, useEffect } from 'react'; 95 | 96 | function Example() { 97 | const [count, setCount] = useState(0); 98 | 99 | useEffect(() => { 100 | // This effect will run whenever `count` changes. 101 | console.log('Count changed:', count); 102 | }, [count]); 103 | 104 | return ( 105 |
    106 |

    You clicked {count} times

    107 | 110 |
    111 | ); 112 | } 113 | ``` 114 | 115 | In this example, the effect inside `useEffect` runs whenever the `count` state changes. 116 | 117 | ::: tip 118 | - Dependencies in `useEffect` are variables or values that the effect depends on. 119 | - When any of these dependencies change, the effect inside `useEffect` runs again. 120 | - It helps in controlling when the effect should run based on certain conditions. 121 | ::: 122 | 123 | ## What are the use cases of useEffect? 124 | 125 | The `useEffect` hook in React is like a Swiss Army knife for managing side effects in your components. It's handy for performing tasks that don't directly involve updating the user interface, such as fetching data from a server, subscribing to events, or setting up timers. Essentially, whenever you need to do something after the component has rendered, `useEffect` comes to the rescue. For example, you can use it to update the title of a webpage dynamically, or to clean up resources when the component unmounts. In simple terms, `useEffect` is your go-to tool for managing all sorts of behind-the-scenes tasks in React components, making your app more interactive and responsive. 126 | 127 | ::: tip 128 | - `useEffect` is commonly used for fetching data from an API when a component mounts. 129 | - It can dynamically update the title of the webpage based on certain conditions or data. 130 | - You can use `useEffect` to subscribe to events like scrolling or resizing the window. 131 | - Setting up timers or intervals for tasks such as automatic updates or countdowns. 132 | - `useEffect` can be used for cleaning up resources like unsubscribing from events or cancelling timers when the component unmounts. 133 | ::: 134 | 135 | ## How to subscribe to and unsubscribe from an event using the useEffect? 136 | 137 | In React, you can subscribe and unsubscribe to events using the `useEffect` hook. To subscribe to an event, you need to provide a function as the first argument of `useEffect`, and within this function, you can add event listeners. For example, if you want to subscribe to a `click` event, you would write something like this: 138 | 139 | ```jsx {4-14} 140 | import { useEffect } from 'react'; 141 | 142 | function MyComponent() { 143 | useEffect(() => { 144 | function handleClick() { 145 | console.log('Button clicked!'); 146 | } 147 | 148 | document.addEventListener('click', handleClick); 149 | 150 | return () => { 151 | document.removeEventListener('click', handleClick); 152 | }; 153 | }, []); 154 | 155 | return ( 156 | 157 | ); 158 | } 159 | ``` 160 | 161 | In this code, `useEffect` is used with an empty dependency array (`[]`), which means it runs once when the component mounts. Inside it, we define a function `handleClick` that logs a message. We then add an event listener to the document for the `click` event, and when the component unmounts (or when the dependencies change, which is never in this case), we remove the event listener to clean up after ourselves and avoid memory leaks. 162 | 163 | ::: tip 164 | - To subscribe to an event using `useEffect` define a function to handle the event. 165 | - To unsubscribe from the event return a cleanup function from the `useEffect` hook. 166 | ::: 167 | 168 | ## What is `useMemo in react? 169 | 170 | `useMemo` is a feature in React that helps optimize performance by memorizing the result of a function and returning the cached result when the inputs remain the same. It's useful when you have a costly computation that you want to avoid repeating unnecessarily. For instance, if you have a component that renders based on some data, and that rendering process is computationally intensive, you can wrap that computation in `useMemo` to ensure it only recalculates when the data it depends on changes. Here's a simple example: 171 | 172 | ```jsx {4-7} 173 | import { useMemo } from 'react'; 174 | 175 | function MyComponent({ data }) { 176 | const expensiveCalculation = useMemo(() => { 177 | // Perform some costly computation based on data 178 | return data.reduce((acc, val) => acc + val, 0); 179 | }, [data]); // Only recompute if 'data' changes 180 | 181 | return ( 182 |
    183 |

    Result of expensive calculation: {expensiveCalculation}

    184 |
    185 | ); 186 | } 187 | ``` 188 | 189 | In this example, `expensiveCalculation` will only be recalculated if the `data` prop changes, otherwise, it will reuse the previously computed value, improving performance. 190 | 191 | ::: tip 192 | - `useMemo` in React helps optimize performance by memorizing the result of a function. 193 | - It returns the cached result when the inputs to the function remain the same. 194 | - Useful for avoiding unnecessary recalculations of costly computations. 195 | - Typically used when a component relies on some data that might change, but the result of a computation based on that data doesn't need to be recalculated every time. 196 | - Improves performance by preventing redundant computations. 197 | ::: 198 | 199 | ## What is `useRef` in react? 200 | 201 | In React, useRef is a tool that helps to reference a DOM element or a value that persists across renders. It's like a sticky note where you can write something and remember it even if the page changes. Here's a simple example: 202 | 203 | ```jsx {4,7,12} 204 | import { useRef } from 'react'; 205 | 206 | function MyComponent() { 207 | const inputRef = useRef(null); 208 | 209 | const handleClick = () => { 210 | inputRef.current.focus(); // Focuses on the input field 211 | }; 212 | 213 | return ( 214 |
    215 | 216 | 217 |
    218 | ); 219 | } 220 | ``` 221 | 222 | In this code, useRef is used to create a reference to the input element. Later, when the button is clicked, the input field gets focused because we use the `.focus()` method on the `inputRef.current`. This is just one simple use case, but useRef can be handy for many other situations where you need to keep track of a value across renders. 223 | 224 | ::: tip 225 | - useRef in React allows you to create references to DOM elements or values that persist across renders. 226 | - With useRef, you can access and manipulate DOM elements directly without resorting to traditional DOM manipulation methods. 227 | - One common use case is to access and modify the properties or methods of a DOM element, such as focusing an input field or measuring its dimensions. 228 | - useRef returns a mutable object with a `.current` property, which holds the reference to the value or DOM element. 229 | ::: 230 | 231 | ## What is `useCallback` in react? 232 | 233 | In React, useCallback is a hook that helps in optimizing performance by memoizing (or caching) callback functions. When you use useCallback, it returns a memoized version of the callback function that only changes if one of the dependencies has changed. This can be useful in preventing unnecessary re-renders of child components. Here's a simple example: 234 | 235 | ```jsx {7-9} 236 | import { useCallback, useState } from 'react'; 237 | 238 | function App() { 239 | const [count, setCount] = useState(0); 240 | 241 | // useCallback to memoize the increment function 242 | const increment = useCallback(() => { 243 | setCount(prevCount => prevCount + 1); 244 | }, []); 245 | 246 | return ( 247 |
    248 |

    Count: {count}

    249 | 250 |
    251 | ); 252 | } 253 | ``` 254 | 255 | In this example, the `increment` function is memoized using useCallback, ensuring that it doesn't change between re-renders unless the dependencies (in this case, there are none `[]`) change. 256 | 257 | ::: tip 258 | - `useCallback` is a hook in React. 259 | - It optimizes performance by memoizing callback functions. 260 | - Memoization means caching the function so that it only changes if its dependencies change. 261 | - Helps prevent unnecessary re-renders of child components. 262 | ::: 263 | 264 | ## What is `useContext` in react? 265 | 266 | `useContext` is a tool in React that lets you easily access data from a Context without having to pass it through multiple components. In simpler terms, it helps you share information, like a user's authentication status or theme preference, across different parts of your app without manually passing it down. Here's a basic example: 267 | 268 | ```jsx {4,9,16} 269 | import { useContext } from 'react'; 270 | 271 | // Create a context 272 | const ThemeContext = React.createContext('light'); 273 | 274 | // A component that uses the context 275 | function ThemeDisplay() { 276 | // Use useContext to access the context 277 | const theme = useContext(ThemeContext); 278 | return

    Current theme: {theme}

    ; 279 | } 280 | 281 | // Another component that uses the context 282 | function App() { 283 | return ( 284 | 285 |
    286 | 287 |
    288 |
    289 | ); 290 | } 291 | 292 | export default App; 293 | ``` 294 | 295 | In this example, `useContext` is used to access the `ThemeContext` in the `ThemeDisplay` component, allowing it to display the current theme without directly passing it from the `App` component. 296 | 297 | ::: tip 298 | - `useContext` is a feature in React for accessing data stored in a Context. 299 | - It enables components to consume data from a Context without explicitly passing it down through props. 300 | - It simplifies sharing data like user authentication status, theme preferences, or language selection across different parts of an application. 301 | - With `useContext`, you create a Context using `React.createContext()`. 302 | - Then, you can use `useContext(ContextName)` within a component to access the data stored in that Context. 303 | - This eliminates the need for prop drilling, making code cleaner and more maintainable. 304 | ::: 305 | 306 | ## What is `useLayoutEffect` in react? 307 | 308 | `useLayoutEffect` in React is similar to `useEffect`, but it gets executed synchronously after all DOM mutations. This means it's useful for tasks that require you to read layout from the DOM and then make changes immediately, like measuring the size or position of an element. Here's a simple example: 309 | 310 | ```jsx {7-10} 311 | import { useLayoutEffect, useState, useRef } from 'react'; 312 | 313 | function Component() { 314 | const [width, setWidth] = useState(0); 315 | const ref = useRef(); 316 | 317 | useLayoutEffect(() => { 318 | // Measure the width of the element 319 | setWidth(ref.current.clientWidth); 320 | }, []); 321 | 322 | return ( 323 |
    324 | Width: {width}px 325 |
    326 | ); 327 | } 328 | ``` 329 | 330 | In this code, `useLayoutEffect` is used to measure the width of a `div` element and update the state accordingly. The effect runs synchronously after the DOM is updated, ensuring accurate measurements. 331 | 332 | ::: tip 333 | - `useLayoutEffect` in React executes synchronously after all DOM mutations. 334 | - It's similar to `useEffect` but is preferred for tasks needing immediate DOM layout changes. 335 | - Useful for measuring elements' size or position right after they're rendered. 336 | - Ensures accurate measurements as it runs before the browser paints the screen. 337 | - Perfect for scenarios where you need to update state based on DOM layout calculations. 338 | ::: 339 | 340 | ## What is `useDeferredValue` in react? 341 | 342 | In React, `useDeferredValue` is a hook used to defer the update of a value until certain conditions are met, typically to improve performance. It's particularly handy when dealing with user input or network requests where immediate updates might not be necessary. For example, if you have a large list of items and the user is scrolling through them, you might not want to update the UI for every single item scrolled past, but rather wait until the scrolling stops to update. Here's a simple code snippet demonstrating its usage: 343 | 344 | ```jsx {4} 345 | import { useDeferredValue } from 'react'; 346 | 347 | function MyComponent() { 348 | const deferredValue = useDeferredValue(someValue); 349 | 350 | // Use the deferred value in your component 351 | return
    {deferredValue}
    ; 352 | } 353 | ``` 354 | 355 | In this code, `someValue` can be any value that you want to defer updating until later. 356 | 357 | ::: tip 358 | - `useDeferredValue` is a React hook for deferring the update of a value until certain conditions are met. 359 | - It's useful for improving performance, especially with user input or network requests where immediate updates may not be necessary. 360 | - Deferred values can be used in components to avoid immediate updates, enhancing the user experience. 361 | ::: 362 | 363 | ## What is `useId` in react? 364 | 365 | In React, `useId` is a special function, known as a React Hook, that helps generate unique IDs. These IDs are useful for adding accessibility attributes to elements in a webpage. When you use `useId`, it creates a unique ID string that you can then use for accessibility-related attributes like `aria-describedby`. This is helpful for connecting different parts of your webpage, such as linking an input field to its description for screen readers. Here's a simple example of how you can use `useId` in a React component: 366 | 367 | ```jsx {4,12,15} 368 | import { useId } from 'react'; 369 | 370 | function PasswordField() { 371 | const passwordHintId = useId(); 372 | 373 | return ( 374 | <> 375 | 382 |

    383 | The password should contain at least 18 characters 384 |

    385 | 386 | ); 387 | } 388 | ``` 389 | 390 | In this example, `useId` generates a unique ID for the password hint, and we use it for both the `aria-describedby` attribute on the input field and the `id` attribute on the paragraph element. This ensures that even if the PasswordField component is used multiple times on a page, each instance will have its own unique IDs, avoiding conflicts and ensuring accessibility. 391 | 392 | ::: tip 393 | - `useId` is a React Hook used for generating unique IDs. 394 | - These unique IDs are primarily used for adding accessibility attributes to elements. 395 | - You can use `useId` to generate IDs for elements like input fields and their related descriptions. 396 | - The generated IDs can be passed to attributes like `aria-describedby` to link elements together for accessibility purposes. 397 | - Hardcoding IDs is not recommended in React; instead, use `useId` to dynamically generate unique IDs for components. 398 | ::: 399 | 400 | ::: warning 401 | Avoid using `useId` to generate keys in a list; keys should typically be derived from your data. 402 | ::: 403 | 404 | ## What is `useReducer` in react? 405 | 406 | `useReducer` is a function in React that helps manage state more efficiently, especially for complex state logic. It's like a Swiss Army knife for state management. Instead of having multiple `useState` calls for different pieces of state, you can use `useReducer` for managing state transitions based on actions. It takes in a reducer function and an initial state, returning the current state and a dispatch function to trigger state updates. Here's a simple example: 407 | 408 | ```jsx {4-13,17,21-23} 409 | import { useReducer } from 'react'; 410 | 411 | // Reducer function 412 | const reducer = (state, action) => { 413 | switch (action.type) { 414 | case 'increment': 415 | return { count: state.count + 1 }; 416 | case 'decrement': 417 | return { count: state.count - 1 }; 418 | default: 419 | return state; 420 | } 421 | }; 422 | 423 | // Component using useReducer 424 | const Counter = () => { 425 | const [state, dispatch] = useReducer(reducer, { count: 0 }); 426 | 427 | return ( 428 |
    429 |

    Count: {state.count}

    430 | 431 | 432 |
    433 | ); 434 | }; 435 | 436 | export default Counter; 437 | ``` 438 | 439 | In this example, we define a reducer function that takes the current state and an action, and returns the new state based on that action. Then, in the `Counter` component, we use `useReducer` to manage the state of `count`. We dispatch actions to increment or decrement the count, and the reducer updates the state accordingly. 440 | 441 | ::: tip 442 | - `useReducer` is a function in React for managing state more efficiently. 443 | - It's particularly useful for complex state logic. 444 | - With `useReducer`, you can handle state transitions based on actions, similar to how Redux works. 445 | - It takes in a reducer function and an initial state, returning the current state and a dispatch function to trigger state updates. 446 | - Reducer function defines how state should change in response to actions. 447 | - `useReducer` simplifies state management compared to having multiple `useState` calls for different pieces of state. 448 | ::: 449 | 450 | ## What is `useTransition` in react? 451 | 452 | In React, `useTransition` is a hook that helps in handling animations when adding or removing items from a list. It allows you to smoothly transition between different states of your components, making your UI look more polished and user-friendly. Essentially, it lets you control how elements enter and exit the screen. Here's a simple example: 453 | 454 | ```jsx {5,8-10,23} 455 | import { useState, useTransition } from 'react'; 456 | 457 | function App() { 458 | const [items, setItems] = useState([]); 459 | const [isPending, startTransition] = useTransition(); 460 | 461 | const addItem = () => { 462 | startTransition(() => { 463 | setItems([...items, items.length]); 464 | }); 465 | }; 466 | 467 | const removeItem = () => { 468 | startTransition(() => { 469 | setItems(items.slice(0, -1)); 470 | }); 471 | }; 472 | 473 | return ( 474 |
    475 | 476 | 477 | {isPending ?

    Adding or Removing...

    : null} 478 |
      479 | {items.map(item => ( 480 |
    • {item}
    • 481 | ))} 482 |
    483 |
    484 | ); 485 | } 486 | ``` 487 | 488 | In this example, when you click "Add Item" or "Remove Item", the list items transition smoothly in and out of the list, providing a better user experience. The `useTransition` hook manages the animation process, making it easier to implement animations in your React components. 489 | 490 | ::: tip 491 | - `useTransition` is a React hook used for handling animations when adding or removing items from a list. 492 | - It helps in smoothly transitioning between different states of components, improving the user interface's visual appeal. 493 | - The hook allows control over how elements enter and exit the screen, making UI interactions more polished. 494 | - It's beneficial for creating animations like fading in/out or sliding in/out of elements. 495 | ::: 496 | 497 | ## What is `useDebugValue` in react? 498 | 499 | In React, useDebugValue is a hook that helps developers add debug information to custom hooks. It's handy for making sense of custom hook values in React DevTools. With useDebugValue, you can give meaningful labels or values to your custom hooks, which can make debugging easier. Here's a simple example: 500 | 501 | ```jsx {7} 502 | import { useDebugValue, useState } from 'react'; 503 | 504 | function useCustomHook(initialState) { 505 | const [value, setValue] = useState(initialState); 506 | 507 | // Giving a label to the value for debugging purposes 508 | useDebugValue(value ? 'Value is true' : 'Value is false'); 509 | 510 | return [value, setValue]; 511 | } 512 | 513 | function MyComponent() { 514 | const [state, setState] = useCustomHook(false); 515 | 516 | return ( 517 |
    518 |

    {state ? 'Value is true' : 'Value is false'}

    519 | 520 |
    521 | ); 522 | } 523 | ``` 524 | 525 | In this example, `useCustomHook` is a custom hook that maintains a state value. By using `useDebugValue`, we attach a label to the state value for debugging purposes. This label will be visible in React DevTools, helping developers understand the state's purpose more easily. 526 | 527 | ::: tip 528 | - `useDebugValue` is a hook in React. 529 | - It's used to add debug information to custom hooks. 530 | - Helps in understanding custom hook values in React DevTools. 531 | - Allows developers to give meaningful labels or values to custom hooks for easier debugging. 532 | ::: 533 | 534 | ## What is `useImperativeHandle` in react? 535 | 536 | `useImperativeHandle` is a hook in React that allows you to customize the instance value that is exposed by a child component when using `forwardRef`. This hook is useful when you want to control what methods or properties are accessible to the parent component when it interacts with the child component's ref. For instance, you might want to expose specific functions from the child component's instance to the parent. Here's a simple example: 537 | 538 | ```jsx {7-11,21} 539 | import { useRef, useImperativeHandle, forwardRef } from 'react'; 540 | 541 | const ChildComponent = forwardRef((props, ref) => { 542 | const inputRef = useRef(); 543 | 544 | // Expose specific function 'focusInput' to parent 545 | useImperativeHandle(ref, () => ({ 546 | focusInput: () => { 547 | inputRef.current.focus(); 548 | } 549 | })); 550 | 551 | return ; 552 | }); 553 | 554 | const ParentComponent = () => { 555 | const childRef = useRef(); 556 | 557 | const handleClick = () => { 558 | // Call the function 'focusInput' exposed by ChildComponent 559 | childRef.current.focusInput(); 560 | }; 561 | 562 | return ( 563 |
    564 | 565 | 566 |
    567 | ); 568 | }; 569 | 570 | export default ParentComponent; 571 | ``` 572 | 573 | In this example, the `useImperativeHandle` hook is used to expose the `focusInput` function of the child component to its parent. Then, the parent component can call this function to focus on the input element within the child component. 574 | 575 | ::: tip 576 | - `useImperativeHandle` is a React hook used to customize the instance value exposed by a child component when using `forwardRef`. 577 | - It allows you to control which methods or properties of the child component's instance are accessible to the parent component. 578 | - This hook is particularly useful when you need to expose specific functions or behaviors from the child component to its parent. 579 | - It is commonly used in conjunction with `forwardRef` to provide a more controlled and focused API for interacting with child components. 580 | - By using `useImperativeHandle`, you can enhance encapsulation and provide a cleaner interface between parent and child components in React applications. 581 | ::: 582 | 583 | ## What is `useSyncExternalStore` in react? 584 | 585 | The useSyncExternalStore in React is a tool that helps you connect your components to an external data store, like a database or another part of your application. When you use this hook, you can subscribe to changes in the store and get the current snapshot of its data. In simple terms, it's a way for your React components to stay up-to-date with the latest information from outside sources. 586 | 587 | Here's a small example of how you might use it: 588 | 589 | ```jsx {6} 590 | import { useSyncExternalStore } from 'react'; 591 | import { todosStore } from './todoStore.js'; 592 | 593 | function TodosApp() { 594 | // This line connects our TodosApp component to the todosStore 595 | const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot); 596 | // Now we can use 'todos' in our component to display or work with the data 597 | return ( 598 |
    599 | {todos.map(todo => ( 600 |
    {todo.text}
    601 | ))} 602 |
    603 | ); 604 | } 605 | ``` 606 | 607 | In this example, whenever the data in `todosStore` changes, our `TodosApp` component will automatically re-render to reflect those changes. This helps keep our UI in sync with the external data source. 608 | 609 | ::: tip 610 | - `useSyncExternalStore` is a React Hook for connecting components to an external data store. 611 | - It allows subscribing to changes in the store and fetching the current snapshot of its data. 612 | - Helps components stay updated with the latest information from outside sources. 613 | - Usage involves passing subscribe and getSnapshot functions to connect to the store. 614 | - React re-renders the component whenever the store data changes. 615 | - Useful for integrating with third-party state management libraries or browser APIs. 616 | - Ensures components reflect real-time changes in external data. 617 | ::: 618 | -------------------------------------------------------------------------------- /docs/react/index.md: -------------------------------------------------------------------------------- 1 | # React 2 | 3 | This page helps explain the core ideas of React in a simple way. It breaks down the main concepts of React, making it easier to understand for beginners. 4 | 5 | ## 1. What is React? 6 | 7 | React is a popular `JavaScript library` used for building user interfaces, particularly for web applications. It allows developers to create reusable UI components that efficiently update and render based on changes in data. React uses a virtual DOM to optimize performance by minimizing the number of updates to the actual DOM, resulting in faster and smoother user experiences. Its declarative approach simplifies the process of building complex UIs by breaking them down into smaller, manageable components. Overall, React streamlines the development of interactive and dynamic web applications. 8 | 9 | ::: tip 10 | - React is a JavaScript library for building user interfaces 11 | - React uses a virtual DOM for efficient updates and rendering. 12 | ::: 13 | 14 | ## 2. What is the origin of React? 15 | 16 | React was created by `Facebook` engineer Jordan Walke. It first emerged in 2011 as an internal project at Facebook, and it was later released as an open-source library in 2013. React was developed to make it easier for Facebook developers to build user interfaces for their web applications. It quickly gained popularity due to its efficiency in managing complex user interfaces and its ability to update only the parts of a webpage that need to change, leading to faster and more dynamic web experiences. 17 | 18 | ::: tip 19 | - React was created by Facebook engineer Jordan Walke. 20 | - Originated in 2011 as an internal project at Facebook. 21 | - Released as an open-source library in 2013. 22 | ::: 23 | 24 | ## 3. What is the core concept of React? 25 | 26 | The core concept of React is to make building user interfaces easier and more efficient. React is a JavaScript library that helps developers create interactive and dynamic UI components for web applications. It works by breaking down the UI into small, reusable pieces called components, each responsible for a specific part of the UI. React uses a concept called the virtual DOM (Document Object Model) to efficiently update and render these components when the data changes, resulting in faster performance and a better user experience. Overall, React simplifies the process of building complex user interfaces by providing a structured and efficient way to manage UI components and their interactions. 27 | 28 | ::: tip 29 | - React breaks down the UI into small, reusable components. 30 | - Each component is responsible for a specific part of the UI. 31 | - React utilizes the virtual DOM (Document Object Model) for efficient updates and rendering. 32 | ::: 33 | 34 | ## 4. What is the Virtual DOM? 35 | 36 | The virtual DOM is like a blueprint of a webpage that exists in memory. It's a simplified version of the actual webpage's structure and content. When something changes on a webpage, like a user clicking a button or updating some text, instead of directly changing the real webpage, the virtual DOM gets updated first. Then, a process called `reconciliation` compares the updated virtual DOM with the previous one to identify what exactly changed. After this, only the specific parts of the real webpage that need to change are updated, making the process faster and more efficient. So, the virtual DOM helps in managing and updating webpages smoothly without constantly redrawing the entire page. 37 | 38 | ::: tip 39 | - The virtual DOM is a simplified representation of a webpage's structure and content that exists in memory. 40 | - This allows for efficient updates as only the specific parts of the real webpage that need to change are updated. 41 | ::: 42 | 43 | ## 5. What is the difference between Shadow DOM and Virtual DOM? 44 | 45 | Shadow DOM and Virtual DOM are both techniques used in web development, but they serve different purposes. The Shadow DOM is a way to encapsulate and isolate components in a web page, keeping their styles and functionality separate from the rest of the page. It helps prevent conflicts between different parts of a web page and makes it easier to manage complex applications. On the other hand, Virtual DOM is a concept used by frameworks like React to improve performance. It's a lightweight copy of the actual DOM (Document Object Model) that the framework uses to track changes. When changes occur, the Virtual DOM is updated instead of the real DOM, which is faster. Then, only the specific parts that have changed are updated in the real DOM, reducing the need for expensive DOM operations. So, in short, Shadow DOM is about encapsulation and isolation, while Virtual DOM is about optimizing performance by minimizing DOM updates. 46 | 47 | ::: tip 48 | - Shadow DOM encapsulates and isolates components in a web page. 49 | - It keeps styles and functionality separate from the rest of the page. 50 | - It prevents conflicts between different parts of a web page. 51 | - Virtual DOM is lightweight copy of the actual DOM (Document Object Model). 52 | - It tracks changes in the DOM efficiently. 53 | - It minimizes expensive DOM operations, enhancing performance. 54 | ::: 55 | 56 | ::: warning 57 | - React uses a virtual DOM. 58 | ::: 59 | 60 | ## 6. How react improves the performance? 61 | 62 | React improves performance primarily through its virtual DOM (Document Object Model) and reconciliation algorithm. When you make changes to your app's data, React doesn't directly update the actual DOM. Instead, it first updates a virtual representation of the DOM, which is much faster. Then, React compares this virtual DOM with the actual DOM to find the differences efficiently. It only applies the necessary changes to the real DOM, minimizing the number of updates needed and making the app faster. 63 | 64 | ::: tip 65 | - React uses a virtual DOM (Document Object Model) to improve performance. 66 | - React's reconciliation algorithm efficiently compares the virtual DOM with the actual DOM to identify differences. 67 | ::: 68 | 69 | ## 7. What is reconciliation? 70 | 71 | In React, reconciliation is like a process where React compares the new changes you made in your app with the old version to figure out what needs updating. It's a bit like comparing two lists to see what's different. React does this to be efficient—it only updates the parts of your app that actually changed, instead of redoing everything. This helps in keeping your app fast and responsive, especially when dealing with a lot of dynamic content or frequent updates. So, reconciliation is basically React's way of making sure your app stays up to date without wasting unnecessary resources. 72 | 73 | ::: tip 74 | - Reconciliation in React is like comparing changes in your app with the old version. 75 | - React does this comparison to avoid unnecessary updates, keeping the app fast. 76 | ::: 77 | 78 | ## 8. What is JSX in React? 79 | 80 | JSX stands for JavaScript XML. It's a syntax extension for JavaScript, often used with React. JSX allows you to write HTML-like code directly within JavaScript. Here's a tiny example: 81 | 82 | ```jsx 83 | const element =

    Hello, world!

    ; 84 | ``` 85 | 86 | In this example, `

    Hello, world!

    ` looks like HTML, but it's actually JSX. It gets transformed into regular JavaScript by a tool like Babel before it's rendered in the browser. This way, you can write UI components more elegantly and expressively in React. 87 | 88 | ::: tip 89 | - JSX stands for JavaScript XML. 90 | - JSX allows you to write HTML-like code directly within JavaScript. 91 | - JSX code gets transformed into regular JavaScript before rendering. 92 | ::: 93 | 94 | ## 9. Why isn't React considered a framework? 95 | 96 | React isn't a framework because it doesn't provide a full set of tools and features to build an entire application. Instead, React is a JavaScript library that helps in building user interfaces, specifically for web applications. It focuses on handling the view layer of the application and allows developers to create reusable UI components. Unlike frameworks such as Angular or Vue.js, React doesn't dictate how you should structure your application or handle things like routing or state management. Developers often combine React with other libraries and tools to create a complete solution for building web applications. 97 | 98 | ::: tip 99 | - React is not a framework but a JavaScript library. 100 | - React focuses on the view layer of the application. 101 | - Unlike frameworks like Angular or Vue.js, React doesn't offer a complete solution for building applications. 102 | - Developers often combine React with other libraries and tools to create full-fledged web applications. 103 | ::: 104 | 105 | ## 10. What are the differences between a framework and a library? 106 | 107 | A framework is like a skeleton that provides a structure for building something. It offers a set of rules and guidelines on how to develop a particular software application. It often dictates the flow of control, and you need to follow its patterns. On the other hand, a library is like a toolbox full of useful functions that you can use to solve specific problems in your code. Unlike a framework, you have more freedom in how you use a library. You can pick and choose which parts of the library to use and integrate them into your code as needed. So, while a framework tells you how to build something, a library provides tools to help you build it. 108 | 109 | ::: tip 110 | - Framework provides a structured skeleton for building applications. 111 | - It dictates the flow of control and often imposes specific patterns to follow. 112 | - Users need to adhere to the framework's guidelines and rules. 113 | - Library is a collection of functions and tools that can be used to solve specific problems. 114 | - Unlike a framework, users have more freedom in utilizing libraries. 115 | ::: 116 | -------------------------------------------------------------------------------- /docs/typescript/index.md: -------------------------------------------------------------------------------- 1 | # Typescript 2 | 3 | ::: info 4 | Coming soon 5 | ::: 6 | -------------------------------------------------------------------------------- /navigation/nav-items.ts: -------------------------------------------------------------------------------- 1 | import { DefaultTheme } from 'vitepress/types/default-theme' 2 | 3 | export const navItems: DefaultTheme.NavItem[] = [ 4 | { text: 'Home', link: '/' }, 5 | { text: 'React', link: '/react/' }, 6 | { text: 'Javascript', link: '/javascript/' }, 7 | { text: 'Typescript', link: '/typescript/' }, 8 | ] 9 | -------------------------------------------------------------------------------- /navigation/sidebar.ts: -------------------------------------------------------------------------------- 1 | import { DefaultTheme } from 'vitepress/types/default-theme' 2 | 3 | export const sidebar: DefaultTheme.Sidebar = [ 4 | { 5 | text: 'React', 6 | base: '/react', 7 | items: [ 8 | { text: 'Basis', link: '/' }, 9 | { text: 'Components', link: '/components' }, 10 | { text: 'Hooks', link: '/hooks' }, 11 | { text: 'Advanced', link: '/advanced' }, 12 | ], 13 | }, 14 | { 15 | text: 'Javascript', 16 | base: '/javascript', 17 | items: [ 18 | { text: 'Basis', link: '/' }, 19 | { text: 'Variables and Scope', link: '/variables' }, 20 | { text: 'Objects', link: '/objects' }, 21 | { text: 'Classes', link: '/classes' }, 22 | { text: 'Maps and Sets', link: '/maps-and-sets' }, 23 | { text: 'Arrays', link: '/arrays' }, 24 | { text: 'Loops', link: '/loops' }, 25 | { text: 'Functions', link: '/functions' }, 26 | { text: 'Asynchronous', link: '/soon' }, 27 | { text: 'Events', link: '/soon' }, 28 | { text: 'Modules', link: '/soon' }, 29 | { text: 'ES6+ Features', link: '/soon' }, 30 | { text: 'DOM Manipulation', link: '/soon' }, 31 | { text: 'Error Handling', link: '/soon' }, 32 | { text: 'Debugging', link: '/soon' }, 33 | { text: 'Workers', link: '/soon' }, 34 | { text: 'Web APIs', link: '/soon' }, 35 | { text: 'Security', link: '/soon' }, 36 | { text: 'Advanced', link: '/soon' }, 37 | ], 38 | }, 39 | { 40 | text: 'Typescript', 41 | base: '/typescript', 42 | items: [{ text: 'Coming Soon', link: '/' }], 43 | }, 44 | { 45 | text: 'About', 46 | base: '/about', 47 | items: [ 48 | { text: 'About', link: '/' }, 49 | { text: 'Contributing', link: '/contributing' }, 50 | { text: 'Changelog', link: '/changelog' }, 51 | ], 52 | }, 53 | ] 54 | -------------------------------------------------------------------------------- /navigation/social-links.ts: -------------------------------------------------------------------------------- 1 | import { DefaultTheme } from 'vitepress/types/default-theme' 2 | 3 | export const socialLinks: DefaultTheme.SocialLink[] = [ 4 | { icon: 'github', link: 'https://github.com/armancodv/frontend-interview' }, 5 | ] 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "scripts": { 3 | "prepare": "husky", 4 | "dev": "vitepress dev", 5 | "build": "vitepress build", 6 | "preview": "vitepress preview", 7 | "lint": "eslint ." 8 | }, 9 | "packageManager": "yarn@4.1.1", 10 | "devDependencies": { 11 | "@commitlint/cli": "^19.2.1", 12 | "@commitlint/config-conventional": "^19.1.0", 13 | "@semantic-release/changelog": "^6.0.3", 14 | "@semantic-release/git": "^10.0.1", 15 | "@semantic-release/github": "^10.0.3", 16 | "@typescript-eslint/eslint-plugin": "7.5.0", 17 | "@typescript-eslint/parser": "7.5.0", 18 | "eslint": "8.57.0", 19 | "eslint-config-prettier": "9.1.0", 20 | "eslint-plugin-prettier": "5.1.3", 21 | "husky": "^9.0.11", 22 | "prettier": "3.2.5", 23 | "semantic-release": "^23.0.8", 24 | "typescript": "5.4.3", 25 | "vitepress": "1.0.2" 26 | } 27 | } 28 | --------------------------------------------------------------------------------