├── .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 |
Count: {count}
84 | 85 |This is a simple React component.
156 |This is a simple React component.
{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 |Count: {count}
126 | 127 |Welcome back!
; 199 | } else { 200 | returnPlease 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 |You typed: {inputValue}
370 |` 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 |
You clicked {count} times
442 | 445 |This is the child component.
510 |This is a paragraph.
579 | > 580 | ); 581 | } 582 | ``` 583 | 584 | In this example, the `` 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 |
You clicked {count} times
37 | {/* When the button is clicked, call setCount to update the count state */} 38 | 41 |{data}
} 75 |You clicked {count} times
107 | 110 |Result of expensive calculation: {expensiveCalculation}
184 |Count: {count}
249 | 250 |Current theme: {theme}
; 279 | } 280 | 281 | // Another component that uses the context 282 | function App() { 283 | return ( 284 |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 |Count: {state.count}
430 | 431 | 432 |Adding or Removing...
: null} 478 |{state ? 'Value is true' : 'Value is false'}
519 | 520 |