diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..b512c09d4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..5a392e8f7 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @ajay-dhangar \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..a197279f0 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: Ajay-Dhangar # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..b083ed4f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Dependencies +/node_modules + +# Production +/build + +# Generated files +.docusaurus +.cache-loader + +# Misc +.DS_Store +.env +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..5fe504136 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +Email. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..004276750 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing to Code Harbor Hub + +Thank you for considering contributing to Code Harbor Hub! We welcome contributions from everyone. + +## How to Contribute + +To contribute to this project, please follow these steps: + +1. **Fork** the repository by clicking on the "Fork" button on the top right corner of this page. +2. **Clone** your fork of the repository to your local machine: + + ```bash + git clone https://github.com/your-username/code-harbor-hub.git + ``` + +3. **Create a new branch** for your changes: + + ```bash + git checkout -b my-contribution + ``` + +4. **Make your changes** and commit them to your branch: + + ```bash + git commit -am "Add your commit message here" + ``` + +5. **Push** your changes to your fork: + + ```bash + git push origin my-contribution + ``` + +6. Submit a **Pull Request** (PR) to the `main` branch of the original repository. Ensure that your PR includes a clear description of the changes you've made and any relevant information about your contribution. + +## Code Style + +Please adhere to the coding style guidelines used in this project. Consistent coding style helps make the codebase more maintainable and readable for everyone. + +## Testing + +Before submitting a PR, ensure that your changes pass any relevant tests. If you're adding new features or fixing bugs, consider adding tests to cover the changes you've made. + +## Resources for Guidance + +Here are some resources that may be helpful as you contribute to Code Harbor Hub: +- [Docusaurus Documentation](https://docusaurus.io/docs/docs-introduction) +- [React.js Documentation](https://legacy.reactjs.org/docs/getting-started.html) +- [Markdown Guide](https://www.markdownguide.org/) +- [MDX Documentation](https://mdxjs.com/docs/) +- [Mermaid Documentation](https://mermaid.js.org/) + +## Code of Conduct + +By participating in this project, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md). Please ensure that all interactions are respectful and constructive. + +## Questions or Need Help? + +If you have any questions about contributing or need assistance with anything, feel free to reach out to us by opening an issue or contacting one of the maintainers listed in the `README.md` file. + +Thank you for contributing to Code Harbor Hub! diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..2ebdf7b1e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM node:18-alpine AS builder + +WORKDIR /app + +COPY package*.json ./ +RUN npm install + +COPY . . + +RUN npm run build + +FROM nginx:alpine AS nginx + +COPY --from=builder /app/build /usr/share/nginx/html + +EXPOSE 80 + +CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 000000000..9946a7cba --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# CodeHarborHub + +Welcome to CodeHarborHub - Your Gateway to Web Development Excellence! + +## About + +CodeHarborHub is a dynamic platform dedicated to empowering developers, enthusiasts, and learners on their journey to mastering web development. This hub serves as a central point for a variety of educational resources, including tutorials, courses, showcases, and much more. + +## Features + +- **In-Depth Tutorials**: Dive into comprehensive tutorials covering a wide range of web development topics. +- **Courses for Mastery**: Enroll in structured courses designed to take your skills to the next level. +- **Inspiring Showcases**: Explore inspiring showcases of real-world projects and innovative web solutions. +- **Engaging Community**: Connect with a vibrant community of developers, share knowledge, and collaborate on projects. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..034e84803 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. diff --git a/babel.config.js b/babel.config.js new file mode 100644 index 000000000..e00595dae --- /dev/null +++ b/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: [require.resolve('@docusaurus/core/lib/babel/preset')], +}; diff --git a/blog/2024-03-15/Dobavlenie-yarlyka-udalyonnogo-oblaka-YAndeks.Disk-v-Dolphin.png b/blog/2024-03-15/Dobavlenie-yarlyka-udalyonnogo-oblaka-YAndeks.Disk-v-Dolphin.png new file mode 100644 index 000000000..83e470dc7 Binary files /dev/null and b/blog/2024-03-15/Dobavlenie-yarlyka-udalyonnogo-oblaka-YAndeks.Disk-v-Dolphin.png differ diff --git a/blog/2024-03-15/GUI-YD-tools-dlya-sredy-KDE.png b/blog/2024-03-15/GUI-YD-tools-dlya-sredy-KDE.png new file mode 100644 index 000000000..8fea696b3 Binary files /dev/null and b/blog/2024-03-15/GUI-YD-tools-dlya-sredy-KDE.png differ diff --git a/blog/2024-03-15/Integratsiya-YAndeks.Disk-s-fajlovym-meneddzherom-vvod-adresa-i-avtorizatsiya.png b/blog/2024-03-15/Integratsiya-YAndeks.Disk-s-fajlovym-meneddzherom-vvod-adresa-i-avtorizatsiya.png new file mode 100644 index 000000000..b6c1debe7 Binary files /dev/null and b/blog/2024-03-15/Integratsiya-YAndeks.Disk-s-fajlovym-meneddzherom-vvod-adresa-i-avtorizatsiya.png differ diff --git a/blog/2024-03-15/Punkty-kontekstnogo-menyu-dlya-YAndeks.Disk-v-Dolphin.png b/blog/2024-03-15/Punkty-kontekstnogo-menyu-dlya-YAndeks.Disk-v-Dolphin.png new file mode 100644 index 000000000..1a7bd9dd1 Binary files /dev/null and b/blog/2024-03-15/Punkty-kontekstnogo-menyu-dlya-YAndeks.Disk-v-Dolphin.png differ diff --git a/blog/2024-03-15/prompt-engineering-guide.md b/blog/2024-03-15/prompt-engineering-guide.md new file mode 100644 index 000000000..759a1cfde --- /dev/null +++ b/blog/2024-03-15/prompt-engineering-guide.md @@ -0,0 +1,33 @@ +--- +title: Prompt Engineering Guide +authors: [ajay-dhangar] +tags: [Prompt Engineering Guide, Engineering Guide] +date: 2020-12-21 15:34:11 +--- + +Prompt Engineering is a process of creating a prompt that is used to guide the user through a series of steps to achieve a specific goal. It is a powerful tool that can help users complete complex tasks with ease and efficiency. In this guide, we will walk you through the process of creating an effective prompt that will help you achieve your desired outcome. + +## Step 1: Define the Goal + +The first step in creating an effective prompt is to define the goal you want to achieve. This could be anything from completing a task, learning a new skill, or solving a problem. By clearly defining the goal, you can create a prompt that guides the user towards that goal. + +## Step 2: Identify the Steps + +Once you have defined the goal, the next step is to identify the steps required to achieve that goal. Break down the goal into smaller, manageable steps that the user can follow to reach the desired outcome. This will help the user understand what they need to do and how to do it. + + +## Step 3: Design the Prompt + +With the goal and steps identified, it's time to design the prompt. The prompt should be clear, concise, and easy to follow. Use simple language and provide clear instructions to guide the user through each step. You can use visual cues, such as arrows or icons, to help the user navigate the prompt. + +## Step 4: Test the Prompt + +Before deploying the prompt, it's essential to test it to ensure that it works as intended. Test the prompt with a small group of users to gather feedback and identify any issues or areas for improvement. Make any necessary adjustments based on the feedback received. + +## Step 5: Deploy the Prompt + +Once you have tested the prompt and made any necessary adjustments, it's time to deploy it. Make the prompt available to users and monitor its performance. Collect data on how users interact with the prompt and use this information to make further improvements. + +## Conclusion + +Creating an effective prompt is a valuable skill that can help you guide users through complex tasks and achieve your desired outcomes. By following these steps, you can create a prompt that is clear, concise, and easy to follow, helping users complete tasks with ease and efficiency. Happy prompting! \ No newline at end of file diff --git a/blog/authors.yml b/blog/authors.yml new file mode 100644 index 000000000..9ce8ba8e6 --- /dev/null +++ b/blog/authors.yml @@ -0,0 +1,22 @@ +ajay-dhangar: + name: Ajay Dhangar + url: https://github.com/ajay-dhangar + image_url: https://avatars.githubusercontent.com/u/99037494?v=4 + +ajay-dhangar_2022: + name: Ajay Dhangar + title: Software Engineer + url: https://github.com/ajay-dhangar + image_url: https://avatars.githubusercontent.com/u/99037494?v=4 + +ajay-dhangar_2021: + name: Ajay Dhangar + title: Full Stack Developer + url: https://github.com/ajay-dhangar + image_url: https://avatars.githubusercontent.com/u/99037494?v=4 + +ajay-dhangar_2020: + name: Ajay Dhangar + title: Frontend Developer + url: https://github.com/ajay-dhangar + image_url: https://avatars.githubusercontent.com/u/99037494?v=4 diff --git a/blog/debugging.md b/blog/debugging.md new file mode 100644 index 000000000..071ab74b2 --- /dev/null +++ b/blog/debugging.md @@ -0,0 +1,116 @@ +--- +title: Step-by-Step Guide Debugging Tests in Create React App +authors: [ajay-dhangar] +tags: [Debugging Tests] +date: 2024-03-14 14:37:46 +description: Step-by-Step Guide Debugging Tests in Create React App +draft: false +--- + +Debugging tests in a React application can be challenging, but fear not! We've got you covered with this step-by-step guide to help you overcome the common hurdles and make your tests shine. Let's dive in: + +**Step 1: Install Create React App** + +If you haven't already set up your Create React App project, start by installing it: + +```bash +npx create-react-app my-app +cd my-app +``` + +**Step 2: Writing a Test** + +Create a simple React component (e.g., a Button) in a separate file and write a test for it. For example: + +```jsx title="src/Button.js" +import React from 'react'; + +const Button = () => { + return ; +}; + +export default Button; +``` + +```jsx title="src/Button.test.js" +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import Button from './Button'; + +test('renders the button', () => { + render( + + ); + } else + return ( +
+ +
+ ); +} + +export default IfElseExample; diff --git a/courses/react-js/begginer-level/building-user-interfaces/KeyPropExample.js b/courses/react-js/begginer-level/building-user-interfaces/KeyPropExample.js new file mode 100644 index 000000000..84729071b --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/KeyPropExample.js @@ -0,0 +1,20 @@ +import React from "react"; + +function KeyPropExample() { + const items = [ + { id: 1, name: "Apple" }, + { id: 2, name: "Banana" }, + { id: 3, name: "Cherry" }, + { id: 4, name: "Date" }, + ]; + + return ( + + ); +} + +export default KeyPropExample; \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-user-interfaces/ListExample.js b/courses/react-js/begginer-level/building-user-interfaces/ListExample.js new file mode 100644 index 000000000..bb432baf8 --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/ListExample.js @@ -0,0 +1,15 @@ +import React from "react"; + +function ListExample() { + const items = ["Apple", "Banana", "Cherry", "Date"]; + + return ( + + ); +} + +export default ListExample; \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-user-interfaces/TernaryOperatorExample.js b/courses/react-js/begginer-level/building-user-interfaces/TernaryOperatorExample.js new file mode 100644 index 000000000..48547149b --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/TernaryOperatorExample.js @@ -0,0 +1,21 @@ +import React, { useState } from "react"; + +function TernaryOperatorExample() { + const [isError, setIsError] = useState(false); + + const handleError = () => { + setIsError(true); + }; + + return ( +
+ {isError ? ( +

An error occurred!

+ ) : ( + + )} +
+ ); +} + +export default TernaryOperatorExample; \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-user-interfaces/_category_.json b/courses/react-js/begginer-level/building-user-interfaces/_category_.json new file mode 100644 index 000000000..e674e7a29 --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 4: Building User Interfaces with React", + "position": 4, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to build user interfaces using the React library. You will learn how to create components, manage state, and use props to pass data between components." + } +} diff --git a/courses/react-js/begginer-level/building-user-interfaces/lesson_1.md b/courses/react-js/begginer-level/building-user-interfaces/lesson_1.md new file mode 100644 index 000000000..e9a5c5a02 --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/lesson_1.md @@ -0,0 +1,137 @@ +--- +id: lesson-1 +title: "Conditional rendering: Displaying content based on state (if/else statements, ternary operator)" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to conditionally render content in React based on component state. Understand how to use if/else statements, the ternary operator, and logical operators to control the visibility of elements." +tags: [courses, react-js, beginner-level, building-user-interfaces, conditional-rendering, if-else, ternary-operator, logical-operators] +--- + +import IfElseExample from "./IfElseExample"; +import TernaryOperatorExample from "./TernaryOperatorExample"; + +In this lesson, you will learn how to conditionally render content in React based on component state. Conditional rendering allows you to display different elements or components based on certain conditions, such as user interactions, API responses, or internal component state. + +## Introduction to conditional rendering in React + +Conditional rendering is a powerful feature in React that allows you to control the visibility of elements based on specific conditions. You can use if/else statements, the ternary operator, and logical operators to conditionally render content in your components. This enables you to create dynamic and interactive user interfaces that respond to user actions and external events. + +## Using if/else statements for conditional rendering + +In React, you can use if/else statements to conditionally render content based on component state. By checking a condition and rendering different elements accordingly, you can create dynamic UIs that adapt to changing data or user interactions. Let's see an example of using if/else statements for conditional rendering in React: + +```jsx title="IfElseExample.js" +import React, { useState } from "react"; + +function IfElseExample() { + const [isLoggedIn, setIsLoggedIn] = useState(false); + + const handleLogin = () => { + setIsLoggedIn(true); + }; + + const handleLogout = () => { + setIsLoggedIn(false); + }; + + if (isLoggedIn) { + return ( +
+

Welcome, user!

+ +
+ ); + } else + return ( +
+ +
+ ); +} + +export default IfElseExample; +``` + + + + + +In this example, we define a functional component called `IfElseExample` that conditionally renders content based on the `isLoggedIn` state. If the user is logged in (`isLoggedIn` is `true`), we display a welcome message and a "Logout" button. Otherwise, we show a "Login" button to allow the user to log in. + +## Using the ternary operator for conditional rendering + +Another common approach to conditional rendering in React is using the ternary operator (`condition ? true : false`). The ternary operator is a concise way to conditionally render content based on a condition. Let's see an example of using the ternary operator for conditional rendering in React: + +```jsx title="TernaryOperatorExample.js" +import React, { useState } from "react"; + +function TernaryOperatorExample() { + const [isError, setIsError] = useState(false); + + const handleError = () => { + setIsError(true); + }; + + return ( +
+ {isError ? ( +

An error occurred!

+ ) : ( + + )} +
+ ); +} + +export default TernaryOperatorExample; +``` + + + + + +In this example, we define a functional component called `TernaryOperatorExample` that uses the ternary operator to conditionally render content based on the `isError` state. If an error occurs (`isError` is `true`), we display an error message in red text. Otherwise, we show a button that triggers the error when clicked. + +## Differences between if/else statements and the ternary operator + +Both if/else statements and the ternary operator are commonly used for conditional rendering in React. Here are some key differences between the two approaches: + +|No. | Feature | If/Else Statements | Ternary Operator | +|----|-------------------|--------------------|------------------| +|1. | Syntax | Uses `if/else` keywords to define conditions and blocks of code. | Uses a concise `condition ? true : false` syntax to conditionally render content. | +|2. | Readability | Can be more readable for complex conditions and multiple branches of logic. | Provides a compact and concise way to handle simple conditional rendering. | +|3. | Flexibility | Offers more flexibility for handling complex conditions and logic. | Suitable for simple conditional rendering with a single condition and two branches. | +|4. | Code structure | Requires curly braces `{}` to define blocks of code for each branch. | Does not require curly braces and can be used inline within JSX expressions. | +|5. | Use cases | Ideal for scenarios with multiple conditions, complex logic, and extensive branching. | Suitable for simple toggling of elements, conditional styling, and basic conditional rendering. | + +Understanding the differences between if/else statements and the ternary operator will help you choose the appropriate approach for conditional rendering based on the complexity of your logic and the readability of your code. + + +:::tip +By using if/else statements, the ternary operator, and logical operators, you can control the visibility of elements based on component state and user interactions. Practice using conditional rendering in your React components to build responsive and engaging web applications. + +::: + +## Live Example for try yourself + +```jsx live +function Example() { + const [showMessage, setShowMessage] = React.useState(false); + + return ( +
+ + {showMessage &&

Hello, World!

} +
+ ); +} +``` + +In the example above, we define a functional component `Example` that toggles the visibility of a message based on the `showMessage` state. The button text changes dynamically to "Show Message" or "Hide Message" based on the current state, and the message is displayed or hidden accordingly. + + +## Conclusion + +Conditional rendering is a fundamental concept in React that allows you to create dynamic and interactive user interfaces. By using if/else statements, the ternary operator, and logical operators, you can control the visibility of elements based on component state and user interactions. Practice using conditional rendering in your React components to build responsive and engaging web applications. \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-user-interfaces/lesson_2.md b/courses/react-js/begginer-level/building-user-interfaces/lesson_2.md new file mode 100644 index 000000000..7e96d9ec9 --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/lesson_2.md @@ -0,0 +1,128 @@ +--- +id: lesson-2 +title: "Rendering dynamic lists with arrays and the map() function" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "Learn how to render dynamic lists in React using arrays and the map() function. Understand how to iterate over data, generate list items, and display dynamic content in your components." +tags: + [ + courses, + react-js, + beginner-level, + building-user-interfaces, + dynamic-lists, + arrays, + map-function, + ] +--- + +import ListExample from "./ListExample"; +import KeyPropExample from "./KeyPropExample"; + +In this lesson, you will learn how to render dynamic lists in React using arrays and the `map()` function. Dynamic lists allow you to display a collection of items in your components, such as a list of products, blog posts, or user comments. By iterating over an array of data and generating list items, you can create dynamic and interactive user interfaces. + +## Introduction to rendering dynamic lists + +Rendering dynamic lists is a common task in web development, especially when working with data-driven applications. In React, you can render dynamic lists by mapping over an array of data and generating list items based on the array elements. The `map()` function is a powerful tool that allows you to transform each element of an array into a new element, making it ideal for rendering dynamic content. + +## Using the `map()` function to render lists + +The `map()` function is a built-in method in JavaScript that allows you to iterate over an array and transform each element into a new value. In React, you can use the `map()` function to render dynamic lists by generating list items for each element in the array. The `map()` function takes a callback function as an argument, which is called for each element in the array. + +Here's an example of using the `map()` function to render a list of items in React: + +```jsx title="ListExample.js" +import React from "react"; + +function ListExample() { + const items = ["Apple", "Banana", "Cherry", "Date"]; + + return ( + + ); +} + +export default ListExample; +``` + + + + + +In this example, we define a functional component called `ListExample` that renders a list of items using the `map()` function. The `items` array contains four fruit names, and we use the `map()` function to generate a list item for each element in the array. The `key` prop is used to provide a unique identifier for each list item. + +## Key prop in list rendering + +When rendering dynamic lists in React, it is essential to provide a unique `key` prop for each list item. The `key` prop helps React identify which items have changed, been added, or been removed in the list. It improves the performance of list rendering and helps maintain component state correctly. + +Here's an example of using the `key` prop in list rendering: + +```jsx title="KeyPropExample.js" +import React from "react"; + +function KeyPropExample() { + const items = [ + { id: 1, name: "Apple" }, + { id: 2, name: "Banana" }, + { id: 3, name: "Cherry" }, + { id: 4, name: "Date" }, + ]; + + return ( + + ); +} + +export default KeyPropExample; +``` + + + + + +In this example, we define a list of items as an array of objects, where each object contains an `id` and a `name` property. We use the `id` property as the `key` prop for each list item to ensure that React can identify and track the items correctly. + +:::note +When using the `map()` function to render dynamic lists in React, always provide a unique `key` prop for each list item. Avoid using the array index as the `key` value, as it can lead to performance issues and incorrect rendering when the array order changes. +::: + +## Live coding example for try it yourself + +In this live coding example, you will have the opportunity to practice rendering dynamic lists in React using the `map()` function. + +```jsx live +function DynamicList() { + const products = [ + { id: 1, name: "Product 1", price: 10 }, + { id: 2, name: "Product 2", price: 20 }, + { id: 3, name: "Product 3", price: 30 }, + { id: 4, name: "Product 4", price: 40 }, + ]; + return ( + + ); +} +``` + +In this example, we define a list of products as an array of objects, where each object contains an `id`, `name`, and `price` property. We use the `map()` function to generate a list item for each product, displaying the product name and price. The `id` property is used as the `key` prop for each list item. + + + +## Conclusion + +Rendering dynamic lists in React using arrays and the `map()` function is a powerful technique for displaying collections of data in your components. By iterating over an array of data and generating list items dynamically, you can create interactive and data-driven user interfaces. Remember to provide a unique `key` prop for each list item to optimize list rendering and maintain component state effectively. +``` diff --git a/courses/react-js/begginer-level/building-user-interfaces/lesson_3.md b/courses/react-js/begginer-level/building-user-interfaces/lesson_3.md new file mode 100644 index 000000000..5362abae3 --- /dev/null +++ b/courses/react-js/begginer-level/building-user-interfaces/lesson_3.md @@ -0,0 +1,176 @@ +--- +id: lesson-3 +title: "Basic styling techniques: Inline styles, internal stylesheets, external stylesheets, and CSS modules" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "Learn how to apply basic styling techniques to your React components using inline styles and external stylesheets. Understand how to style elements, apply CSS properties, and create visually appealing user interfaces." +tags: + [ + courses, + react-js, + beginner-level, + building-user-interfaces, + styling, + inline-styles, + internal-stylesheets, + external-stylesheets, + css-modules, + ] +--- + +In this lesson, you will learn how to apply basic styling techniques to your React components. Styling is an essential aspect of web development that allows you to create visually appealing user interfaces. You will explore different methods of styling React components, including inline styles, internal stylesheets, external stylesheets, and CSS modules. By the end of this lesson, you will have a solid understanding of how to style your components effectively. + +## Introduction to styling in React + +Styling plays a crucial role in creating engaging and user-friendly web applications. In React, you can apply styles to your components using various techniques, each with its advantages and use cases. Whether you want to style a single element or apply styles globally across your application, React provides you with the flexibility to achieve your desired look and feel. + +## Inline styles in React + +Inline styles allow you to apply styles directly to individual elements within your components. You can define styles as JavaScript objects and pass them as props to the `style` attribute of an element. Inline styles provide a convenient way to apply dynamic styles based on component state or props. + +Here's an example of using inline styles in React: + +```jsx title="InlineStyleExample.js" +import React from "react"; + +function InlineStyleExample() { + const buttonStyle = { + backgroundColor: "blue", + color: "white", + padding: "10px 20px", + borderRadius: "5px", + cursor: "pointer", + border: "none", + }; + + return ; +} + +export default InlineStyleExample; +``` + + + + + +In the above example, we define a `buttonStyle` object that contains CSS properties as key-value pairs. We then apply this style object to the `style` attribute of the button element to customize its appearance. + +## Internal stylesheets in React + +Internal stylesheets allow you to define styles within your components using the `style` tag. You can write CSS rules directly in your component file and apply them to specific elements. Internal stylesheets provide a way to encapsulate styles within a component and avoid global style conflicts. + +Here's an example of using internal stylesheets in React: + +```jsx title="InternalStylesheetExample.js" +import React from "react"; + +function InternalStylesheetExample() { + return ( +
+ +
Styled container
+
+ ); +} + +export default InternalStylesheetExample; +``` + + +
Styled container
+
+ +In this example, we use the `style` tag to define CSS rules for the `.container` class. The styles are applied to the `div` element with the `container` class name, creating a visually styled container. + +## External stylesheets in React + +External stylesheets allow you to define styles in separate CSS files and import them into your components. This approach helps maintain a clean separation between your component logic and styling, making it easier to manage styles across multiple components. + + + + ```css + .container { + background-color: lightgray; + padding: 20px; + border-radius: 5px; + color: black; + } + ``` + + + ```jsx + import React from "react"; + import "./styles.css"; + + function ExternalStylesheetExample() { + return
Styled container
; + } + + export default ExternalStylesheetExample; + ``` +
+
+ + +
Styled container
+
+ +In this example, we define a CSS file named `styles.css` that contains styles for the `.container` class. We import this CSS file into the `ExternalStylesheetExample` component and apply the styles to the `div` element with the `container` class. + +## CSS modules in React + +CSS modules provide a way to scope CSS styles locally to a component, preventing style conflicts and improving maintainability. When you use CSS modules, each component gets its unique CSS class names, ensuring that styles are applied only to the intended elements. + +Here's an example of using CSS modules in React: + + + + ```css + .container { + background-color: lightgray; + padding: 20px; + border-radius: 5px; + color: black; + } + ``` + + + ```jsx + import React from "react"; + import styles from "./styles.module.css"; + + function CSSModulesExample() { + return
Styled container
; + } + + export default CSSModulesExample; + ``` +
+
+ + +
Styled container
+
+ +In this example, we define a CSS module file named `styles.module.css` that contains styles for the `.container` class. We import the CSS module into the `CSSModulesExample` component and apply the styles using the unique class name generated by CSS modules. + +:::info +When using CSS modules, the class names are automatically scoped to the component, preventing global style conflicts and ensuring that styles are applied correctly. This approach is particularly useful in large-scale applications with complex styling requirements. +::: + +:::tip +Experiment with different styling techniques in your React projects to find the best approach that suits your needs. Each styling method has its advantages and use cases, so choose the one that works best for your specific requirements. +::: + +## Conclusion + +Styling your React components is an essential skill that allows you to create visually appealing user interfaces. By using inline styles, internal stylesheets, external stylesheets, and CSS modules, you can customize the appearance of your components and enhance the user experience. Experiment with different styling techniques to find the best approach for your projects and create stunning web applications. \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-your-first-react-app/Counter.js b/courses/react-js/begginer-level/building-your-first-react-app/Counter.js new file mode 100644 index 000000000..29ace4244 --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/Counter.js @@ -0,0 +1,23 @@ +import React, { Component } from "react"; + +class Counter extends Component { + constructor(props) { + super(props); + this.state = { count: 0 }; + } + + incrementCount = () => { + this.setState({ count: this.state.count + 1 }); + }; + + render() { + return ( +
+

Count: {this.state.count}

+ +
+ ); + } +} + +export default Counter; diff --git a/courses/react-js/begginer-level/building-your-first-react-app/MyComponent.js b/courses/react-js/begginer-level/building-your-first-react-app/MyComponent.js new file mode 100644 index 000000000..6d2ed0efe --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/MyComponent.js @@ -0,0 +1,42 @@ +import React from 'react'; + +// Define a functional component using JSX +const MyComponent = () => { + // Define some variables to use in JSX expressions + const name = "Ajay"; + const isLoggedIn = true; + const fruits = ["apple", "banana", "orange"]; + + // JSX component rendering + return ( +
+

Hello, {name}!

+ + {/* Embedding expressions */} +

{isLoggedIn ? "You are logged in" : "Please log in"}

+ + {/* Defining attributes */} + Ajay + + {/* Conditionally render elements */} + {isLoggedIn &&

Welcome back, {name}!

} + + {/* Mapping over arrays */} + + + {/* Compose components */} +
+ ); +} + +// Another component to compose +const Button = ({ text, onClick }) => { + return ; +} + +export default MyComponent; \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-your-first-react-app/WelcomeMessage.js b/courses/react-js/begginer-level/building-your-first-react-app/WelcomeMessage.js new file mode 100644 index 000000000..d63691b5e --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/WelcomeMessage.js @@ -0,0 +1,7 @@ +import React from "react"; + +function WelcomeMessage() { + return
Welcome to React!
; +} + +export default WelcomeMessage; diff --git a/courses/react-js/begginer-level/building-your-first-react-app/_category_.json b/courses/react-js/begginer-level/building-your-first-react-app/_category_.json new file mode 100644 index 000000000..a0cf8a302 --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 2: Building Your First React App", + "position": 2, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to build your first React app. We will cover everything from setting up your development environment to deploying your app to the web." + } + } \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-your-first-react-app/lesson_1.md b/courses/react-js/begginer-level/building-your-first-react-app/lesson_1.md new file mode 100644 index 000000000..17ac426d2 --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/lesson_1.md @@ -0,0 +1,110 @@ +--- +id: lesson-1 +title: "Creating a simple 'Hello World' app" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to create a simple 'Hello World' app using React and understand the basic structure of a React component." +tags: [courses, react-js, beginner-level, building-your-first-react-app, hello-world, react-component] +--- + +In this lesson, we will learn how to create a simple 'Hello World' app using React. We will explore the basic structure of a React component and understand how to render content to the screen. + +## Getting started with React + +To get started with React, you need to have Node.js and npm (Node Package Manager) installed on your system. If you haven't installed them yet, follow the instructions in the [Setting up your development environment](../intro-to-react/lesson_3.md) lesson. Once you have Node.js and npm installed, you can create a new React project using Create React App. + +## Create React App + +Create React App is a tool that helps you set up a new React project with a single command. It provides a modern build setup with no configuration required. To create a new React project, open your terminal or command prompt and run the following command: + +```bash +npx create-react-app hello-world-app +``` + +This command will create a new directory called `hello-world-app` with all the necessary files and dependencies to start building your React app. + +## Creating a 'Hello World' component + +Once you have created a new React project, navigate to the project directory and open it in your code editor. You will find a file called `App.js` inside the `src` directory. This file contains the main component of your React app. + +Let's create a new component called `HelloWorld` inside `App.js` to display a simple 'Hello World' message. Replace the content of `App.js` with the following code: + +```jsx title="src/App.js" +import React from 'react'; + +function HelloWorld() { + return ( +
+

Hello World!

+
+ ); +} + +export default HelloWorld; +``` + +In this code snippet, we define a new functional component called `HelloWorld` that returns a `div` element containing an `h1` element with the text 'Hello World!'. This is a simple React component that renders content to the screen. + +## Rendering the component + +To render the `HelloWorld` component in your app, you need to import it in the `App.js` file and include it in the JSX code. Update the `App.js` file as follows: + +```jsx title="src/App.js" +import React from 'react'; + +function HelloWorld() { + return ( +
+

Hello World!

+
+ ); +} + +function App() { + return ( +
+ +
+ ); +} + +export default App; +``` + +In this updated code snippet, we define a new functional component called `App` that includes the `HelloWorld` component. When you run your React app, the `App` component will be rendered to the screen, and the `HelloWorld` component will display the 'Hello World!' message. + +## Running your React app + +To run your React app, open a terminal or command prompt in the project directory and run the following command: + +```bash +npm start +``` + +This command will start the development server and open your React app in a new browser window. You should see the 'Hello World!' message displayed on the screen. + + +
+

Hello World!

+
+
+ +Congratulations! You have successfully created a simple 'Hello World' app using React. And you have learned how to create a basic React component and render it to the screen. Now practice creating more components and explore the different features of React. + +## Practice and Excercise time + +1. Modify the `HelloWorld` component to display a different message. For example, 'Welcome to React!' or 'Hello, World!'. or may be your name (e.g., 'Hello, Ajay!'). + +2. Create a new component called `Greeting` that takes a `name` prop and displays a personalized greeting message. For example, if the `name` prop is 'Alice', the component should display 'Hello, Alice!'. + +3. Add the `Greeting` component to the `App` component and pass a `name` prop to it. Test the app to see if the personalized greeting message is displayed correctly. + +4. Experiment with different HTML elements and CSS styles to enhance the appearance of your app. Try adding a background color, changing the font size, or applying other styles to the components. + +5. Share your 'Hello World' app with your friends or on social media. Let them know that you have started learning React and built your first app. And Join our [Discord Community](https://discord.gg/5VjTyJcf) to share your work and get feedback from other learners. + +That's it for this lesson! In the next lesson, we will explore more advanced concepts of React and build a more interactive app. Stay tuned! + +## Conclusion + +In this lesson, we learned how to create a simple 'Hello World' app using React. We explored the basic structure of a React component and understood how to render content to the screen. We also learned how to create a new React project using Create React App and run the app in the development server (localhost) to see the output. \ No newline at end of file diff --git a/courses/react-js/begginer-level/building-your-first-react-app/lesson_2.md b/courses/react-js/begginer-level/building-your-first-react-app/lesson_2.md new file mode 100644 index 000000000..488ff07bc --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/lesson_2.md @@ -0,0 +1,181 @@ +--- +id: lesson-2 +title: "Understanding components and their structure (functional and class-based)" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "Learn about the different types of components in React and understand their structure and usage in building React applications." +tags: + [ + courses, + react-js, + beginner-level, + building-your-first-react-app, + react-components, + functional-components, + class-based-components, + ] +--- + +import WelcomeMessage from "./WelcomeMessage"; +import Counter from "./Counter"; + +In this lesson, we will explore the concept of components in React and understand the structure and usage of functional and class-based components. Components are the building blocks of a React application, and they encapsulate the UI elements and logic of the application. + +## What are components in React? + +Components are reusable and independent units of UI that can be composed together to build complex user interfaces. In React, components can be of two types: functional components and class-based components. Both types of components serve the same purpose of rendering UI elements, but they differ in their syntax and features. + +## Functional components + +Functional components are JavaScript functions that return JSX (JavaScript XML) elements. They are simple and lightweight, making them ideal for representing UI elements that don't require state or lifecycle methods. Here's an example of a functional component: + +```jsx title="FunctionalComponent.js" +import React from "react"; + +function FunctionalComponent() { + return
Hello, I am a functional component!
; +} + +export default FunctionalComponent; +``` + +In this example, we define a functional component called `FunctionalComponent` that returns a `div` element with a text content. Functional components are easy to read and understand, and they promote the concept of "function as a child" or "function as a prop." + +## Class-based components + +Class-based components are ES6 classes that extend the `React.Component` class. They have additional features such as state management and lifecycle methods. Class-based components are used when you need to manage state or use lifecycle methods in your component. Here's an example of a class-based component: + +```jsx title="ClassBasedComponent.js" +import React, { Component } from "react"; + +class ClassBasedComponent extends Component { + render() { + return
Hello, I am a class-based component!
; + } +} + +export default ClassBasedComponent; +``` + +In this example, we define a class-based component called `ClassBasedComponent` that extends the `Component` class from React. The `render` method is used to return the JSX elements to be rendered on the screen. Class-based components provide more features and flexibility compared to functional components. + +## When to use functional components vs. class-based components + +- **Functional components**: Use functional components for simple UI elements that don't require state or lifecycle methods. They are lightweight and easy to understand, making them suitable for presentational components. + +- **Class-based components**: Use class-based components when you need to manage state, use lifecycle methods, or implement complex logic within the component. They provide more features and flexibility compared to functional components. + +## Differences between functional and class-based components + +| No. | Feature | Functional Components | Class-based Components | +| --- | ----------------- | --------------------- | ---------------------- | +| 1. | Syntax | Function declaration | Class declaration | +| 2. | State management | No state | Stateful | +| 3. | Lifecycle methods | No lifecycle methods | Lifecycle methods | +| 4. | Reusability | Reusable | Reusable | +| 5. | Flexibility | Limited | More flexible | +| 6. | Performance | Lightweight | Heavier | + +Understanding the differences between functional and class-based components will help you choose the right component type based on your application requirements. In the next lesson, we will explore how to create and use components in a React application. + +:::note Practice Time ✏️ + +### Practice Exercise + +In this practice session, you will create a new functional component and a class-based component in your React application. Follow the steps below to complete the practice: + +1. Create a new functional component called `WelcomeMessage` that displays a welcome message to the user. + + ```jsx title="src/WelcomeMessage.js" + import React from "react"; + + function WelcomeMessage() { + return
Welcome to React!
; + } + + export default WelcomeMessage; + ``` + +2. Create a new class-based component called `Counter` that displays a counter value and increments it when a button is clicked. + + ```jsx title="src/Counter.js" + import React, { Component } from "react"; + + class Counter extends Component { + constructor(props) { + super(props); + this.state = { count: 0 }; + } + + incrementCount = () => { + this.setState({ count: this.state.count + 1 }); + }; + + render() { + return ( +
+

Count: {this.state.count}

+ +
+ ); + } + } + + export default Counter; + ``` + +3. Add the `WelcomeMessage` and `Counter` components to the `App` component and test them in your React application. + + ```jsx title="src/App.js" + import React from "react"; + import WelcomeMessage from "./WelcomeMessage"; + import Counter from "./Counter"; + + function App() { + return ( +
+ + +
+ ); + } + + export default App; + ``` + + Now, run your React application and test the `WelcomeMessage` and `Counter` components to see how they work. + + +
+ + +
+
+ +4. Experiment with the `WelcomeMessage` and `Counter` components by customizing their content and functionality. Try adding new features or modifying the existing components to enhance your React application. After making changes, test the components to see the updated behavior. And share your experience with us on our [Discord Community](https://discord.gg/5VjTyJcf). + +5. Congratulations! You have successfully created and tested new functional and class-based components in your React application. Keep exploring more features of React and building exciting applications. + +### Questions to Consider + +1. What are the differences between functional components and class-based components in React? +2. When should you use functional components, and when should you use class-based components in your React application? +3. How do you manage state in a class-based component, and why is it important for building interactive UIs? +4. What are the benefits of using components in a React application, and how do they help in building scalable and maintainable applications? + +::: + + +:::tip Quick Recap + +- Components are the building blocks of a React application that encapsulate UI elements and logic. +- Components can be of two types: functional components and class-based components. +- Functional components are simple and lightweight, while class-based components provide more features and flexibility. +- Use functional components for simple UI elements and class-based components for managing state and lifecycle methods. +- Understanding the differences between these two types of components will help you choose the right component type based on your application requirements. + +::: + +## Conclusion + +In this lesson, you learned about the different types of components in React: functional components and class-based components. Functional components are simple and lightweight, while class-based components provide more features and flexibility. Understanding the differences between these two types of components will help you choose the right component type based on your application requirements. diff --git a/courses/react-js/begginer-level/building-your-first-react-app/lesson_3.md b/courses/react-js/begginer-level/building-your-first-react-app/lesson_3.md new file mode 100644 index 000000000..07707ba15 --- /dev/null +++ b/courses/react-js/begginer-level/building-your-first-react-app/lesson_3.md @@ -0,0 +1,130 @@ +--- +id: lesson-3 +title: "Using JSX for building UI elements" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "Learn how to use JSX (JavaScript XML) to build UI elements in React and understand its syntax and features." +tags: + [ + courses, + react-js, + beginner-level, + building-your-first-react-app, + jsx, + ui-elements, + ] +--- + +import MyComponent from "./MyComponent.js"; + + +In this lesson, we will explore JSX (JavaScript XML) and learn how to use it to build UI elements in React. JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. It provides a more readable and concise way to define UI components in React. + +## What is JSX? + +JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. It is not a separate templating language, but a syntax that is transformed into regular JavaScript by tools like Babel. JSX makes it easier to define UI components in React by combining the power of JavaScript and HTML. + +Here's an example of JSX code: + +```jsx title="JSXExample.jsx" +import React from "react"; + +function JSXExample() { + return ( +
+

Hello, I am a JSX element!

+

This is a paragraph element.

+
+ ); +} + +export default JSXExample; +``` + +In this example, we define a functional component called `JSXExample` that returns a JSX element containing a `div` element with `h1` and `p` child elements. JSX allows you to write HTML-like code directly within your JavaScript files, making it easier to define UI components and structures. + +## JSX Features + +JSX provides several features that make it a powerful tool for building UI elements in React: + +- **Embedding Expressions**: You can embed JavaScript expressions within JSX using curly braces `{}`. This allows you to dynamically generate content based on variables or functions. +- **Attributes and Props**: JSX allows you to define attributes and props for HTML elements using a syntax similar to HTML. You can pass data and event handlers to components using props. +- **Conditional Rendering**: You can use JavaScript expressions and conditional statements within JSX to conditionally render elements based on certain conditions. +- **Mapping Arrays**: JSX allows you to map over arrays and render multiple elements based on the array data. This is useful for rendering lists and collections of data. +- **Styling**: You can apply inline styles to JSX elements using JavaScript objects. This allows you to define styles dynamically based on variables or conditions. +- **Fragments**: JSX provides a shorthand syntax for returning multiple elements without a parent container. You can use fragments (`<>`) to group elements together without adding an extra DOM node. +- **Comments**: JSX supports adding comments within curly braces `{/* */}`. This allows you to add comments directly within your JSX code for documentation or debugging purposes. +- **Event Handling**: JSX allows you to define event handlers for DOM events using camelCase syntax. You can attach event handlers to elements to handle user interactions. +- **Component Composition**: JSX allows you to compose components together by nesting them within each other. This makes it easy to build complex UI structures by combining smaller components. +- **JSX Spread Attributes**: JSX supports the spread operator (`...`) for passing props to components. This allows you to pass multiple props to a component without explicitly specifying each prop. +- **JSX Inheritance**: JSX elements can inherit properties from their parent components. This allows you to pass down props and context to child components without manually passing them as props. +- **JSX Transformation**: JSX code is transformed into regular JavaScript by tools like Babel. This transformation process converts JSX elements into `React.createElement` calls, which are used to create React elements. + +By leveraging these features, you can build dynamic and interactive UI components in React using JSX. It provides a declarative and expressive way to define UI structures and behaviors, making it easier to create complex user interfaces in your applications. + +:::note Practice Time ✏️ + +## Exercise - Create a Simple Functional Component using JSX + +Let's create a simple functional component using JSX and explore its features. Define a functional component called `MyComponent` that renders a greeting message, conditional text based on a variable, an image element, a conditional paragraph, a list of fruits, and a composed `Button` component. + +You can use the following code snippet as a starting point: + +```jsx title="MyComponent.jsx" +import React from 'react'; + +// Define a functional component using JSX +const MyComponent = () => { + // Define some variables to use in JSX expressions + const name = "Ajay"; + const isLoggedIn = true; + const fruits = ["apple", "banana", "orange"]; + + // JSX component rendering + return ( +
+

Hello, {name}!

+ + {/* Embedding expressions */} +

{isLoggedIn ? "You are logged in" : "Please log in"}

+ + {/* Defining attributes */} + Ajay + + {/* Conditionally render elements */} + {isLoggedIn &&

Welcome back, {name}!

} + + {/* Mapping over arrays */} + + + {/* Compose components */} +
+ ); +} + +// Another component to compose +const Button = ({ text, onClick }) => { + return ; +} + +export default MyComponent; +``` + +In this example, we define a functional component called `MyComponent` that renders a greeting message, conditional text, an image, a conditional paragraph, a list of fruits, and a composed `Button` component. We use JSX features like embedding expressions, defining attributes, conditional rendering, mapping arrays, and composing components to build the UI structure. + + + + + +Try modifying the JSX code and exploring different features to understand how JSX works and how you can use it to build UI elements in React. + +::: + +## Conclusion + +In this lesson, we explored JSX and learned how to use it to build UI elements in React. JSX provides a more readable and concise way to define UI components by combining the power of JavaScript and HTML. It offers several features like embedding expressions, defining attributes, conditional rendering, mapping arrays, and composing components that make it a powerful tool for building dynamic and interactive user interfaces. \ No newline at end of file diff --git a/courses/react-js/begginer-level/intro-to-react/_category_.json b/courses/react-js/begginer-level/intro-to-react/_category_.json new file mode 100644 index 000000000..168534e36 --- /dev/null +++ b/courses/react-js/begginer-level/intro-to-react/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 1: Introduction to React.js", + "position": 1, + "link": { + "type": "generated-index", + "description": "In this module, you will learn about the basics of React.js and how to get started with it." + } + } \ No newline at end of file diff --git a/courses/react-js/begginer-level/intro-to-react/image-1.png b/courses/react-js/begginer-level/intro-to-react/image-1.png new file mode 100644 index 000000000..f72210b88 Binary files /dev/null and b/courses/react-js/begginer-level/intro-to-react/image-1.png differ diff --git a/courses/react-js/begginer-level/intro-to-react/image-2.png b/courses/react-js/begginer-level/intro-to-react/image-2.png new file mode 100644 index 000000000..8958fcac4 Binary files /dev/null and b/courses/react-js/begginer-level/intro-to-react/image-2.png differ diff --git a/courses/react-js/begginer-level/intro-to-react/image-3.png b/courses/react-js/begginer-level/intro-to-react/image-3.png new file mode 100644 index 000000000..678d8d61f Binary files /dev/null and b/courses/react-js/begginer-level/intro-to-react/image-3.png differ diff --git a/courses/react-js/begginer-level/intro-to-react/image-4.png b/courses/react-js/begginer-level/intro-to-react/image-4.png new file mode 100644 index 000000000..609d20ace Binary files /dev/null and b/courses/react-js/begginer-level/intro-to-react/image-4.png differ diff --git a/courses/react-js/begginer-level/intro-to-react/image-5.png b/courses/react-js/begginer-level/intro-to-react/image-5.png new file mode 100644 index 000000000..ab0d72aa3 Binary files /dev/null and b/courses/react-js/begginer-level/intro-to-react/image-5.png differ diff --git a/courses/react-js/begginer-level/intro-to-react/image.png b/courses/react-js/begginer-level/intro-to-react/image.png new file mode 100644 index 000000000..c6886d4ae Binary files /dev/null and b/courses/react-js/begginer-level/intro-to-react/image.png differ diff --git a/courses/react-js/begginer-level/intro-to-react/lesson_1.md b/courses/react-js/begginer-level/intro-to-react/lesson_1.md new file mode 100644 index 000000000..6da892ca7 --- /dev/null +++ b/courses/react-js/begginer-level/intro-to-react/lesson_1.md @@ -0,0 +1,65 @@ +--- +id: react-intro-lesson-1 +title: What is React and why use it? +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "In this lesson, we will learn what React is and why we should use it. We will also learn about the history of React and its features." +tags: [courses, react-js, beginner-level, intro-to-react, what-is-react, why-use-react, history, features] +--- + +In this lesson, we will learn what React is and why we should use it. We will also learn about the history of React and its features. + +## What is React? + +React is a JavaScript library for building user interfaces. It was developed by Facebook in 2011 and released to the public in 2013. React allows developers to create interactive and dynamic user interfaces with ease. It is widely used in web development for building single-page applications, mobile applications, and more. + +## Why use React? + +We should use React for several reasons: + +|No. | Reason | Description | +|:----|:--------------------|:------------------------------------------------------------------------------------------------------------------| +|1. | Declarative | React uses a declarative programming style to describe how the UI should look based on the current state. | +|2. | Component-based | React is based on the concept of components, which are reusable building blocks for creating user interfaces. | +|3. | Virtual DOM | React uses a virtual DOM to optimize the rendering process and improve performance. | +|4. | One-way data flow | React follows a unidirectional data flow, which makes it easier to manage the state of the application. | +|5. | Rich ecosystem | React has a rich ecosystem of tools, libraries, and community support, making it easy to build complex applications. | +|6. | SPA (Single Page Application) | React is well-suited for building SPAs, which provide a seamless user experience by loading content dynamically. | + +React's simplicity, performance, and flexibility make it a popular choice for developers working on a wide range of projects. By using React, developers can create interactive and engaging user interfaces that provide a great user experience. + +## History of React + +React was created by Jordan Walke, a software engineer at Facebook, in 2011. The initial version of React was used internally at Facebook to build user interfaces for the news feed and other features. React was open-sourced in 2013, and it quickly gained popularity among developers for its innovative approach to building user interfaces. + +Over the years, React has evolved and introduced new features and optimizations to improve performance and developer experience. React has also inspired the development of other libraries and frameworks, such as Redux, Next.js, and Gatsby, which build on top of React to provide additional functionality and features. + +Today, React is one of the most widely used libraries for building user interfaces, and it continues to be actively maintained and developed by Facebook and the open-source community. React's popularity and versatility make it a valuable tool for developers working on a wide range of projects, from small websites to large-scale applications. + +## Features of React + +React has several key features that make it a powerful library for building user interfaces: + +|No. | Feature | Description | +|:----|:--------------------|:------------------------------------------------------------------------------------------------------------------| +|1. | Declarative | React uses a declarative programming style to describe how the UI should look based on the current state. | +|2. | Component-based | React is based on the concept of components, which are reusable building blocks for creating user interfaces. | +|3. | JSX (JavaScript XML) | React uses JSX, a syntax extension for JavaScript that allows developers to write HTML-like code in JavaScript. | +|4. | Virtual DOM | React uses a virtual DOM to optimize the rendering process and improve performance. | +|5. | One-way data flow | React follows a unidirectional data flow, which makes it easier to manage the state of the application. | +|6. | Hooks | React introduced hooks in version 16.8, which allow developers to use state and other React features in functional components. | +|7. | Context API | React provides a Context API for managing global state in an application without prop drilling. | +|8. | Server-side rendering | React supports server-side rendering, which improves performance and SEO for web applications. | +|9. | Rich ecosystem | React has a rich ecosystem of tools, libraries, and community support, making it easy to build complex applications. | +|10. | Developer tools | React has a set of developer tools that help developers debug, inspect, and profile React applications. | +|11. | Community support | React has a large and active community of developers who contribute to the library and provide support to others. | +|12. | Performance optimizations | React includes performance optimizations such as memoization, lazy loading, and concurrent mode to improve performance. | +|13. | Accessibility | React provides accessibility features and tools to help developers build inclusive and accessible user interfaces. | +|14. | Mobile development | React Native, a framework based on React, allows developers to build mobile applications for iOS and Android platforms. | +|15. | Testing utilities | React provides testing utilities such as Jest and React Testing Library to help developers write tests for React components. | + +These features, along with React's simplicity and flexibility, make it a popular choice for developers who want to build modern and interactive user interfaces. React's focus on performance, developer experience, and community support has contributed to its widespread adoption and success in the web development industry. + +## Conclusion + +In this lesson, we learned what React is, why we should use it, the history of React, and its key features. React is a powerful library for building user interfaces, and it offers a wide range of features and benefits that make it a popular choice among developers. By using React, developers can create interactive and engaging user interfaces that provide a great user experience. \ No newline at end of file diff --git a/courses/react-js/begginer-level/intro-to-react/lesson_2.md b/courses/react-js/begginer-level/intro-to-react/lesson_2.md new file mode 100644 index 000000000..e5befb293 --- /dev/null +++ b/courses/react-js/begginer-level/intro-to-react/lesson_2.md @@ -0,0 +1,138 @@ +--- +id: react-intro-lesson-2 +title: "Core concepts: Components, JSX, Virtual DOM" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "In this lesson, we will learn about the core concepts of React, such as components, JSX, and Virtual DOM. We will also learn how to create a simple React component." +tags: [courses, react-js, beginner-level, intro-to-react, core-concepts, components, jsx, virtual-dom] +--- + +In this lesson, we will learn about the core concepts of React, such as components, JSX, and Virtual DOM. We will also learn how to create a simple React component. + +## Components + +Components are the building blocks of a React application. A component is a reusable piece of code that defines how a part of the user interface should look and behave. Components can be simple, such as a button or a text input, or complex, such as a form or a navigation bar. + +There are two main types of components in React: + +### Functional components + +Functional components are JavaScript functions that return JSX (JavaScript XML) to describe the UI. They are simple and lightweight, making them ideal for rendering UI elements. + +For example, a simple functional component that displays a greeting message might look like this: + +```jsx title="Greeting.js" +import React from 'react'; + +function Greeting() { + return

Hello, React!

; +} + +export default Greeting; +``` + +### Class components + +Class components are ES6 classes that extend the `React.Component` class. They have additional features such as state and lifecycle methods, making them suitable for more complex logic and interactions. + +For example, a class component that displays a counter might look like this: + +```jsx title="Counter.js" +import React, { Component } from 'react'; + +class Counter extends Component { + constructor(props) { + super(props); + this.state = { count: 0 }; + } + + render() { + return ( +
+

Count: {this.state.count}

+ +
+ ); + } +} + +export default Counter; +``` + +## JSX (JavaScript XML) + +JSX is a syntax extension for JavaScript that allows developers to write HTML-like code in JavaScript. JSX makes it easier to create and manipulate the UI components in React. JSX is not a separate templating language but a syntax that is transformed into regular JavaScript by tools like Babel. + +For example, the following JSX code: + +```jsx title="JSX Example" +const element =

Hello, React!

; +``` + +is transformed into the following JavaScript code: + +```jsx title="JSX Transformed" +const element = React.createElement('h1', null, 'Hello, React!'); +``` + +JSX allows developers to write code that looks similar to HTML but is actually JavaScript under the hood. This makes it easier to understand and work with React components. + +## Virtual DOM + +The Virtual DOM is a lightweight copy of the real DOM (Document Object Model) that React uses to optimize the rendering process. When a component's state changes, React updates the Virtual DOM instead of the real DOM. React then compares the Virtual DOM with the real DOM and only applies the necessary changes to the actual DOM, minimizing the number of updates and improving performance. + +The Virtual DOM allows React to efficiently update the UI without re-rendering the entire page. This optimization technique is one of the key reasons why React is fast and efficient for building dynamic user interfaces. + +## Creating a simple React component + +Let's create a simple React component using JSX and functional components. We will create a component that displays a greeting message. + +1. Create a new file named `Greeting.js` in your React project. + +2. Add the following code to define the `Greeting` component: + + ```jsx title="Greeting.js" + import React from 'react'; + + function Greeting() { + return

Hello, React!

; + } + + export default Greeting; + ``` + +3. Import and use the `Greeting` component in your main application file (e.g., `App.js`): + + ```jsx title="App.js" + import React from 'react'; + import Greeting from './Greeting'; + + function App() { + return ( +
+

Welcome to React!

+ +
+ ); + } + + export default App; + ``` + +4. Run your React application to see the `Greeting` component in action. + + +
+

Welcome to React!

+

Hello, React!

+
+
+ +5. You should see the greeting message "Hello, React!" displayed on the screen. +6. Congratulations! You have created your first React component using JSX and functional components. + +## Conclusion + +In this lesson, we learned about the core concepts of React, including components, JSX, and Virtual DOM. We also created a simple React component to display a greeting message. Understanding these concepts is essential for building interactive and dynamic user interfaces with React. In the next lesson, we will explore more advanced topics in React and build on the knowledge gained in this lesson. \ No newline at end of file diff --git a/courses/react-js/begginer-level/intro-to-react/lesson_3.md b/courses/react-js/begginer-level/intro-to-react/lesson_3.md new file mode 100644 index 000000000..8bcabdb91 --- /dev/null +++ b/courses/react-js/begginer-level/intro-to-react/lesson_3.md @@ -0,0 +1,136 @@ +--- +id: react-intro-lesson-3 +title: "Setting up your development environment (Node.js, npm, code editor)" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "Learn how to set up your development environment for React development by installing Node.js, npm, and a code editor." +tags: [courses, react-js, beginner-level, intro-to-react, development-environment, node-js, npm, code-editor] +--- + +In this lesson, we will learn how to set up your development environment for React development. We will cover the installation of Node.js, npm (Node Package Manager), and a code editor to get started with React development. + +## Node.js + +Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript code outside of a web browser, making it ideal for server-side development, command-line tools, and building JavaScript applications. + +To install Node.js, follow these steps: + +1. Go to the [Node.js website](https://nodejs.org/) and download the LTS (Long-Term Support) version for your operating system. + + [![alt text](image.png)](https://nodejs.org/en) + +2. Run the installer and follow the installation instructions. +3. Verify the installation by opening a terminal or command prompt and running the following commands: + +```bash title="Check Node.js version" +node -v +``` + +```bash title="Check npm version" +npm -v +``` + +If you see the version numbers for Node.js and npm, the installation was successful. + +## npm (Node Package Manager) + +npm is the default package manager for Node.js and JavaScript. It allows you to install, manage, and share packages of code with other developers. You can use npm to install libraries, frameworks, tools, and dependencies for your projects. + +To install npm, follow these steps: + +1. npm is included with Node.js, so you don't need to install it separately. +2. Verify the installation by opening a terminal or command prompt and running the following command: + +```bash title="Check npm version" +npm -v +``` + +If you see the version number for npm, the installation was successful. + +## Code editor + +A code editor is a tool used by developers to write, edit, and manage code for software development. There are many code editors available, but some popular choices for React development include: + +- [Visual Studio Code](https://code.visualstudio.com/) 🚀 +- [Atom](https://atom.io/) +- [Sublime Text](https://www.sublimetext.com/) +- [WebStorm](https://www.jetbrains.com/webstorm/) +- [Vim](https://www.vim.org/) +- [Emacs](https://www.gnu.org/software/emacs/) + +Choose a code editor that you are comfortable with and that meets your development needs. Visual Studio Code is a popular choice among developers due to its features, extensions, and community support. + +:::note 📝 Visual Studio Code (VS Code) Download / Installation + +In this course, we will be using Visual Studio Code as our code editor. You can download it from the [Visual Studio Code website](https://code.visualstudio.com/). + +![alt text](image-1.png) + +1. Go to the [Visual Studio Code website](https://code.visualstudio.com/). +2. Download the installer for your operating system. +3. Run the installer and follow the installation instructions. +4. Open Visual Studio Code and install any recommended extensions for JavaScript and React development. +5. You are now ready to start coding with Visual Studio Code! +6. If you are using a different code editor, follow the installation instructions for that editor. +7. Make sure to install any recommended extensions for JavaScript and React development in your code editor. +8. You are now ready to start coding with your preferred code editor! +9. If you are using a different code editor, follow the installation instructions for that editor. + + ![alt text](image-2.png) + + Now that you have installed Node.js, npm, and a code editor, you are ready to start building React applications. You can use these tools to create, develop, and deploy React projects on your local machine. +::: + +:::tip more 📌 Additional Resources + +1. Our official vs code theme for Code Editor [Dark Code Master](https://marketplace.visualstudio.com/items?itemName=DarkCodeMaster.dark-code-master) + + + + + [![alt text](image-3.png)](https://marketplace.visualstudio.com/items?itemName=DarkCodeMaster.dark-code-master&ssr=false#overview) + + + + + [![alt text](image-4.png)](https://github.com/Ajay-Dhangar/dark-code-master-theme) + + + + + + [![alt text](image-5.png)](vscode:extension/DarkCodeMaster.dark-code-master) + + + + +2. [Visual Studio Code Tips and Tricks](https://code.visualstudio.com/docs/getstarted/tips-and-tricks) + +3. [Visual Studio Code Keyboard Shortcuts](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf) + +4. [Visual Studio Code Extensions for JavaScript and React Development](https://code.visualstudio.com/docs/nodejs/reactjs-tutorial) + +5. [Visual Studio Code Marketplace](https://marketplace.visualstudio.com/) + +::: + + +## Now run your first JavaScript code using Node.js + +Create a new file named `hello.js` and add the following code: + +```javascript title="hello.js" +console.log('Hello, Node.js!'); +``` + +Save the file and open a terminal or command prompt in the same directory. Run the following command to execute the JavaScript code using Node.js: + +```bash title="Run hello.js with Node.js" +node hello.js +``` + +You should see the output `Hello, Node.js!` displayed in the terminal. Congratulations! You have successfully run your first JavaScript code using Node.js. + +## Conclusion + +In this lesson, we learned how to set up our development environment for React development by installing Node.js, npm, and a code editor. We also ran our first JavaScript code using Node.js to verify the installation. Setting up your development environment is the first step towards building React applications, and it is essential to have the right tools and environment to work efficiently. \ No newline at end of file diff --git a/courses/react-js/begginer-level/introduction-to-forms/FormComponent.js b/courses/react-js/begginer-level/introduction-to-forms/FormComponent.js new file mode 100644 index 000000000..b7524f7e4 --- /dev/null +++ b/courses/react-js/begginer-level/introduction-to-forms/FormComponent.js @@ -0,0 +1,69 @@ +import React, { useState } from "react"; + +function FormComponent() { + const [formData, setFormData] = useState({ + username: "", + email: "", + }); + + const handleChange = (event) => { + const { name, value } = event.target; + setFormData({ + ...formData, + [name]: value, + }); + }; + + const handleSubmit = (event) => { + event.preventDefault(); + alert("Form submitted: " + JSON.stringify(formData)); + console.log("Form submitted:", formData); + }; + + return ( +
+ + + + + + +
+ ); +} + +export default FormComponent; diff --git a/courses/react-js/begginer-level/introduction-to-forms/_category_.json b/courses/react-js/begginer-level/introduction-to-forms/_category_.json new file mode 100644 index 000000000..6f182c87e --- /dev/null +++ b/courses/react-js/begginer-level/introduction-to-forms/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 5: Introduction to Forms in React", + "position": 5, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to create forms in React. You will learn how to handle form input, how to submit a form, and how to validate form input. You will also learn how to use controlled components and uncontrolled components in React." + } +} diff --git a/courses/react-js/begginer-level/introduction-to-forms/lesson_1.md b/courses/react-js/begginer-level/introduction-to-forms/lesson_1.md new file mode 100644 index 000000000..a37697912 --- /dev/null +++ b/courses/react-js/begginer-level/introduction-to-forms/lesson_1.md @@ -0,0 +1,149 @@ +--- +id: lesson-1 +title: "Creating controlled components to manage form data with state" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "learn how to create controlled components in React to manage form data using state. Controlled components allow you to handle form inputs and manage their state, enabling you to control and validate user input in React applications." +tags: + [ + courses, + react-js, + beginner-level, + introduction-to-forms, + controlled-components, + form-data, + state-management, + ] +--- + +In React, controlled components are a way to manage form data using state. Controlled components allow you to handle form inputs and manage their state, enabling you to control and validate user input in React applications. In this lesson, we will explore how to create controlled components to manage form data with state in React. + +## What are controlled components in React? + +Controlled components are form elements whose value is controlled by React state. Instead of letting the DOM handle the form data, you manage it using React state and update it based on user input. This approach allows you to control and validate user input, making it easier to manage form data in React applications. + +Here's an example of creating a controlled input component in React: + +```jsx title="ControlledInput.js" +import React, { useState } from "react"; + +function ControlledInput() { + const [value, setValue] = useState(""); + + const handleChange = (event) => { + setValue(event.target.value); + }; + + return ( + + ); +} + +export default ControlledInput; +``` + + + + + +In this example, we create a controlled input component `ControlledInput` that manages its value using React state. The `value` state variable holds the current value of the input, and the `handleChange` function updates the state based on user input. The input element's value is set to the `value` state variable, making it a controlled component. + +## Handling form data with controlled components + +Controlled components allow you to handle form data in React applications by managing the state of form inputs. You can update the state based on user input and use the state to control the value of form elements. This approach enables you to validate user input, perform calculations, and trigger actions based on form data changes. + +Here's how you can handle form data with controlled components: + +```jsx live +function FormComponent() { + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + + const handleNameChange = (event) => { + setName(event.target.value); + }; + + const handleEmailChange = (event) => { + setEmail(event.target.value); + }; + + const handleSubmit = (event) => { + event.preventDefault(); + alert(`Name: ${name}, Email: ${email}`); + }; + + return ( +
+ + + +
+ ); +} +``` + +In this example, we create a form component `FormComponent` that manages the state of two input fields: `name` and `email`. The `handleNameChange` and `handleEmailChange` functions update the state based on user input, and the `handleSubmit` function logs the form data when the form is submitted. The input elements are controlled components that display the current state values and update them as the user types. + +By using controlled components to manage form data, you can create interactive and dynamic forms in React applications. Controlled components allow you to control the form data flow, validate user input, and handle form submissions with ease. + +:::note Note 📝 + +Controlled components provide a powerful way to manage form data in React applications. By controlling the value of form elements using React state, you can handle user input, validate data, and trigger actions based on form data changes. This approach provides a flexible and robust way to manage form data and create interactive forms in React. + +::: + +:::tip Recap 📌 + +- Controlled components are form elements whose value is controlled by React state. +- You can manage form data using controlled components to handle user input, validate data, and trigger actions based on form data changes. +- By controlling the value of form elements using React state, you can create interactive and dynamic forms in React applications. +- Controlled components provide a flexible and robust way to manage form data and create interactive forms in React. +- Using controlled components allows you to control the form data flow, validate user input, and handle form submissions with ease. +- Controlled components are a powerful way to manage form data in React applications. +- By controlling the value of form elements using React state, you can handle user input, validate data, and trigger actions based on form data changes. +- This approach provides a flexible and robust way to manage form data and create interactive forms in React. + +::: + +## Conclusion + +Controlled components are a powerful way to manage form data in React applications. By controlling the value of form elements using React state, you can handle user input, validate data, and trigger actions based on form data changes. This approach provides a flexible and robust way to manage form data and create interactive forms in React. diff --git a/courses/react-js/begginer-level/introduction-to-forms/lesson_2.md b/courses/react-js/begginer-level/introduction-to-forms/lesson_2.md new file mode 100644 index 000000000..8b9f2721d --- /dev/null +++ b/courses/react-js/begginer-level/introduction-to-forms/lesson_2.md @@ -0,0 +1,116 @@ +--- +id: lesson-2 +title: "Handling form submissions (sending data or local processing)" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "learn how to handle form submissions in React applications. Handling form submissions involves sending form data to a server or processing it locally within the application. In this lesson, we will explore how to handle form submissions in React using event handlers and state management." +tags: [courses, react-js, beginner-level, introduction-to-forms, form-submissions, event-handlers, state-management] +--- + +import FormComponent from "./FormComponent"; + +In React applications, handling form submissions is a common task that involves sending form data to a server or processing it locally within the application. Form submissions are triggered when a user interacts with a form element, such as clicking a submit button or pressing the Enter key. In this lesson, we will explore how to handle form submissions in React using event handlers and state management. + +## What is form submission in React? + +Form submission in React refers to the process of sending form data to a server or processing it locally within the application. When a user interacts with a form element, such as entering text in an input field or selecting an option from a dropdown, the form data is collected and submitted to a server for processing. Form submissions can be triggered by various events, such as clicking a submit button, pressing the Enter key, or using a custom event handler. + +Here's an example of handling form submissions in React using an event handler: + +```jsx title="FormComponent.js" +import React, { useState } from "react"; + +function FormComponent() { + const [formData, setFormData] = useState({ + username: "", + email: "", + }); + + const handleChange = (event) => { + const { name, value } = event.target; + setFormData({ + ...formData, + [name]: value, + }); + }; + + const handleSubmit = (event) => { + event.preventDefault(); + alert("Form submitted: " + JSON.stringify(formData)); + console.log("Form submitted:", formData); + }; + + return ( +
+ + + + + + +
+ ); +} + +export default FormComponent; +``` + + + + + + +In this example, the `FormComponent` component manages form data using the `useState` hook. The form data is stored in the `formData` state object, which contains the `username` and `email` fields. The `handleChange` function updates the form data when the user enters text in the input fields, and the `handleSubmit` function is triggered when the form is submitted. + +When the form is submitted, the `handleSubmit` function prevents the default form submission behavior using `event.preventDefault()`, displays an alert message with the form data, and logs the form data to the console. This example demonstrates how to handle form submissions in React by capturing form data and processing it using event handlers and state management. + +:::info +In the `handleChange` function, we use object destructuring to extract the `name` and `value` properties from the event target. This allows us to update the form data dynamically based on the input field name. + +The `onSubmit` event handler is used to capture the form submission event and trigger the `handleSubmit` function. By calling `event.preventDefault()` in the `handleSubmit` function, we prevent the default form submission behavior and handle the form data locally within the application. +::: + +:::tip +When handling form submissions in React, you can perform additional validation, data processing, or API calls based on the form data. By managing form data in state and defining event handlers to update the form data, you can create interactive forms that respond to user input and trigger actions when the form is submitted. + +Form submissions can be used to send data to a server for processing or perform local operations within the application, depending on the requirements of the application. + +::: + +## Conclusion + +Handling form submissions in React involves capturing form data and processing it using event handlers and state management. By managing form data in state and defining event handlers to update the form data, you can create interactive forms that respond to user input and trigger actions when the form is submitted. Form submissions can be used to send data to a server for processing or perform local operations within the application, depending on the requirements of the application. \ No newline at end of file diff --git a/courses/react-js/begginer-level/working-with-components-and-data/ChangeEventExample.js b/courses/react-js/begginer-level/working-with-components-and-data/ChangeEventExample.js new file mode 100644 index 000000000..b1ee04c88 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/ChangeEventExample.js @@ -0,0 +1,15 @@ +import React, { useState } from 'react'; + +function ChangeEventExample() { + const [value, setValue] = useState(''); + + const handleChange = (event) => { + setValue(event.target.value); + }; + + return ( + + ); +} + +export default ChangeEventExample; \ No newline at end of file diff --git a/courses/react-js/begginer-level/working-with-components-and-data/ComplexStateExample.js b/courses/react-js/begginer-level/working-with-components-and-data/ComplexStateExample.js new file mode 100644 index 000000000..6e961bb89 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/ComplexStateExample.js @@ -0,0 +1,27 @@ +import React, { useState } from "react"; + +function ComplexStateExample() { + const [user, setUser] = useState({ name: "Ajay", age: 24 }); + + const updateName = () => { + setUser({ ...user, name: "Pawan" }); + }; + + const updateAge = () => { + setUser({ ...user, age: 23 }); + }; + + return ( +
+

Complex State Example

+

Name: {user.name}

+

Age: {user.age}

+
+ + +
+
+ ); +} + +export default ComplexStateExample; diff --git a/courses/react-js/begginer-level/working-with-components-and-data/SubmitEventExample.js b/courses/react-js/begginer-level/working-with-components-and-data/SubmitEventExample.js new file mode 100644 index 000000000..a04976bb3 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/SubmitEventExample.js @@ -0,0 +1,23 @@ +import React, { useState } from 'react'; + +function SubmitEventExample() { + const [value, setValue] = useState(''); + + const handleSubmit = (event) => { + event.preventDefault(); + alert('Form submitted with value: ' + value); + }; + + const handleChange = (event) => { + setValue(event.target.value); + }; + + return ( +
+ + +
+ ); +} + +export default SubmitEventExample; \ No newline at end of file diff --git a/courses/react-js/begginer-level/working-with-components-and-data/_category_.json b/courses/react-js/begginer-level/working-with-components-and-data/_category_.json new file mode 100644 index 000000000..fc0a16330 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 3: Working with Components and Data in React", + "position": 3, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to work with components and data in React. You will learn how to create and use components, how to pass data to components, and how to work with data in React. You will also learn how to work with forms in React and how to handle events in React. Finally, you will learn how to work with lists in React and how to use conditional rendering in React." + } + } \ No newline at end of file diff --git a/courses/react-js/begginer-level/working-with-components-and-data/lesson_1.md b/courses/react-js/begginer-level/working-with-components-and-data/lesson_1.md new file mode 100644 index 000000000..d0fdd2eb2 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/lesson_1.md @@ -0,0 +1,125 @@ +--- +id: lesson-1 +title: "Passing data between components with props (required and optional)" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "learn how to pass data between components in React using props. Props are used to pass data from a parent component to a child component, enabling the sharing of information and functionality between different parts of the application." +tags: [courses, react-js, beginner-level, working-with-components-and-data, props, data-sharing] +--- + +In React, components can communicate with each other by passing data through props. Props (short for properties) are a way to pass information from a parent component to a child component. They allow you to share data and functionality between different parts of your application. In this lesson, we will explore how to pass data between components using props in React. + +## What are props in React? + +Props are a mechanism for passing data from a parent component to a child component in React. They are read-only and help you create reusable and modular components by sharing data and functionality between them. Props are passed as attributes to child components and can be accessed within the child component as properties of the `props` object. + +Here's an example of passing data between components using props: + +```jsx title="ParentComponent.js" +import React from "react"; +import ChildComponent from "./ChildComponent"; + +function ParentComponent() { + const message = "Hello, I am a prop!"; + + return ; +} + +export default ParentComponent; +``` + +In this example, the `ParentComponent` passes a `message` prop to the `ChildComponent` by setting it as an attribute on the `ChildComponent` element. The `message` prop can then be accessed within the `ChildComponent` as a property of the `props` object. + +## Accessing props in a child component + +To access props in a child component, you can use the `props` object passed as an argument to the component function. Props are accessed as properties of the `props` object, allowing you to read the data passed from the parent component. + +Here's how you can access props in a child component: + +```jsx title="ChildComponent.js" +import React from "react"; + +function ChildComponent(props) { + return
{props.message}
; +} + +export default ChildComponent; +``` + + +
+ Hello, I am a prop! +
+
+ +In this example, the `ChildComponent` receives the `message` prop from the `ParentComponent` and renders it within a `div` element. The value of the `message` prop is accessed using `props.message` in the child component. + +## Passing required and optional props + +In React, you can define required and optional props for a component to enforce data validation and provide default values. Required props are essential for the component to function correctly, while optional props provide flexibility and customization options. + +### Required props + +To define required props for a component, you can use PropTypes to specify the expected data types and ensure that the required props are passed from the parent component. PropTypes help you validate the data passed through props and provide warnings in development mode if the data does not match the expected types. + +Here's an example of defining required props using PropTypes: + +```jsx title="ChildComponent.js" +import React from "react"; +import PropTypes from "prop-types"; + +function ChildComponent(props) { + return
{props.message}
; +} + +ChildComponent.propTypes = { + message: PropTypes.string.isRequired, +}; + +export default ChildComponent; +``` + +In this example, the `ChildComponent` specifies that the `message` prop is required and must be of type `string`. If the `message` prop is not passed or is not a string, a warning will be displayed in the console during development. + +### Optional props + +Optional props provide additional customization options for a component and allow you to define default values if the prop is not passed from the parent component. Optional props are useful for providing fallback values or configuring the component based on user preferences. + +Here's an example of defining optional props with default values: + +```jsx title="ChildComponent.js" +import React from "react"; + +function ChildComponent(props) { + const { message = "Default message" } = props; + + return
{message}
; +} + + +export default ChildComponent; +``` + +In this example, the `ChildComponent` sets a default value of `"Default message"` for the `message` prop if it is not passed from the parent component. This ensures that the component can render correctly even if the `message` prop is not provided. + +:::note Note 📝 + +By defining required and optional props, you can create more robust and predictable components in React. Required props help enforce data validation and prevent errors, while optional props provide flexibility and customization options for your components. + +### Differences between required and optional props + +|No. | Feature | Required Props | Optional Props | +|:----|:-------------------|:----------------|:----------------| +|1. | Definition | Must be passed | Optional | +|2. | Validation | Enforced | Not enforced | +|3. | Default values | Not applicable | Can have defaults | +|4. | Usage | Essential | Customizable | +|5. | Error handling | Warns if missing | No warnings | + +Understanding the differences between required and optional props will help you design more robust and maintainable components in React. By defining clear prop types and default values, you can create components that are easier to use and understand. + +::: + +## Conclusion + +Passing data between components using props is a fundamental concept in React that enables you to create modular and reusable components. Props allow you to share information and functionality between components, making your application more flexible and maintainable. By defining required and optional props, you can enforce data validation and provide default values for your components, ensuring a consistent user experience across your application. \ No newline at end of file diff --git a/courses/react-js/begginer-level/working-with-components-and-data/lesson_2.md b/courses/react-js/begginer-level/working-with-components-and-data/lesson_2.md new file mode 100644 index 000000000..6736b3f01 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/lesson_2.md @@ -0,0 +1,154 @@ +--- +id: lesson-2 +title: "Managing dynamic data within components using the useState hook" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "learn how to manage dynamic data within components using the useState hook in React. The useState hook allows you to add stateful logic to functional components and handle dynamic data updates." +tags: [courses] +--- + +import ComplexStateExample from "./ComplexStateExample"; + +In this lesson, we will explore how to manage dynamic data within components using the `useState` hook in React. The `useState` hook is a built-in React hook that allows you to add stateful logic to functional components. It enables you to handle dynamic data updates and re-renders in response to user interactions or external events. + +## What is the useState hook? + +The `useState` hook is a built-in React hook that allows you to add state to functional components. State is used to store and manage dynamic data within a component, such as user input, API responses, or component state. The `useState` hook returns a stateful value and a function to update that value, allowing you to manage state in functional components. + +Here's an example of using the `useState` hook to manage a counter value: + +```jsx title="CounterExample.js" +import React, { useState } from "react"; + +function CounterExample() { + const [count, setCount] = useState(0); + + const increment = () => { + setCount(count + 1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} + +export default CounterExample; +``` + +In this example, we define a functional component called `CounterExample` that uses the `useState` hook to manage a counter value. The `useState` hook initializes the `count` state to `0` and provides a `setCount` function to update the state value. When the "Increment" button is clicked, the `increment` function is called to update the `count` state. + +## Updating state with the useState hook + +You can update state values using the `setCount` function returned by the `useState` hook. When you call the `setCount` function with a new value, React will re-render the component with the updated state value. This allows you to handle dynamic data updates and trigger re-renders based on user interactions or external events. + +Here's an example of updating state with the `useState` hook: + +```jsx title="CounterExample.js" +import React, { useState } from "react"; + +function CounterExample() { + const [count, setCount] = useState(0); + + const increment = () => { + setCount(count + 1); + }; + + const decrement = () => { + setCount(count - 1); + }; + + return ( +
+

Count: {count}

+ + +
+ ); +} + +export default CounterExample; +``` + +In this updated example, we add a `decrement` function that calls `setCount` with `count - 1` to decrement the counter value. When the "Decrement" button is clicked, the `decrement` function is called to update the `count` state and trigger a re-render of the component. + +## Managing complex state with the useState hook + +The `useState` hook can manage complex state values, such as objects or arrays, by storing them in the component state. You can update specific properties of an object or elements of an array by creating a new state object or array and passing it to the `setCount` function. + +Here's an example of managing complex state with the `useState` hook: + +```jsx title="ComplexStateExample.js" +import React, { useState } from "react"; + +function ComplexStateExample() { + const [user, setUser] = useState({ name: "Ajay", age: 24 }); + + const updateName = () => { + setUser({ ...user, name: "Pawan" }); + }; + + const updateAge = () => { + setUser({ ...user, age: 23 }); + }; + + return ( +
+

Complex State Example

+

Name: {user.name}

+

Age: {user.age}

+
+ + +
+
+ ); +} + +export default ComplexStateExample; +``` + + + + + +In this example, we define a functional component called `ComplexStateExample` that uses the `useState` hook to manage a complex state object `user`. The `updateName` and `updateAge` functions update the `name` and `age` properties of the `user` object by creating a new state object with the updated values. + +:::info +When updating complex state values like objects or arrays, it's important to create a new state object or array to trigger a re-render of the component. This ensures that React detects the state change and updates the component UI accordingly. + +In the example above, we use the spread operator `{ ...user }` to create a new object with the existing properties of the `user` object and then update the specific property (`name` or `age`) with the new value. +::: + + +## Live Example (Code Editor try on your own) + +```jsx live +function CounterExample() { + const [count, setCount] = useState(0); + + const increment = () => { + setCount(count + 1); + }; + + const decrement = () => { + setCount(count - 1); + }; + + return ( +
+

Count: {count}

+
+ + +
+
+ ); +} +``` + +## Conclusion + +In this lesson, we learned how to manage dynamic data within components using the `useState` hook in React. The `useState` hook allows you to add stateful logic to functional components and handle dynamic data updates. By using the `useState` hook, you can create interactive and dynamic user interfaces in React applications. \ No newline at end of file diff --git a/courses/react-js/begginer-level/working-with-components-and-data/lesson_3.md b/courses/react-js/begginer-level/working-with-components-and-data/lesson_3.md new file mode 100644 index 000000000..ced041686 --- /dev/null +++ b/courses/react-js/begginer-level/working-with-components-and-data/lesson_3.md @@ -0,0 +1,182 @@ +--- +id: lesson-3 +title: "Handling user interactions with events (onClick, onChange, etc.)" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "Learn how to handle user interactions in React using event handlers like onClick, onChange, and more. Understand how to respond to user actions and update the UI based on events." +tags: + [ + courses, + react-js, + beginner-level, + working-with-components-and-data, + events, + event-handlers, + onClick, + onChange, + onSubmit + ] +--- + +import ChangeEventExample from './ChangeEventExample'; +import SubmitEventExample from './SubmitEventExample'; + +In this lesson, you will learn how to handle user interactions in React using event handlers. You will understand how to respond to user actions and update the UI based on events like `onClick`, `onChange`, and more. + +## Introduction to event handling in React + +Event handling is an essential part of building interactive web applications. In React, you can handle user interactions using event handlers like `onClick`, `onChange`, `onSubmit`, etc. These event handlers allow you to respond to user actions and update the UI based on events. + +## Handling user interactions with `onClick` event + +The `onClick` event handler is used to handle click events on elements like buttons, links, etc. You can define a function that gets called when the element is clicked. Let's see an example of handling a click event in React: + +```jsx title="ClickEventExample.js" +import React from "react"; + +function ClickEventExample() { + const handleClick = () => { + alert("Button clicked!"); + }; + + return ; +} + +export default ClickEventExample; +``` + + + + + +In the above example, we have defined a `handleClick` function that shows an alert when the button is clicked. We have attached this function to the `onClick` event of the button element. + +## Handling user interactions with `onChange` event + +The `onChange` event handler is used to handle changes in form elements like input fields, checkboxes, radio buttons, etc. You can define a function that gets called when the value of the element changes. Let's see an example of handling a change event in React: + +```jsx title="ChangeEventExample.js" +import React, { useState } from "react"; + +function ChangeEventExample() { + const [value, setValue] = useState(""); + + const handleChange = (event) => { + setValue(event.target.value); + }; + + return ; +} + +export default ChangeEventExample; +``` + + + + + +In the above example, we have defined a `handleChange` function that updates the state value when the input field value changes. We have attached this function to the `onChange` event of the input element. + +## Handling user interactions with `onSubmit` event + +The `onSubmit` event handler is used to handle form submission events. You can define a function that gets called when the form is submitted. Let's see an example of handling a form submission event in React: + +```jsx title="SubmitEventExample.js" +import React, { useState } from "react"; + +function SubmitEventExample() { + const [value, setValue] = useState(""); + + const handleSubmit = (event) => { + event.preventDefault(); + alert("Form submitted with value: " + value); + }; + + const handleChange = (event) => { + setValue(event.target.value); + }; + + return ( +
+ + +
+ ); +} + +export default SubmitEventExample; +``` + + + + + +In the above example, we have defined a `handleSubmit` function that prevents the default form submission behavior and shows an alert with the form value. We have attached this function to the `onSubmit` event of the form element. + +## Handling user interactions with other events + +Apart from `onClick`, `onChange`, and `onSubmit`, React provides event handlers for various other events like `onMouseOver`, `onMouseOut`, `onFocus`, `onBlur`, etc. You can use these event handlers to handle user interactions and update the UI based on different events. + +## Live Example (Code Editor try on your own) + +```jsx live +function AllEventsExample() { + const [value, setValue] = useState(""); + + const handleChange = (event) => { + setValue(event.target.value); + }; + + const handleMouseOver = () => { + setValue("Mouse over event triggered"); + }; + + const handleFocus = () => { + setValue("Input field focused"); + }; + + return ( +
+

All Events Example

+
+

Value: {value}

+ +
+
+ ); +} +``` + +In the example above, we have defined a functional component `AllEventsExample` that demonstrates handling different events like `onChange`, `onMouseOver`, and `onFocus`. The `handleChange`, `handleMouseOver`, and `handleFocus` functions update the state value based on the respective events. + +:::tip +You can experiment with different event handlers and their behavior by modifying the example above. Try adding new event handlers like `onMouseOut`, `onBlur`, etc., and observe how the component responds to user interactions. +::: + +## Conclusion + +In this lesson, you learned how to handle user interactions in React using event handlers like `onClick`, `onChange`, etc. You can use these event handlers to respond to user actions and update the UI based on events. Practice using event handlers in your React applications to build interactive and responsive user interfaces. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/_category_.json b/courses/react-js/intermidiate-level/_category_.json new file mode 100644 index 000000000..c92f2b780 --- /dev/null +++ b/courses/react-js/intermidiate-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Intermediate Level", + "position": 3, + "link": { + "type": "generated-index", + "description": "View Intermediate Level Modules 6-10. Click on the module to view the content. FOr React.js learning path." + } + } \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/advanced-styling/_category_.json b/courses/react-js/intermidiate-level/advanced-styling/_category_.json new file mode 100644 index 000000000..c1f38fc89 --- /dev/null +++ b/courses/react-js/intermidiate-level/advanced-styling/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 6: Advanced Styling in React", + "position": 1, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to use advanced styling techniques in React. You will learn how to use CSS Modules, Styled Components, and how to use the CSS-in-JS approach to style your React components. You will also learn how to use the Material-UI library to style your React components." + } +} diff --git a/courses/react-js/intermidiate-level/advanced-styling/lesson_1.md b/courses/react-js/intermidiate-level/advanced-styling/lesson_1.md new file mode 100644 index 000000000..06fe2a190 --- /dev/null +++ b/courses/react-js/intermidiate-level/advanced-styling/lesson_1.md @@ -0,0 +1,94 @@ +--- +id: lesson-1 +title: "CSS Modules for component-scoped styling" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to use CSS Modules to create component-scoped styles in React applications. CSS Modules allow you to write modular and reusable styles for your components without worrying about global CSS conflicts." +tags: [courses, react-js, intermediate-level, advanced-styling, css-modules, styling] +--- + +In React applications, styling components can be challenging due to the global nature of CSS. CSS Modules provide a solution by allowing you to create component-scoped styles that are isolated from the rest of your application. This lesson will introduce you to CSS Modules and show you how to use them to style your React components. + +## What are CSS Modules? + +CSS Modules are a way to write modular and reusable styles for your components in React. They allow you to define styles that are scoped to a specific component, preventing global CSS conflicts and making it easier to manage your styles. CSS Modules work by automatically generating unique class names for your styles, ensuring that they only apply to the component they are intended for. + +Here's an example of using CSS Modules in a React component: + + + + ```jsx + import React from "react"; + import styles from "./App.module.css"; + + function App() { + return ( +
+

Hello, CSS Modules!

+

Styling made easy.

+
+ ); + } + + export default App; + ``` +
+ + + ```css + .container { + padding: 20px; + border: 1px solid #ccc; + border-radius: 5px; + } + + .title { + font-size: 24px; + margin-bottom: 10px; + } + + .description { + font-size: 16px; + } + ``` + +
+ + +
+

Hello, CSS Modules!

+

Styling made easy.

+
+
+ +In this example, we import the styles from the `App.module.css` file and apply them to the corresponding elements in the `App` component. The class names defined in the CSS file are automatically transformed into unique identifiers by CSS Modules, ensuring that they only affect the `App` component. + +## Benefits of using CSS Modules + +CSS Modules offer several benefits for styling React components: + +- **Component-scoped styles:** CSS Modules provide a way to create styles that are scoped to a specific component, reducing the risk of global CSS conflicts. +- **Modular and reusable:** CSS Modules allow you to define styles in a modular and reusable way, making it easier to maintain and update your styles. +- **Automatic class name generation:** CSS Modules automatically generate unique class names for your styles, ensuring that they only apply to the intended component. +- **Improved maintainability:** By encapsulating styles within components, CSS Modules make it easier to manage and refactor your styles as your application grows. +- **Enhanced developer experience:** CSS Modules provide a more intuitive and developer-friendly way to style components in React, improving the overall development experience. +- **Support for CSS features:** CSS Modules support the use of CSS features like variables, nesting, and media queries, allowing you to write more expressive and powerful styles. +- **Integration with build tools:** CSS Modules can be easily integrated with popular build tools like Webpack, enabling seamless integration into your React application. + +By using CSS Modules, you can create more maintainable and scalable styles for your React components, improving the overall styling experience in your applications. + +:::note Key Takeaways + +- CSS Modules allow you to create component-scoped styles in React applications. +- CSS Modules automatically generate unique class names for your styles, preventing global CSS conflicts. +- CSS Modules provide benefits such as component-scoped styles, modularity, automatic class name generation, and improved maintainability. +- Using CSS Modules can enhance the developer experience and make styling components in React easier and more efficient. +- CSS Modules support CSS features like variables, nesting, and media queries, enabling you to write more expressive styles. +- CSS Modules can be integrated with build tools like Webpack to streamline the styling process in React applications. +- Try using CSS Modules in your React projects to take advantage of their benefits for styling components. + +::: + +## Conclusion + +CSS Modules provide a powerful solution for styling React components by offering component-scoped styles that are isolated from the rest of your application. By using CSS Modules, you can create modular and reusable styles that are easier to manage and maintain, improving the overall styling experience in your React applications. Try using CSS Modules in your next project to see the benefits they offer for styling components in React. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/advanced-styling/lesson_2.md b/courses/react-js/intermidiate-level/advanced-styling/lesson_2.md new file mode 100644 index 000000000..5548b8735 --- /dev/null +++ b/courses/react-js/intermidiate-level/advanced-styling/lesson_2.md @@ -0,0 +1,155 @@ +--- +id: lesson-2 +title: "Advanced styling libraries (styled-components, tailwindcss, Material-UI) (Optional)" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "Learn how to use advanced styling libraries like styled-components, tailwindcss, and Material-UI to style your React components. These libraries provide powerful tools and utilities for creating modern and responsive designs in your applications." +tags: [courses, react-js, intermediate-level, advanced-styling, styled-components, tailwindcss, material-ui] +--- + +In React applications, styling components can be challenging due to the global nature of CSS. Advanced styling libraries like styled-components, tailwindcss, and Material-UI provide powerful tools and utilities for creating modern and responsive designs in your applications. This lesson will introduce you to these libraries and show you how to use them to style your React components. + +## What are styled-components? + +styled-components is a popular CSS-in-JS library that allows you to write CSS directly in your JavaScript code. It provides a way to create styled components by defining CSS rules as template literals within your components. styled-components generates unique class names for your styles, ensuring that they are scoped to the component they are intended for. + +Here's an example of using styled-components in a React component: + +```jsx title="Button.js" +import React from "react"; +import styled from "styled-components"; + +const Button = styled.button` + background-color: #007bff; + color: #fff; + padding: 10px 20px; + border: none; + border-radius: 5px; + cursor: pointer; +`; + +function App() { + return ; +} + +export default App; +``` + + + + + +In this example, the `Button` component is created using styled-components, which defines the styles for the button element. The CSS rules are defined as a template literal within the `styled.button` function, allowing you to write CSS directly in your JavaScript code. + +:::note Note + +If you want to use styled-components in your project, you can install it via npm or yarn: + +```bash npm2yarn +npm install styled-components +``` + +Now you can import styled-components in your components and start using it to create styled components. + +::: + +## What is Tailwindcss? + +Tailwindcss is a utility-first CSS framework that provides a set of pre-built utility classes for styling your components. It allows you to create modern and responsive designs by applying utility classes directly in your HTML or JSX code. tailwindcss is highly customizable and provides a flexible way to style your components without writing custom CSS. + +Here's an example of using tailwindcss utility classes in a React component: + +```jsx title="Button.js" +import React from "react"; + +function Button() { + return ( + + ); +} + +export default Button; +``` + + + + + +In this example, the button element is styled using tailwindcss utility classes directly in the JSX code. The `bg-blue-500`, `text-white`, `font-bold`, `py-2`, `px-4`, and `rounded` classes apply background color, text color, font weight, padding, margin, and border-radius styles to the button element. + +:::note Note + +If you want to use tailwindcss in your project, you can install it via npm or yarn: + +```bash npm2yarn +npm install tailwindcss +``` + +You can then configure tailwindcss in your project and start using its utility classes to style your components. + +::: + +## What is Material-UI? + +Material-UI is a popular React component library that provides a set of pre-built components and styles based on Google's Material Design guidelines. It allows you to create modern and responsive user interfaces by using components like buttons, cards, dialogs, and more. Material-UI provides a rich set of components and themes that can be customized to match your application's design. + +Here's an example of using Material-UI components in a React component: + +```jsx title="Button.js" +import React from "react"; +import Button from "@material-ui/core/Button"; + +function App() { + return ; +} + +export default App; +``` + + + + + +In this example, the `Button` component from Material-UI is used to create a styled button element. The `variant="contained"` and `color="primary"` props apply the default Material-UI styles to the button, giving it a modern and responsive appearance. + +:::note Note + +If you want to use Material-UI in your project, you can install it via npm or yarn: + +```bash npm2yarn +npm install @material-ui/core +``` + +You can then import Material-UI components in your project and start using them to create modern and responsive user interfaces. + +::: + +## Benefits of using advanced styling libraries + +Using advanced styling libraries like styled-components, tailwindcss, and Material-UI provides several benefits for styling your React components: + +- **Modular and reusable styles**: styled-components and tailwindcss allow you to create modular and reusable styles for your components, making it easier to manage your styles and maintain consistency across your application. +- **Component-scoped styles**: styled-components generates unique class names for your styles, ensuring that they are scoped to the component they are intended for. This reduces the risk of global CSS conflicts and makes it easier to style your components. +- **Pre-built components and themes**: Material-UI provides a rich set of pre-built components and themes based on Google's Material Design guidelines. This allows you to create modern and responsive user interfaces without writing custom CSS. +- **Customization and flexibility**: styled-components, tailwindcss, and Material-UI offer customization options and utilities that allow you to style your components according to your design requirements. You can easily customize the styles, themes, and components to match your application's design. +- **Responsive design**: styled-components, tailwindcss, and Material-UI provide tools and utilities for creating responsive designs that adapt to different screen sizes and devices. This ensures that your application looks great on desktop, tablet, and mobile devices. +- **Developer experience**: Using advanced styling libraries can improve your developer experience by providing tools like syntax highlighting, auto-completion, and error checking for styling your components. This makes it easier to write and maintain CSS in your React applications. +- **Community support**: styled-components, tailwindcss, and Material-UI have active communities and documentation that provide resources, tutorials, and examples for using these libraries in your projects. You can leverage the community support to learn best practices and get help when styling your components. +- **Integration with build tools**: styled-components, tailwindcss, and Material-UI can be easily integrated with popular build tools like Webpack, enabling seamless integration into your React application. This allows you to optimize your styles and assets for production builds. +- **Performance optimization**: styled-components, tailwindcss, and Material-UI provide performance optimizations like code splitting, tree shaking, and server-side rendering that help improve the performance of your React applications. This ensures that your styles are loaded efficiently and do not impact the user experience. +- **Cross-browser compatibility**: styled-components, tailwindcss, and Material-UI ensure cross-browser compatibility by generating vendor prefixes and polyfills for CSS features that are not supported in older browsers. This ensures that your styles work consistently across different browsers and devices. +- **Accessibility**: styled-components, tailwindcss, and Material-UI follow best practices for accessibility and provide tools and utilities for creating accessible user interfaces. This ensures that your components are usable by all users, including those with disabilities. + +By using advanced styling libraries in your React applications, you can create modern and responsive designs that are modular, reusable, and customizable. These libraries provide powerful tools and utilities for styling your components, making it easier to create visually appealing user interfaces that meet your design requirements. Whether you prefer CSS-in-JS, utility-first CSS, or pre-built components, there is an advanced styling library that can help you style your React components effectively. + +:::tip + +When choosing an advanced styling library for your React project, consider factors like your design requirements, developer experience, performance optimizations, and community support. Evaluate the features and benefits of each library to determine which one best suits your styling needs and preferences. + +::: + +## Conclusion + +In this lesson, you learned about advanced styling libraries like styled-components, tailwindcss, and Material-UI and how to use them to style your React components. These libraries provide powerful tools and utilities for creating modern and responsive designs in your applications. By leveraging the benefits of these libraries, you can create modular, reusable, and customizable styles that enhance the user experience of your React applications. Whether you prefer writing CSS in JavaScript, using utility classes, or working with pre-built components, there is an advanced styling library that can help you achieve your styling goals in React. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/advanced-styling/lesson_3.md b/courses/react-js/intermidiate-level/advanced-styling/lesson_3.md new file mode 100644 index 000000000..5d2eb5e34 --- /dev/null +++ b/courses/react-js/intermidiate-level/advanced-styling/lesson_3.md @@ -0,0 +1,162 @@ +--- +id: lesson-3 +title: "BEM naming convention for organized CSS classes" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "Learn how to use the BEM (Block Element Modifier) naming convention to create organized and maintainable CSS classes in your React applications. BEM helps you structure your stylesheets by defining a clear naming convention for CSS classes, making it easier to understand and maintain your styles." +tags: + [ + courses, + react-js, + intermediate-level, + advanced-styling, + bem, + css-naming-convention, + ] +--- + +In React applications, managing CSS classes can become challenging as your project grows in size and complexity. The BEM (Block Element Modifier) naming convention provides a structured approach to naming CSS classes, making it easier to organize and maintain your stylesheets. This lesson will introduce you to the BEM naming convention and show you how to use it to create organized CSS classes in your React components. + +## What is the BEM naming convention? + +BEM is a popular naming convention for CSS classes that stands for Block Element Modifier. It helps you create modular and maintainable stylesheets by defining a clear and consistent naming structure for your CSS classes. BEM divides your styles into three categories: + +- **Block**: A standalone component that can be reused across your application. +- **Element**: A part of a block that has no meaning or use outside of the block. +- **Modifier**: A variation or state of a block or element. + +By following the BEM naming convention, you can create self-explanatory and reusable CSS classes that are easy to understand and maintain. Here's an example of using BEM in a React component: + +```css title="styles.css" +/* Block */ +.button { + display: inline-block; + padding: 10px 20px; + background-color: #007bff; + color: #fff; + border: none; + border-radius: 5px; +} + +/* Element */ + +.button__icon { + margin-right: 5px; +} + +/* Modifier */ + +.button--disabled { + opacity: 0.5; + cursor: not-allowed; +} +``` + +In this example, we have defined a block `.button`, an element `.button__icon`, and a modifier `.button--disabled` using the BEM naming convention. This structure helps you organize your styles and understand the relationship between different parts of your components. + +## How to use BEM in React components + +To use the BEM naming convention in your React components, you can apply the BEM structure to your CSS classes and use them in your JSX elements. By following the BEM naming convention, you can create consistent and maintainable styles for your components. Here's an example of using BEM in a React component: + +```jsx title="Button.js" +import React from "react"; + +function Button({ children, disabled }) { + return ( + + ); +} + +export default Button; +``` + +In this example, we have created a `Button` component that uses the BEM naming convention for its CSS classes. The `button` class represents the block, the `button__icon` class represents the element, and the `button--disabled` class represents the modifier. By following this naming convention, you can create structured and organized CSS classes for your React components. + +## Benefits of using the BEM naming convention + +Using the BEM naming convention in your React applications offers several benefits: + +- **Modularity**: BEM helps you create modular and reusable styles by dividing your components into blocks, elements, and modifiers. +- **Consistency**: BEM provides a consistent naming structure for your CSS classes, making it easier to understand and maintain your stylesheets. +- **Scalability**: BEM scales well with large projects, allowing you to organize and manage your styles effectively as your application grows. +- **Readability**: BEM class names are self-explanatory and descriptive, making it easier for developers to understand the purpose of each CSS class. +- **Maintainability**: BEM makes it easier to update and modify your stylesheets without affecting other parts of your application, improving code maintainability. +- **Collaboration**: BEM promotes collaboration among team members by providing a clear and structured approach to naming CSS classes, ensuring consistency across the project. +- **Accessibility**: BEM class names are accessible and meaningful, making it easier for developers to navigate and work with your stylesheets. +- **Performance**: BEM class names are optimized for performance and efficiency, reducing the risk of conflicts and improving rendering speed. +- **Documentation**: BEM class names serve as documentation for your stylesheets, helping new developers understand the structure and organization of your components. +- **Debugging**: BEM class names make it easier to debug and troubleshoot styling issues in your components, saving time and effort during development. +- **Best practices**: BEM follows best practices for naming CSS classes, ensuring that your stylesheets are well-organized and maintainable. +- **Flexibility**: BEM provides flexibility in naming conventions, allowing you to customize and extend the structure to suit your project's needs. +- **Community support**: BEM is widely adopted in the web development community, making it easier to find resources and tools that support the naming convention. +- **Future-proofing**: BEM is a robust and future-proof naming convention that can adapt to new technologies and trends in web development. +- **Developer experience**: BEM improves the overall developer experience by providing a clear and structured approach to styling components, reducing cognitive load and enhancing productivity. +- **Code quality**: BEM helps maintain code quality by enforcing consistent naming conventions and organization in your stylesheets, leading to cleaner and more maintainable code. +- **Cross-browser compatibility**: BEM class names are compatible with all modern browsers and devices, ensuring a consistent user experience across different platforms. + +By using the BEM naming convention in your React applications, you can create organized, maintainable, and scalable stylesheets that improve the overall development experience and code quality of your projects. + +:::info Try it out + +## Live example of BEM in action + +To see the BEM naming convention in action, let's create a simple React component that uses BEM for styling. We'll create a `Card` component that displays a title and description with structured CSS classes following the BEM naming convention. You can view the code for the `Card` component below: + + + + ```jsx + import React from "react"; + import "./Card.css"; + + function Card() { + return ( +
+

Card Title

+

This is a card description.

+
+ ); + } + + export default Card; + ``` +
+ + ```css + .card { + border: 1px solid #ccc; + border-radius: 10px; + padding: 20px; + margin: 20px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26); + } + + .card__title { + font-size: 1.5rem; + margin-bottom: 0.5rem; + } + + .card__description { + font-size: 1rem; + color: #888; + } + ``` + +
+ + +
+

Card Title

+

This is a card description.

+
+
+ +In this example, we have created a `Card` component that uses the BEM naming convention for its CSS classes. The `card` class represents the block, the `card__title` class represents the element, and the `card__description` class represents another element. By following the BEM naming convention, we can create structured and organized CSS classes for our components. + +::: + +## Conclusion + +The BEM naming convention is a powerful tool for organizing and maintaining CSS classes in your React applications. By following the BEM structure and naming conventions, you can create modular, reusable, and maintainable stylesheets that scale well with your project. BEM provides a clear and consistent approach to naming CSS classes, making it easier to understand and manage your styles across different components. By adopting the BEM naming convention, you can improve the readability, maintainability, and collaboration of your stylesheets, leading to a more efficient and productive development process. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/App.js b/courses/react-js/intermidiate-level/handling-data-flow/App.js new file mode 100644 index 000000000..59272b283 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/App.js @@ -0,0 +1,17 @@ +import React from "react"; +import { ThemeProvider } from "./ThemeContext"; +import Header from "./Header"; +import Content from "./Content"; + +function App() { + return ( + +
+
+ +
+
+ ); +} + +export default App; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/Content.js b/courses/react-js/intermidiate-level/handling-data-flow/Content.js new file mode 100644 index 000000000..d457c7448 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/Content.js @@ -0,0 +1,19 @@ +import React, { useContext } from "react"; +import { ThemeContext } from "./ThemeContext"; + +function Content() { + const { theme } = useContext(ThemeContext); + + return ( +
+

Content Area

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam + in turpis nec felis fermentum ultricies. Donec sit amet nunc + vitae libero ultricies ultricies. +

+
+ ); +} + +export default Content; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/Header.js b/courses/react-js/intermidiate-level/handling-data-flow/Header.js new file mode 100644 index 000000000..bf46a690a --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/Header.js @@ -0,0 +1,15 @@ +import React, { useContext } from "react"; +import { ThemeContext } from "./ThemeContext"; + +function Header() { + const { theme, toggleTheme } = useContext(ThemeContext); + + return ( +
+

Theme Switcher

+ +
+ ); +} + +export default Header; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/Counter.js b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/Counter.js new file mode 100644 index 000000000..5bac4174d --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/Counter.js @@ -0,0 +1,25 @@ +import React from "react"; +import { connect } from "react-redux"; + +function Counter({ count, increment, decrement }) { + return ( +
+

Count: {count}

+
+ + +
+
+ ); +} + +const mapStateToProps = (state) => ({ + count: state.count, +}); + +const mapDispatchToProps = (dispatch) => ({ + increment: () => dispatch({ type: "INCREMENT" }), + decrement: () => dispatch({ type: "DECREMENT" }), +}); + +export default connect(mapStateToProps, mapDispatchToProps)(Counter); \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/index.js b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/index.js new file mode 100644 index 000000000..7672a724b --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/index.js @@ -0,0 +1,17 @@ +import React from "react"; +import { Provider } from "react-redux"; +import store from "./store"; +import Counter from "./Counter"; + +function ReduxApp() { + return ( + +
+

Redux App

+ +
+
+ ); +} + +export default ReduxApp; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/reducers.js b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/reducers.js new file mode 100644 index 000000000..f26b88b20 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/reducers.js @@ -0,0 +1,16 @@ +const initialState = { + count: 0, + }; + + function counterReducer(state = initialState, action) { + switch (action.type) { + case "INCREMENT": + return { ...state, count: state.count + 1 }; + case "DECREMENT": + return { ...state, count: state.count - 1 }; + default: + return state; + } + } + + export default counterReducer; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/store.js b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/store.js new file mode 100644 index 000000000..feceed7a0 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/ReduxApp/store.js @@ -0,0 +1,6 @@ +import { createStore } from "redux"; +import rootReducer from "./reducers"; + +const store = createStore(rootReducer); + +export default store; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/ThemeContext.js b/courses/react-js/intermidiate-level/handling-data-flow/ThemeContext.js new file mode 100644 index 000000000..5038bcb8a --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/ThemeContext.js @@ -0,0 +1,19 @@ +import React, { createContext, useState } from "react"; + +const ThemeContext = createContext(); + +function ThemeProvider({ children }) { + const [theme, setTheme] = useState("light"); + + const toggleTheme = () => { + setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light")); + }; + + return ( + + {children} + + ); +} + +export { ThemeProvider, ThemeContext }; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/_category_.json b/courses/react-js/intermidiate-level/handling-data-flow/_category_.json new file mode 100644 index 000000000..9daff44b4 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 8: Handling Data Flow in React", + "position": 3, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to handle data flow in React. You will learn how to pass data from parent to child components, how to handle user input, and how to manage state in React components. You will also learn how to use React's built-in state management tools, such as the Context API and the useReducer hook. Finally, you will learn how to use React's built-in state management tools, such as the Context API and the useReducer hook." + } +} diff --git a/courses/react-js/intermidiate-level/handling-data-flow/lesson_1.md b/courses/react-js/intermidiate-level/handling-data-flow/lesson_1.md new file mode 100644 index 000000000..e784375b0 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/lesson_1.md @@ -0,0 +1,136 @@ +--- +id: lesson-1 +title: "Context API for managing global state without prop drilling (Optional)" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to use the Context API in React to manage global state without prop drilling. The Context API provides a way to pass data through the component tree without having to pass props down manually at every level. This lesson will introduce you to the Context API and show you how to use it to manage global state in your React applications." +tags: [courses, react-js, intermediate-level, state-management, context-api, prop-drilling] +--- + +import App from './App'; + +In React applications, managing shared state between components can be challenging, especially when components are not directly related in the component tree. The Context API is a feature in React that allows you to manage global state without prop drilling. The Context API provides a way to pass data through the component tree without having to pass props down manually at every level. This lesson will introduce you to the Context API and show you how to use it to manage global state in your React applications. + +## What is the Context API? + +The Context API is a feature in React that allows you to share data across the component tree without having to pass props down manually at every level. It provides a way to manage global state in your application and avoid prop drilling, where props are passed through multiple levels of components. + +The Context API consists of the following key concepts: + +1. **Context Object**: The context object is created using the `createContext` function from the `react` package. It represents the shared data that you want to pass down the component tree. +2. **Provider Component**: The provider component is used to wrap the part of the component tree where you want to make the context available. It accepts a `value` prop that contains the data you want to share. +3. **Consumer Component**: The consumer component is used to access the context data within a component. It uses the `useContext` hook to consume the context data provided by the nearest `Provider` component in the tree. +4. **Context Hook**: The `useContext` hook is used to consume the context data within a functional component. It takes the context object as an argument and returns the current context value. +5. **Context Type**: The `ContextType` is a property that can be added to a class component to access the context data. It provides a way to consume context data in class components. +6. **Context API with Class Components**: The Context API can also be used with class components by using the `Consumer` component and the `ContextType` property. This allows you to access context data in class components. +7. **Default Value**: The `createContext` function accepts a default value as an argument. This default value is used when a component does not have a matching `Provider` component in the tree. + +Here's an example of using the Context API to manage global state in a React application: + + + + ```jsx + import React from "react"; + import { ThemeProvider } from "./ThemeContext"; + import Header from "./Header"; + import Content from "./Content"; + + function App() { + return ( + +
+
+ +
+
+ ); + } + + export default App; + ``` +
+ + ```jsx + import React, { createContext, useState } from "react"; + const ThemeContext = createContext(); + + function ThemeProvider({ children }) { + const [theme, setTheme] = useState("light"); + + const toggleTheme = () => { + setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light")); + }; + + return ( + + {children} + + ); + } + + export { ThemeProvider, ThemeContext }; + ``` + + + ```jsx + import React, { useContext } from "react"; + import { ThemeContext } from "./ThemeContext"; + + function Header() { + const { theme, toggleTheme } = useContext(ThemeContext); + + return ( +
+

Theme Switcher

+ +
+ ); + } + + export default Header; + ``` +
+ + ```jsx + import React, { useContext } from "react"; + import { ThemeContext } from "./ThemeContext"; + + function Content() { + const { theme } = useContext(ThemeContext); + + return ( +
+

Content Area

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam + in turpis nec felis fermentum ultricies. Donec sit amet nunc + vitae libero ultricies ultricies. +

+
+ ); + } + + export default Content; + ``` +
+
+ +In this example, we have a `ThemeProvider` component that wraps the `Header` and `Content` components in the `App` component. The `ThemeProvider` component provides the theme data and the `toggleTheme` function to the `Header` and `Content` components using the `ThemeContext.Provider` component. The `Header` and `Content` components consume the theme data and the `toggleTheme` function using the `useContext` hook. + +When the "Toggle Theme" button in the `Header` component is clicked, it calls the `toggleTheme` function to update the theme state in the `ThemeProvider` component. This change in the theme state is reflected in the `Header` and `Content` components, allowing them to update their styles based on the theme. + + + + + +By using the Context API, we can manage global state in our application without having to pass props down manually through multiple levels of components. This makes it easier to share data across the component tree and avoid prop drilling. + +:::info + +The Context API is a powerful feature in React that allows you to manage global state in your application. It is especially useful when you have shared data that needs to be accessed by multiple components at different levels in the component tree. By using the Context API, you can avoid prop drilling and keep your components decoupled from each other. + +::: + +## Conclusion + +The Context API in React provides a way to manage global state in your application without prop drilling. By using the Context API, you can share data across the component tree and avoid passing props down manually at every level. This lesson introduced you to the Context API and showed you how to use it to manage global state in your React applications. You learned about the context object, provider component, consumer component, context hook, context type, and default value in the Context API. You also saw an example of using the Context API to manage global state in a React application. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/handling-data-flow/lesson_2.md b/courses/react-js/intermidiate-level/handling-data-flow/lesson_2.md new file mode 100644 index 000000000..5d7b2fe43 --- /dev/null +++ b/courses/react-js/intermidiate-level/handling-data-flow/lesson_2.md @@ -0,0 +1,162 @@ +--- +id: lesson-2 +title: "Introduction to Redux: Advanced state management for complex applications" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "Learn how to use Redux for advanced state management in React applications. Redux is a predictable state container for JavaScript apps that helps you manage complex application state in a more organized and efficient way. This lesson will introduce you to the core concepts of Redux and show you how to integrate Redux into your React applications." +tags: [courses, react-js, intermediate-level, state-management, redux, react-redux] +--- + +import ReduxApp from './ReduxApp'; + +In React applications, managing complex state across multiple components can be challenging, especially when components are not directly related in the component tree. Redux is a predictable state container for JavaScript apps that helps you manage complex application state in a more organized and efficient way. Redux provides a centralized store for your application's state and allows you to define actions and reducers to update the state in a predictable manner. This lesson will introduce you to the core concepts of Redux and show you how to integrate Redux into your React applications. + +## What is Redux? + +Redux is a state management library for JavaScript applications that provides a predictable state container. It helps you manage the state of your application in a more organized and efficient way by centralizing the state and defining actions and reducers to update the state. Redux follows a unidirectional data flow pattern, where the state is stored in a single store and can only be modified by dispatching actions. This pattern helps you keep your application's data in sync and makes it easier to debug and test your application. Redux is commonly used with React to manage the state of complex applications. + +The core concepts of Redux are: + +1. **Store**: The store is a centralized container that holds the state of your application. It provides methods to access the state, dispatch actions, and subscribe to changes in the state. The store is created using the `createStore` function from the `redux` package. +2. **Actions**: Actions are plain JavaScript objects that represent events in your application. They are used to describe what happened in your application and contain a `type` property that defines the action type. Actions are dispatched using the `dispatch` method on the store. +3. **Reducers**: Reducers are pure functions that specify how the state should change in response to an action. They take the current state and an action as arguments and return the new state. Reducers are combined using the `combineReducers` function from the `redux` package. +4. **Dispatch**: Dispatch is a method provided by the store to dispatch actions to update the state. When an action is dispatched, the store calls the reducers to calculate the new state based on the action type. +5. **Selectors**: Selectors are functions that extract specific pieces of state from the store. They help you access the state in a more organized way and avoid direct access to the store. +6. **Middleware**: Middleware is a function that intercepts actions before they reach the reducers. It provides a way to add additional functionality to the dispatch process, such as logging, async actions, or routing. Middleware is added to the store using the `applyMiddleware` function from the `redux` package. +7. **React-Redux**: React-Redux is the official Redux binding for React. It provides a set of APIs that allow you to connect your React components to the Redux store and access the state and dispatch actions in your components. + +Here's an example of using Redux to manage state in a React application: + + + + ```jsx title="src/App.js" + import React from "react"; + import { Provider } from "react-redux"; + import store from "./store"; + import Counter from "./Counter"; + + function App() { + return ( + +
+

Redux App

+ +
+
+ ); + } + + export default App; + ``` +
+ + ```jsx title="src/store.js" + import { createStore } from "redux"; + import rootReducer from "./reducers"; + + const store = createStore(rootReducer); + + export default store; + ``` + + + ```jsx title="src/reducers.js" + const initialState = { + count: 0, + }; + + function counterReducer(state = initialState, action) { + switch (action.type) { + case "INCREMENT": + return { ...state, count: state.count + 1 }; + case "DECREMENT": + return { ...state, count: state.count - 1 }; + default: + return state; + } + } + + export default counterReducer; + ``` + + + ```jsx title="src/Counter.js" + import React from "react"; + import { connect } from "react-redux"; + + function Counter({ count, increment, decrement }) { + return ( +
+

Count: {count}

+
+ + +
+
+ ); + } + + const mapStateToProps = (state) => ({ + count: state.count, + }); + + const mapDispatchToProps = (dispatch) => ({ + increment: () => dispatch({ type: "INCREMENT" }), + decrement: () => dispatch({ type: "DECREMENT" }), + }); + + export default connect(mapStateToProps, mapDispatchToProps)(Counter); + ``` +
+
+ +Now, Run application to see the output. + + + + + +In this example, we have a simple Redux counter application with the following components: + +- `App.js`: The main component that wraps the application with the `Provider` component from `react-redux` and renders the `Counter` component. The `Provider` component provides the Redux store to the application. +- `store.js`: The store configuration file that creates the Redux store using the `createStore` function from `redux` and the root reducer. +- `reducers.js`: The reducer file that defines the `counterReducer` function, which specifies how the state should change in response to the "INCREMENT" and "DECREMENT" actions. +- `Counter.js`: The counter component that displays the count value and provides buttons to increment and decrement the count. The `connect` function from `react-redux` is used to connect the component to the Redux store and map the state and dispatch functions to props. + +When the "Increment" or "Decrement" buttons are clicked in the `Counter` component, they dispatch the corresponding actions to update the count state in the Redux store. The `counterReducer` function then calculates the new state based on the action type, and the updated state is reflected in the `Counter` component. + +:::warning + +If you want to use Redux in your React application, you need to install the following packages: + +```bash +npm install redux react-redux +``` + +::: + +Redux provides a powerful and flexible way to manage state in complex React applications. By following the core concepts of Redux and integrating it with React using React-Redux, you can build scalable and maintainable applications with predictable state management. + +## Benefits of using Redux + +Using Redux for state management in React applications offers several benefits: + +1. **Predictable state management**: Redux follows a strict unidirectional data flow pattern, making it easier to understand how data changes in your application. +2. **Centralized state**: Redux provides a single source of truth for your application's state, making it easier to manage and debug the state. +3. **Debugging and testing**: Redux makes it easier to debug and test your application by providing a clear separation of concerns between actions, reducers, and components. +4. **Scalability**: Redux scales well with large applications by providing a structured way to manage state and data flow. +5. **Developer tools**: Redux comes with a set of developer tools that help you inspect the state, actions, and performance of your application during development. +6. **Middleware support**: Redux allows you to add middleware to intercept actions and add additional functionality to the dispatch process. +7. **Integration with React**: Redux integrates seamlessly with React using the React-Redux library, providing a set of APIs to connect your components to the Redux store. + +By leveraging the benefits of Redux, you can build robust and maintainable React applications that scale well with complex state management requirements. + +:::tip + +Redux is a powerful state management library for JavaScript applications that provides a predictable state container. By following the core concepts of Redux and integrating it with React using React-Redux, you can build scalable and maintainable applications with predictable state management. + +::: + +## Conclusion + +Redux is a predictable state container for JavaScript applications that helps you manage complex application state in a more organized and efficient way. In this lesson, you learned about the core concepts of Redux, including the store, actions, reducers, dispatch, selectors, middleware, and React-Redux. You also saw an example of using Redux to manage state in a React application and how to connect React components to the Redux store. By integrating Redux into your React applications, you can build scalable and maintainable applications with predictable state management. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/App.js b/courses/react-js/intermidiate-level/managing-complex-uis/App.js new file mode 100644 index 000000000..31f3e8cb2 --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/App.js @@ -0,0 +1,19 @@ +import React, { useState } from "react"; +import ParentComponent from "./ParentComponent"; + +function App() { + const [count, setCount] = useState(0); + + const incrementCount = () => { + setCount(count + 1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} + +export default App; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/ChildComponent.js b/courses/react-js/intermidiate-level/managing-complex-uis/ChildComponent.js new file mode 100644 index 000000000..f417fc64a --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/ChildComponent.js @@ -0,0 +1,12 @@ +import React from "react"; + +function ChildComponent({ incrementCount }) { + return ( +
+

Child Component

+ +
+ ); +} + +export default ChildComponent; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/ParentComponent.js b/courses/react-js/intermidiate-level/managing-complex-uis/ParentComponent.js new file mode 100644 index 000000000..14b84b967 --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/ParentComponent.js @@ -0,0 +1,14 @@ +import React from "react"; +import ChildComponent from "./ChildComponent"; + +function ParentComponent({ count, incrementCount }) { + return ( +
+

Parent Component

+

Count: {count}

+ +
+ ); +} + +export default ParentComponent; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/TodoApp.js b/courses/react-js/intermidiate-level/managing-complex-uis/TodoApp.js new file mode 100644 index 000000000..80312e3d1 --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/TodoApp.js @@ -0,0 +1,52 @@ +import React, { useState } from "react"; +import TodoList from "./TodoList"; + +function TodoApp() { + const [todos, setTodos] = useState([ + { id: 1, text: "Learn React", completed: false }, + { id: 2, text: "Build a project", completed: false }, + { id: 3, text: "Deploy to production", completed: false }, + ]); + const [newTodoText, setNewTodoText] = useState(""); + + const toggleTodo = (id) => { + setTodos((prevTodos) => + prevTodos.map((todo) => + todo.id === id ? { ...todo, completed: !todo.completed } : todo + ) + ); + }; + + const handleAddTodo = () => { + if (newTodoText.trim() !== "") { + setTodos((prevTodos) => [ + ...prevTodos, + { + id: prevTodos.length + 1, + text: newTodoText, + completed: false, + }, + ]); + setNewTodoText(""); + } + }; + + return ( +
+

Todo App

+
+ setNewTodoText(e.target.value)} + style={{ marginRight: "10px", padding: "5px"}} + /> + +
+ +
+ ); +} + +export default TodoApp; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/TodoItem.js b/courses/react-js/intermidiate-level/managing-complex-uis/TodoItem.js new file mode 100644 index 000000000..a0b53fda5 --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/TodoItem.js @@ -0,0 +1,35 @@ +import React from "react"; + +function TodoItem({ todo, toggleTodo }) { + const { id, text, completed } = todo; + + const handleToggle = () => { + toggleTodo && toggleTodo(id); + }; + + const handleKeyPress = (event) => { + if (event.key === 'Enter') { + handleToggle(); + } + }; + + return ( +
+ + {text} + +
+ ); +} + +export default TodoItem; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/TodoList.js b/courses/react-js/intermidiate-level/managing-complex-uis/TodoList.js new file mode 100644 index 000000000..44fabcfeb --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/TodoList.js @@ -0,0 +1,15 @@ +import React from "react"; +import TodoItem from "./TodoItem"; + +function TodoList({ todos, toggleTodo }) { + return ( +
+

Todo List

+ {todos.map((todo) => ( + + ))} +
+ ); +} + +export default TodoList; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/_category_.json b/courses/react-js/intermidiate-level/managing-complex-uis/_category_.json new file mode 100644 index 000000000..8041de6ef --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 7: Managing Complex UIs in React", + "position": 2, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to manage complex UIs in React. You will learn how to manage state in a React component, how to use React's lifecycle methods, and how to use React's context API to manage state across multiple components. You will also learn how to use React's ref API to interact with the DOM directly, and how to use React's error boundaries to handle errors in your application. Finally, you will learn how to use React's new hooks API to manage state and side effects in your components." + } +} diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/lesson_1.md b/courses/react-js/intermidiate-level/managing-complex-uis/lesson_1.md new file mode 100644 index 000000000..e50c7d5a5 --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/lesson_1.md @@ -0,0 +1,119 @@ +--- +id: lesson-1 +title: "Lifting state up for shared state management across components" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to lift state up in React to manage shared state across multiple components. Lifting state up is a common pattern in React applications that allows you to share state between components and keep your application's data in sync." +tags: [courses, react-js, intermediate-level, state-management, lifting-state-up] +--- + +import App from './App'; + +In React applications, managing shared state between components can be challenging, especially when components are not directly related in the component tree. Lifting state up is a common pattern in React that allows you to manage shared state in a parent component and pass it down to child components as props. This lesson will introduce you to the concept of lifting state up and show you how to use it to share state between components in your React applications. + +## What is lifting state up? + +Lifting state up is a pattern in React that involves moving the state from child components to their closest common ancestor in the component tree. By lifting state up, you can manage shared state in a parent component and pass it down to child components as props. This pattern helps you keep your application's data in sync and avoid prop drilling, where props are passed through multiple levels of components. + +Here's an example of lifting state up in a React application: + + + + ```jsx + import React, { useState } from "react"; + import ParentComponent from "./ParentComponent"; + + function App() { + const [count, setCount] = useState(0); + + const incrementCount = () => { + setCount(count + 1); + }; + + return ( +
+

Count: {count}

+ +
+ ); + } + + export default App; + ``` +
+ + ```jsx + import React from "react"; + import ChildComponent from "./ChildComponent"; + + function ParentComponent({ count, incrementCount }) { + return ( +
+

Parent Component

+

Count: {count}

+ +
+ ); + } + + export default ParentComponent; + ``` +
+ + ```jsx + import React from "react"; + + function ChildComponent({ incrementCount }) { + return ( +
+

Child Component

+ +
+ ); + } + + export default ChildComponent; + ``` +
+
+ +In this example, we have an `App` component that manages the `count` state using the `useState` hook. The `App` component passes the `count` state and an `incrementCount` function down to the `ParentComponent` as props. The `ParentComponent` then passes the `incrementCount` function down to the `ChildComponent` as a prop. When the `ChildComponent` button is clicked, it calls the `incrementCount` function to update the `count` state in the `App` component. + + + + + +By lifting the `count` state up to the `App` component, we can share the state between the `ParentComponent` and `ChildComponent` without having to pass the state through multiple levels of components. This pattern helps keep the application's data in sync and makes it easier to manage shared state across components. + +## Benefits of lifting state up + +Lifting state up has several benefits in React applications: + +- **Shared state management**: Lifting state up allows you to manage shared state in a parent component and pass it down to child components as props. This pattern helps keep the application's data in sync and avoids prop drilling. +- **Data flow control**: By lifting state up, you have more control over the data flow in your application. You can manage the state in a single location and pass it down to child components as needed. +- **Code organization**: Lifting state up helps organize your code by moving the state management logic to a common ancestor in the component tree. This makes it easier to understand and maintain the codebase. +- **Component reusability**: Components that rely on shared state can be reused in different parts of the application without having to manage the state separately. This improves the reusability and maintainability of your components. +- **Performance optimization**: Lifting state up can help optimize the performance of your application by reducing unnecessary re-renders of components that don't depend on the shared state. You can control when and how the state is updated to improve performance. +- **Scalability**: Lifting state up scales well with large applications by providing a centralized approach to managing shared state. As your application grows, you can easily add new components that rely on the shared state without affecting other parts of the application. +- **Debugging**: Lifting state up makes it easier to debug and troubleshoot state-related issues in your application. You can trace the flow of data from the parent component to child components to identify and fix problems more effectively. +- **Testing**: Components that rely on shared state can be tested more easily by mocking the state and props passed down from the parent component. This makes it easier to write unit tests and ensure the correctness of your components. +- **Separation of concerns**: Lifting state up promotes the separation of concerns by moving the state management logic out of individual components and into a common ancestor. This improves the maintainability and readability of your codebase. +- **State encapsulation**: By lifting state up, you encapsulate the state management logic in a single location, making it easier to reason about and update the state. This reduces the risk of state-related bugs and improves the predictability of your application. +- **Code quality**: Lifting state up improves the overall code quality of your application by enforcing a structured approach to managing shared state. You can follow best practices for state management and data flow control to create more maintainable and scalable React applications. +- **Developer experience**: Lifting state up enhances the developer experience by providing a clear and organized way to manage shared state in React applications. Developers can easily understand and work with components that rely on shared state, improving productivity and collaboration. +- **Best practices**: Lifting state up follows best practices for state management in React applications, ensuring that your codebase is well-organized and maintainable. You can leverage the power of React's component-based architecture to create robust and scalable applications. +- **Flexibility**: Lifting state up provides flexibility in managing shared state by allowing you to customize the data flow and state management logic based on your application's requirements. You can adapt the pattern to suit different use cases and scenarios in your application. + +By lifting state up in your React applications, you can create more maintainable, scalable, and performant components that share state effectively and improve the overall development experience of your projects. + +:::info Try it out + +Now that you've learned about lifting state up in React, try implementing this pattern in your own applications. Identify components that rely on shared state and move the state management logic to a common ancestor in the component tree. By lifting state up, you can improve the organization, reusability, and performance of your React components. + +Share your app with your friends or on social media. Let them know that you have learned how to lift state up in React and manage shared state across components. And Join our [Discord Community](https://discord.gg/5VjTyJcf) to share your work and get feedback from other learners. + +::: + +## Conclusion + +Lifting state up is a powerful pattern in React that allows you to manage shared state across components by moving the state to a common ancestor in the component tree. By lifting state up, you can improve the organization, reusability, and performance of your React components, making it easier to manage complex data flows and keep your application's data in sync. Start using the lifting state up pattern in your React applications to create more maintainable, scalable, and performant components that share state effectively and enhance the overall development experience of your projects. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/managing-complex-uis/lesson_2.md b/courses/react-js/intermidiate-level/managing-complex-uis/lesson_2.md new file mode 100644 index 000000000..7cde70851 --- /dev/null +++ b/courses/react-js/intermidiate-level/managing-complex-uis/lesson_2.md @@ -0,0 +1,186 @@ +--- +id: lesson-2 +title: "Understanding the challenges of prop drilling" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "Learn about the challenges of prop drilling in React applications and how to avoid them using context, Redux, or other state management libraries. Prop drilling can lead to complex and hard-to-maintain code, especially in large applications with deeply nested components." +tags: [courses, react-js, intermediate-level, state-management, prop-drilling, context-api, redux, state-management-libraries] +--- + +import TodoApp from './TodoApp'; + +In React applications, passing data through multiple levels of components using props can become cumbersome and lead to prop drilling. Prop drilling refers to the process of passing props down the component tree to child components that do not directly use the props, resulting in complex and hard-to-maintain code. This lesson will explore the challenges of prop drilling in React applications and discuss strategies to avoid them using context, Redux, or other state management libraries. + +## What is prop drilling? + +Prop drilling occurs when data needs to be passed from a parent component to a deeply nested child component through intermediate components that do not use the data themselves. This process can lead to several challenges, including: + +- **Complexity**: Prop drilling can make your codebase more complex and harder to understand, especially when passing props through multiple levels of components. +- **Coupling**: Components become tightly coupled to the data they receive through props, making it difficult to reuse or refactor components independently. +- **Maintenance**: As your application grows, managing prop drilling becomes more challenging, and refactoring components can lead to widespread changes in your codebase. +- **Performance**: Passing props through multiple levels of components can impact performance, especially when components re-render unnecessarily due to prop changes. +- **Debugging**: Debugging components that rely on prop drilling can be more difficult, as you need to trace the flow of props through the component tree. +- **Testing**: Writing tests for components that rely on prop drilling can be more complex, as you need to provide props at each level of the component tree. +- **Scalability**: Prop drilling becomes more problematic in large applications with deeply nested components, requiring more effort to manage data flow. +- **Flexibility**: Components become less flexible and reusable, as they rely on specific props passed down from parent components. +- **Maintainability**: Prop drilling can lead to code duplication and inconsistencies in how props are passed down the component tree, making it harder to maintain and update components. +- **State management**: Managing shared state between components using prop drilling can be challenging, especially when components are not directly related in the component tree. +- **Context switching**: Developers need to switch context frequently to understand how props are passed through the component tree, leading to cognitive overhead. +- **Developer experience**: Prop drilling can impact the developer experience by making it harder to work with components that rely on deeply nested props. +- **Code readability**: Code that relies on prop drilling can be less readable and maintainable, as developers need to understand the entire component tree to follow the flow of data. + +## How to avoid prop drilling + +To avoid the challenges of prop drilling in React applications, you can use the following strategies: + +### 1. Context API + +The Context API in React allows you to share data across the component tree without passing props manually at each level. By creating a context provider and consumer, you can pass data down the component tree without prop drilling. Context API is suitable for managing global or shared state in your application. + +### 2. Redux + +Redux is a state management library for React applications that provides a centralized store to manage application state. By using Redux, you can store and update shared state in a predictable and efficient way, avoiding prop drilling. Redux is suitable for managing complex state and data flow in large applications. + +### 3. State management libraries + +Other state management libraries like MobX, Recoil, or Zustand provide alternative solutions for managing state in React applications. These libraries offer different approaches to state management, allowing you to choose the one that best fits your application's needs. + +### 4. Higher-order components (HOCs) + +Higher-order components are functions that take a component as an argument and return a new component with additional props or functionality. By using HOCs, you can enhance components with shared logic or data without prop drilling. + +### 5. Render props + +Render props are a pattern in React where a component's prop is a function that returns a React element. By using render props, you can pass data or functionality down the component tree without prop drilling, making your components more flexible and reusable. + +### 6. Hooks (useContext, useReducer) + +React hooks like `useContext` and `useReducer` provide a way to manage state and share data between components without prop drilling. By using hooks, you can create reusable logic for managing state and avoid passing props through intermediate components. + +### 7. Component composition + +Component composition is a design pattern in React where components are composed of smaller, reusable components. By breaking down complex components into smaller pieces, you can reduce the need for prop drilling and make your codebase more modular and maintainable. + +By using these strategies, you can avoid the challenges of prop drilling in your React applications and create a more maintainable and scalable codebase. Each approach has its strengths and weaknesses, so choose the one that best fits your application's requirements and development workflow. + +## Live example of prop drilling + +Let's look at an example of prop drilling in a React application for Todo list management: + + + + ```jsx + import React, { useState } from "react"; + import TodoList from "./TodoList"; + + function TodoApp() { + const [todos, setTodos] = useState([ + { id: 1, text: "Learn React", completed: false }, + { id: 2, text: "Build a project", completed: false }, + { id: 3, text: "Deploy to production", completed: false }, + ]); + const [newTodoText, setNewTodoText] = useState(""); + + const toggleTodo = (id) => { + setTodos((prevTodos) => + prevTodos.map((todo) => + todo.id === id ? { ...todo, completed: !todo.completed } : todo + ) + ); + }; + + const handleAddTodo = () => { + if (newTodoText.trim() !== "") { + setTodos((prevTodos) => [ + ...prevTodos, + { + id: prevTodos.length + 1, + text: newTodoText, + completed: false, + }, + ]); + setNewTodoText(""); + } + }; + + return ( +
+

Todo App

+
+ setNewTodoText(e.target.value)} + style={{ marginRight: "10px", padding: "5px"}} + /> + +
+ +
+ ); + } + + export default TodoApp; + ``` +
+ + ```jsx + import React from "react"; + import TodoItem from "./TodoItem"; + + function TodoList({ todos, toggleTodo }) { + return ( +
+

Todo List

+ {todos.map((todo) => ( + + ))} +
+ ); + } + + export default TodoList; + ``` +
+ + ```jsx + import React from "react"; + function TodoItem({ todo, toggleTodo }) { + const { id, text, completed } = todo; + + const handleToggle = () => { + toggleTodo && toggleTodo(id); + }; + + return ( +
+ + {text} + +
+ ); + } + export default TodoItem; + ``` +
+
+ +In this example, the `TodoApp` component manages the state of todos and new todo text using the `useState` hook. It passes the todos array and `toggleTodo` function to the `TodoList` component as props. The `TodoList` component then maps over the todos array and renders a `TodoItem` component for each todo, passing the todo object and `toggleTodo` function as props. + + + + + +This example demonstrates prop drilling, as the `TodoApp` component passes down the todos array and `toggleTodo` function through the `TodoList` component to the `TodoItem` component. While this approach works for small applications, it can become cumbersome and hard to maintain as the application grows in complexity. + +## Conclusion + +Prop drilling can lead to complex and hard-to-maintain code in React applications, especially in large projects with deeply nested components. By understanding the challenges of prop drilling and using context, Redux, or other state management libraries, you can avoid prop drilling and manage shared state more effectively. These strategies help improve code maintainability, performance, and developer experience by providing a structured and scalable approach to managing data flow in your React applications. Choose the right approach based on your application's requirements and development workflow to create more maintainable and scalable React components. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/routing-for-spas/_category_.json b/courses/react-js/intermidiate-level/routing-for-spas/_category_.json new file mode 100644 index 000000000..d77f2f743 --- /dev/null +++ b/courses/react-js/intermidiate-level/routing-for-spas/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 10: Routing for SPAs in React", + "position": 5, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to implement routing in a single-page application (SPA) using React Router. You will learn how to set up routes, create nested routes, and pass data between routes. You will also learn how to use URL parameters and query strings to pass data between routes. Finally, you will learn how to use the useHistory hook to programmatically navigate between routes." + } +} diff --git a/courses/react-js/intermidiate-level/routing-for-spas/lesson_1.md b/courses/react-js/intermidiate-level/routing-for-spas/lesson_1.md new file mode 100644 index 000000000..63782f864 --- /dev/null +++ b/courses/react-js/intermidiate-level/routing-for-spas/lesson_1.md @@ -0,0 +1,159 @@ +--- +id: lesson-1 +title: "Introduction to routing concepts in React applications" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to implement client-side routing in React applications using the React Router library. Routing is an essential concept in web development that allows you to navigate between different pages or views in a single-page application (SPA). React Router provides a declarative way to define routes, handle navigation, and manage the application's UI based on the current URL." +tags: + [ + courses, + react-js, + intermediate-level, + routing, + react-router, + single-page-applications, + ] +--- + +In React applications, routing is the process of navigating between different pages or views based on the URL. Routing is an essential concept in web development that allows you to create multi-page experiences in a single-page application (SPA). React Router is a popular library that provides routing capabilities for React applications and allows you to define routes, handle navigation, and manage the application's UI based on the current URL. + +This lesson will introduce you to routing concepts in React applications and show you how to implement client-side routing using the React Router library. You'll learn how to define routes, handle navigation events, and render different components based on the current URL. By the end of this lesson, you'll have a solid understanding of how routing works in React applications and how to create dynamic and interactive user experiences using React Router. + +## What is routing in React? + +Routing in React refers to the process of mapping URLs to different components or views in a single-page application. In traditional web applications, each URL corresponds to a separate HTML page that is loaded from the server. However, in SPAs built with React, the entire application is loaded once, and routing is handled on the client-side using JavaScript. + +React Router is a library that provides routing capabilities for React applications and allows you to define routes using a declarative syntax. With React Router, you can create routes that match specific URLs and render different components based on the current URL. React Router also provides features like nested routes, route parameters, and route transitions to create dynamic and interactive user interfaces. + +Here's an example of routing in a React application using React Router: + + + + ```jsx + import React from "react"; + import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; + import Home from "./Home"; + import About from "./About"; + import Contact from "./Contact"; + + function App() { + return ( + + + } /> + } /> + } /> + + + ); + } + + export default App; + ``` + + + + ```jsx + import React from "react"; + + function Home() { + return

Home Page

; + } + + export default Home; + ``` + +
+ + ```jsx + import React from "react"; + + function About() { + return

About Page

; + } + + export default About; + ``` + +
+ + ```jsx + import React from "react"; + + function Contact() { + return

Contact Page

; + } + + export default Contact; + ``` + +
+
+ +In this example, we define routes for the home, about, and contact pages using the `Route` component from React Router. The `path` prop specifies the URL pattern that should match the route, and the `element` prop specifies the component to render when the route matches. By wrapping our routes in a `Router` component, we enable client-side routing in our React application. + + + + +
+

Home Page

+
+
+
+ + +
+

About Page

+
+
+
+ + +
+

Contact Page

+
+
+
+
+ +When a user navigates to different URLs in the application, React Router matches the URL to the defined routes and renders the corresponding components. This allows us to create a multi-page experience within a single-page application and provide a seamless navigation experience to the users. React Router also provides features like nested routes, route parameters, and route transitions to build more complex routing logic in React applications. + +:::warning + +If you want to follow along with the examples in this lesson, make sure to install the `react-router-dom` package in your React project. + +```bash title="terminal" +npm install react-router-dom +``` + +::: + +## Key concepts in React Router + +React Router provides several key concepts that are essential for building routing logic in React applications: + +- **Route**: The `Route` component is used to define a route in the application. It specifies the URL pattern that should match the route and the component to render when the route matches. +- **Router**: The `Router` component is used to wrap the application and enable client-side routing. React Router provides different router implementations like `BrowserRouter`, `HashRouter`, and `MemoryRouter` to handle routing based on the browser's URL. +- **Routes**: The `Routes` component is used to define a collection of routes within the application. It allows you to group multiple routes together and render them based on the current URL. +- **Link**: The `Link` component is used to create hyperlinks that navigate to different routes in the application. It provides a declarative way to handle navigation events and update the URL without reloading the page. +- **Route parameters**: Route parameters allow you to extract dynamic segments from the URL and pass them as props to the rendered component. This enables you to create routes that accept variable values and render components based on the URL parameters. +- **Nested routes**: Nested routes allow you to define routes within other routes to create a hierarchy of components. This is useful for building complex layouts and nested views in React applications. +- **Route transitions**: React Router provides support for route transitions, allowing you to animate the transition between different routes. This can enhance the user experience and provide visual feedback when navigating between pages. +- **Programmatic navigation**: React Router provides a `useNavigate` hook and a `navigate` function that allow you to programmatically navigate to different routes in the application. This is useful for handling navigation events in response to user interactions or application logic. +- **Route matching**: React Router uses a matching algorithm to determine which route should be rendered based on the current URL. It supports exact matching, partial matching, and custom matching strategies to define how routes should be matched against the URL. +- **Route guards**: Route guards allow you to protect routes based on certain conditions or permissions. You can use route guards to restrict access to specific routes, redirect users to login pages, or perform authentication checks before rendering a route. +- **Route context**: React Router provides a `useParams`, `useLocation`, and `useNavigate` hooks that allow you to access route parameters, location information, and navigation functions within your components. This makes it easy to interact with the current route and handle routing logic in your application. +- **Route configuration**: React Router allows you to configure routes using a declarative syntax that makes it easy to define routes, nested routes, and route transitions. You can also use route configuration objects to define routes programmatically and generate routes dynamically based on certain conditions. +- **Route history**: React Router maintains a history stack that keeps track of the user's navigation history and allows you to navigate back and forth between different routes. This history stack can be accessed using the `useHistory` hook or the `useNavigate` hook to implement custom navigation logic in your application. + +By understanding these key concepts, you can build powerful routing logic in React applications and create dynamic and interactive user experiences using React Router. Routing is an essential part of modern web development, and React Router provides a robust solution for managing routing in React applications. + +:::info + +**Note:** React Router is a popular library for client-side routing in React applications. It provides a flexible and declarative way to define routes, handle navigation events, and manage the application's UI based on the current URL. React Router is widely used in the React community and is recommended for building complex routing logic in React applications. + +::: + +## Conclusion + +In this lesson, you learned about routing concepts in React applications and how to implement client-side routing using the React Router library. Routing allows you to navigate between different pages or views in a single-page application and create dynamic user experiences based on the current URL. React Router provides a declarative way to define routes, handle navigation events, and manage the application's UI based on the URL. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/routing-for-spas/lesson_2.md b/courses/react-js/intermidiate-level/routing-for-spas/lesson_2.md new file mode 100644 index 000000000..f10f16247 --- /dev/null +++ b/courses/react-js/intermidiate-level/routing-for-spas/lesson_2.md @@ -0,0 +1,198 @@ +--- +id: lesson-2 +title: "Using React Router for navigation between views" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "In this lesson, we will learn how to use React Router to navigate between views in a single-page application." +tags: + [ + courses, + react-js, + intermidiate-level, + routing-for-spas, + navigation, + react-router, + ] +--- + +In this lesson, we will learn how to use React Router to navigate between views in a single-page application. React Router is a popular library for routing in React applications. It allows you to define routes and navigate between views using a declarative syntax. + +## Setting up React Router + +To get started with React Router, you need to install the `react-router-dom` package. You can do this by running the following command: + +```bash +npm install react-router-dom +``` + +Once you have installed the `react-router-dom` package, you can start using React Router in your application. + +## Creating routes with React Router + +To define routes in your application, you need to use the `BrowserRouter` and `Route` components provided by React Router. The `BrowserRouter` component is used to wrap your application and provide routing functionality, while the `Route` component is used to define individual routes. + +Here's an example of how you can define routes in your application: + + + + ```jsx title="/src/App.js" + import React from 'react'; + import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; + import Header from './Header'; + import Home from './Home'; + import About from './About'; + import Contact from './Contact'; + + function App() { + return ( + <> +

My App

+
+ + + } /> + } /> + } /> + + + + ); + } + + export default App; + ``` + + In this example, we have defined three routes: `/`, `/about`, and `/contact`. Each route is associated with a component that will be rendered when the route matches the current URL. The `Router` component wraps the `Routes` component and provides the routing functionality to the application. The `Header` component is used to display a navigation menu that allows the user to navigate between the different views. + + + + ```jsx title="/src/Header.js" + import React from 'react'; + import { Link } from 'react-router-dom'; + + function Header() { + return ( + + ); + } + + export default Header; + ``` + + The `Header` component displays a navigation menu with links to the different views in the application. The `Link` component provided by React Router is used to create links that navigate to the specified route when clicked. + + + + ```jsx title="/src/Home.js" + import React from 'react'; + + function Home() { + return ( +
+

Home

+

Welcome to the home page!

+
+ ); + } + + export default Home; + ``` + + The `Home` component displays the content for the home page. When the user navigates to the `/` route, this component will be rendered. + +
+ + ```jsx title="/src/About.js" + import React from 'react'; + + function About() { + return ( +
+

About

+

Welcome to the about page!

+
+ ); + } + + export default About; + ``` + + The `About` component displays the content for the about page. When the user navigates to the `/about` route, this component will be rendered. + +
+ + ```jsx title="/src/Contact.js" + import React from 'react'; + + function Contact() { + return ( +
+

Contact

+

Welcome to the contact page!

+
+ ); + } + + export default Contact; + ``` + + The `Contact` component displays the content for the contact page. When the user navigates to the `/contact` route, this component will be rendered. +
+ + +In this example, we have defined three routes: `/`, `/about`, and `/contact`. Each route is associated with a component that will be rendered when the route matches the current URL. The `Router` component wraps the `Routes` component and provides the routing functionality to the application. The `Header` component is used to display a navigation menu that allows the user to navigate between the different views. + +## Navigating between views + +To navigate between views in your application, you can use the `Link` component provided by React Router. The `Link` component creates a hyperlink that navigates to the specified route when clicked. + +Here's an example of how you can use the `Link` component to create navigation links in your application: + +```jsx title="/src/Header.js" +import React from 'react'; +import { Link } from 'react-router-dom'; + +function Header() { + return ( + + ); +} + +export default Header; +``` + +In this example, we have created navigation links for the home, about, and contact views using the `Link` component. When the user clicks on one of these links, they will be navigated to the corresponding route. + +:::info + +The `Link` component provided by React Router is similar to the `` element in HTML, but it uses the React Router routing system to navigate between views in a single-page application. + +::: + +## Conclusion + +In this lesson, we learned how to use React Router to navigate between views in a single-page application. React Router provides a declarative way to define routes and navigate between views using a simple and intuitive API. By using React Router, you can create complex navigation structures in your application with ease. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/routing-for-spas/lesson_3.md b/courses/react-js/intermidiate-level/routing-for-spas/lesson_3.md new file mode 100644 index 000000000..9eee591d6 --- /dev/null +++ b/courses/react-js/intermidiate-level/routing-for-spas/lesson_3.md @@ -0,0 +1,121 @@ +--- +id: lesson-3 +title: "Implementing nested routes for intricate layouts" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "In this lesson, we will learn how to implement nested routes in React Router to create intricate layouts and nested views in a single-page application." +tags: [courses, react-js, intermidiate-level, routing-for-spas, nested-routes, react-router] +--- + +In this lesson, we will learn how to implement nested routes in React Router to create intricate layouts and nested views in a single-page application. Nested routes allow you to define routes within routes, enabling you to create complex layouts with multiple levels of nesting. + +## Setting up nested routes + +To implement nested routes in React Router, you can use the `Routes` and `Route` components to define the nested routes. The `Routes` component is used to group multiple `Route` components together and define the nested routes. + +Here's an example of how you can implement nested routes in your application: + + + + ```jsx title="/src/App.js" + import React from 'react'; + import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; + import Header from './Header'; + import Home from './Home'; + import About from './About'; + import Contact from './Contact'; + import Profile from './Profile'; + import Settings from './Settings'; + + function App() { + return ( + <> +

My App

+
+ + + } /> + } /> + } /> + }> + } /> + + + + + ); + } + + export default App; + ``` + + + ```jsx title="/src/Header.js" + import React from 'react'; + import { Link } from 'react-router-dom'; + + function Header() { + return ( + + ); + } + + export default Header; + ``` + + + ```jsx title="/src/Profile.js" + import React from 'react'; + import { Routes, Route } from 'react-router-dom'; + + function Profile() { + return ( +
+

Profile

+ {/* Nested route for settings */} + + } /> + +
+ ); + } + + export default Profile; + ``` +
+ + ```jsx title="/src/Settings.js" + import React from 'react'; + + function Settings() { + return ( +
+

Settings

+

Profile settings go here...

+
+ ); + } + + export default Settings; + ``` +
+ + + +In the example above, we have defined a nested route for the `Profile` component. When the user navigates to the `/profile` route, the `Profile` component is rendered, and the nested route for `settings` is also defined within the `Profile` component. This allows us to create a nested view for the settings page within the profile page. + +By using nested routes, you can create intricate layouts and nested views in your single-page application, making it easier to manage complex routing scenarios. + +In the next lesson, we will learn how to implement route parameters in React Router to handle dynamic routing scenarios. + + +## Conclusion + +In this lesson, we learned how to implement nested routes in React Router to create intricate layouts and nested views in a single-page application. Nested routes allow you to define routes within routes, enabling you to create complex layouts with multiple levels of nesting. By using nested routes, you can manage complex routing scenarios and create a more structured application layout. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/working-with-apis/FetchDataExample.js b/courses/react-js/intermidiate-level/working-with-apis/FetchDataExample.js new file mode 100644 index 000000000..6d1117b15 --- /dev/null +++ b/courses/react-js/intermidiate-level/working-with-apis/FetchDataExample.js @@ -0,0 +1,40 @@ +import React, { useState, useEffect } from "react"; +import axios from "axios"; + +function FetchDataExample() { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + const fetchData = async () => { + try { + const response = await axios.get("https://jsonplaceholder.typicode.com/users"); + setData(response.data); + setLoading(false); + } catch (error) { + setError(error.message); + setLoading(false); + } + }; + + fetchData(); + }, []); + + return ( +
+

Fetch Data Example

+ {loading ?

Loading...

: ( + error ?

Error: {error}

: ( +
    + {data && data.map((item) => ( +
  • {item.name}
  • + ))} +
+ ) + )} +
+ ); +} + +export default FetchDataExample; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/working-with-apis/UserList.js b/courses/react-js/intermidiate-level/working-with-apis/UserList.js new file mode 100644 index 000000000..a06cd021f --- /dev/null +++ b/courses/react-js/intermidiate-level/working-with-apis/UserList.js @@ -0,0 +1,25 @@ +import React, { useState, useEffect } from "react"; + +function UserList() { + const [users, setUsers] = useState([]); + + useEffect(() => { + fetch("https://jsonplaceholder.typicode.com/users") + .then((response) => response.json()) + .then((data) => setUsers(data)) + .catch((error) => console.error("Error fetching data:", error)); + }, []); + + return ( +
+

User List

+
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+
+ ); +} + +export default UserList; \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/working-with-apis/_category_.json b/courses/react-js/intermidiate-level/working-with-apis/_category_.json new file mode 100644 index 000000000..387b92ad4 --- /dev/null +++ b/courses/react-js/intermidiate-level/working-with-apis/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Module 9: Working with APIs in React", + "position": 4, + "link": { + "type": "generated-index", + "description": "In this module, you will learn how to work with APIs in React. You will learn how to fetch data from an API and display it in your React application. You will also learn how to use the Axios library to make API requests in React. Finally, you will learn how to use the React Router library to create a multi-page application that fetches data from an API." + } +} diff --git a/courses/react-js/intermidiate-level/working-with-apis/lesson_1.md b/courses/react-js/intermidiate-level/working-with-apis/lesson_1.md new file mode 100644 index 000000000..af0bc7899 --- /dev/null +++ b/courses/react-js/intermidiate-level/working-with-apis/lesson_1.md @@ -0,0 +1,135 @@ +--- +id: lesson-1 +title: "Making API calls using fetch() or axios" +sidebar_label: Lesson - 1 +sidebar_position: 1 +description: "Learn how to make API calls in React using the fetch() method or the axios library. Making API calls is a common task in web development, and React provides several ways to fetch data from external APIs and update your application's state with the response." +tags: [courses, react-js, intermediate-level, api-calls, fetch, axios, state-management] +--- + +import UserList from './UserList'; + +In React applications, making API calls to fetch data from external services is a common task. You can use the `fetch()` method or the `axios` library to make HTTP requests and handle the response data in your React components. This lesson will show you how to make API calls using `fetch()` and `axios` and update your application's state with the fetched data. + +## Making API calls with fetch() + +The `fetch()` method is a built-in browser API that allows you to make HTTP requests to external services and fetch data asynchronously. You can use `fetch()` to make GET, POST, PUT, DELETE, and other types of requests to interact with RESTful APIs and retrieve data in JSON, XML, or other formats. + +Here's an example of making an API call using `fetch()` in a React component: + +```jsx title="/src/components/UserList.js" +import React, { useState, useEffect } from "react"; + +function UserList() { + const [users, setUsers] = useState([]); + + useEffect(() => { + fetch("https://jsonplaceholder.typicode.com/users") + .then((response) => response.json()) + .then((data) => setUsers(data)) + .catch((error) => console.error("Error fetching data:", error)); + }, []); + + return ( +
+

User List

+
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+
+ ); +} + +export default UserList; +``` + + + + + +In this example, the `UserList` component uses the `fetch()` method to make a GET request to the JSONPlaceholder API and fetch a list of users. The fetched data is stored in the `users` state using the `setUsers` function, and the list of users is rendered in the component's UI. + +## Making API calls with axios + +Axios is a popular JavaScript library that provides a simple and easy-to-use API for making HTTP requests in the browser and Node.js environments. You can use axios to make GET, POST, PUT, DELETE, and other types of requests to interact with RESTful APIs and handle the response data in your React components. + +Here's an example of making an API call using axios in a React component: + +```jsx title="/src/components/UserList.js" +import React, { useState, useEffect } from "react"; + +function UserList() { + const [users, setUsers] = useState([]); + + useEffect(() => { + axios.get("https://jsonplaceholder.typicode.com/users") + .then((response) => setUsers(response.data)) + .catch((error) => console.error("Error fetching data:", error)); + }, []); + + return ( +
+

User List

+
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+
+ ); +} + +export default UserList; +``` + + + + + +In this example, the `UserList` component uses the `axios.get()` method to make a GET request to the JSONPlaceholder API and fetch a list of users. The fetched data is stored in the `users` state using the `setUsers` function, and the list of users is rendered in the component's UI. + +:::info + +To use axios in your React application, you need to install the axios library by running the following command: + +```bash title="terminal" +npm install axios +``` + +::: + +## When to use fetch() vs. axios + +Both `fetch()` and axios are powerful tools for making API calls in React applications. Here are some considerations to help you decide which method to use: + +- **fetch()**: The `fetch()` method is built into modern browsers and provides a simple and lightweight way to make HTTP requests. It is suitable for basic API calls and can be used without additional dependencies. However, `fetch()` has a lower-level API compared to axios and may require more code to handle common use cases like error handling and request cancellation. + +- **axios**: The axios library provides a more feature-rich and user-friendly API for making HTTP requests. It supports features like request and response interceptors, automatic JSON parsing, and error handling out of the box. If you need advanced functionality or want a more convenient API for working with APIs, axios is a good choice. + +You can choose the method that best fits your project requirements and preferences when working with API calls in React. + +## Differences between fetch() and axios + +Here are some key differences between `fetch()` and axios: + +|No. | Feature | fetch() | axios | +|:---|:-----------------|:--------|:------| +|1. | Browser support | Modern browsers | All browsers | +|2. | API simplicity | Low-level API | High-level API | +|3. | Error handling | Manual handling | Automatic handling | +|4. | Request headers | Manual configuration | Automatic configuration | +|5. | Interceptors | Not supported | Supported | +|6. | JSON parsing | Manual parsing | Automatic parsing | +|7. | Request cancellation | Manual handling | Automatic handling | +|8. | File uploads | Supported | Supported | +|9. | Custom instances | Not supported | Supported | +|10. | Promise chaining | Yes | Yes | + +Both `fetch()` and axios have their strengths and weaknesses, and you can choose the method that best fits your project requirements and development workflow when working with API calls in React. + + +## Conclusion + +In this lesson, you learned how to make API calls in React using the `fetch()` method and the axios library. Both `fetch()` and axios are powerful tools for fetching data from external APIs and updating your application's state with the response. You can choose the method that best fits your project requirements and preferences when working with API calls in React. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/working-with-apis/lesson_2.md b/courses/react-js/intermidiate-level/working-with-apis/lesson_2.md new file mode 100644 index 000000000..51de1830f --- /dev/null +++ b/courses/react-js/intermidiate-level/working-with-apis/lesson_2.md @@ -0,0 +1,256 @@ +--- +id: lesson-2 +title: "Handling asynchronous operations (promises, async/await)" +sidebar_label: Lesson - 2 +sidebar_position: 2 +description: "Learn how to handle asynchronous operations in React using promises, async/await, and the useEffect hook. Asynchronous operations are common in web development, and React provides several ways to manage asynchronous code and update your application's state with the results." +tags: + [ + courses, + react-js, + intermediate-level, + asynchronous-operations, + promises, + async-await, + useEffect-hook, + ] +--- + +In React applications, handling asynchronous operations like fetching data from external APIs, reading/writing to a database, or performing time-consuming tasks is a common requirement. Asynchronous operations are tasks that don't block the main thread and allow your application to continue running while waiting for the operation to complete. React provides several ways to handle asynchronous code, including promises, async/await, and the `useEffect` hook. + +This lesson will introduce you to handling asynchronous operations in React using promises, async/await, and the `useEffect` hook. You'll learn how to fetch data from an external API, update your application's state with the fetched data, and handle loading and error states in your components. + +## What are asynchronous operations? + +Asynchronous operations in JavaScript are tasks that run independently of the main thread and don't block the execution of other code. Common examples of asynchronous operations include fetching data from an external API, reading/writing to a database, and handling user input events. Asynchronous code is essential for building responsive and interactive web applications that can perform multiple tasks concurrently. + +Here's an example of an asynchronous operation in React using a `setTimeout` function: + + + + ```jsx title="/src/components/AsyncOperationExample.js" + import React, { useState, useEffect } from "react"; + + function AsyncOperationExample() { + const [loading, setLoading] = useState(true); + + useEffect(() => { + setTimeout(() => { + setLoading(false); + }, 3000); + }, []); + + return ( +
+

Async Operation Example

+ {loading ?

Loading...

:

Async operation completed!

} +
+ ); + } + + export default AsyncOperationExample; + ``` + +
+ + ```jsx live + function AsyncOperationExample() { + const [loading, setLoading] = useState(true); + + setTimeout(() => { + setLoading(false); + }, 3000); + + return ( +
+ {loading ?

Loading...

:

Async operation completed!

} +
+ ); + } + ``` + +
+
+ +In this example, the `AsyncOperationExample` component uses a `setTimeout` function to simulate an asynchronous operation that takes 3 seconds to complete. The `loading` state is initially set to `true`, and after 3 seconds, it's updated to `false`, indicating that the asynchronous operation has completed. + +## Handling asynchronous operations with promises + +Promises are a built-in JavaScript feature that allows you to work with asynchronous code in a more readable and manageable way. Promises represent the eventual completion (or failure) of an asynchronous operation and provide a clean syntax for handling asynchronous tasks. You can use promises to fetch data from an external API, read/write to a database, or perform other asynchronous operations in your React components. + +Here's an example of fetching data from an external API using promises in a React component: + + + + ```jsx title="/src/components/UserList.js" + import React, { useState, useEffect } from "react"; + + function UserList() { + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + fetch("https://jsonplaceholder.typicode.com/users") + .then((response) => response.json()) + .then((data) => { + setUsers(data); + setLoading(false); + }) + .catch((error) => console.error("Error fetching data:", error)); + }, []); + + return ( +
+

User List

+ {loading ? ( +

Loading...

+ ) : ( +
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+ )} +
+ ); + } + + export default UserList; + ``` + +
+ + ```jsx live + function UserList() { + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + fetch("https://jsonplaceholder.typicode.com/users") + .then((response) => response.json()) + .then((data) => { + setUsers(data); + setLoading(false); + }) + .catch((error) => console.error("Error fetching data:", error)); + }, []); + + return ( +
+

User List

+ {loading ? ( +

Loading...

+ ) : ( +
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+ )} +
+ ); + } + ``` + +
+
+ +In this example, the `UserList` component uses the `fetch` API to make a GET request to the JSONPlaceholder API and fetch a list of users. The `fetch` function returns a promise that resolves with the response to the request. You can use the `then` method to handle the response data and update the component's state with the fetched users. + +## Handling asynchronous operations with async/await + +Async/await is a modern JavaScript feature that provides a more concise and readable way to work with asynchronous code. Async functions return a promise that resolves with the function's return value, allowing you to use the `await` keyword to pause the execution of the function until the promise is resolved. You can use async/await to fetch data from an external API, read/write to a database, or perform other asynchronous tasks in your React components. + +Here's an example of fetching data from an external API using async/await in a React component: + + + + ```jsx title="/src/components/UserList.js" + import React, { useState, useEffect } from "react"; + + function UserList() { + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const fetchData = async () => { + try { + const response = await fetch("https://jsonplaceholder.typicode.com/users"); + const data = await response.json(); + setUsers(data); + setLoading(false); + } catch (error) { + console.error("Error fetching data:", error); + } + }; + + fetchData(); + }, []); + + return ( +
+

User List

+ {loading ? ( +

Loading...

+ ) : ( +
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+ )} +
+ ); + } + + export default UserList; + ``` +
+ + ```jsx live + function UserList() { + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const fetchData = async () => { + try { + const response = await fetch("https://jsonplaceholder.typicode.com/users"); + const data = await response.json(); + setUsers(data); + setLoading(false); + } catch (error) { + console.error("Error fetching data:", error); + } + }; + fetchData(); + }, []); + + return ( +
+

User List

+ {loading ? ( +

Loading...

+ ) : ( +
    + {users.map((user) => ( +
  • {user.name}
  • + ))} +
+ )} +
+ ); + } + ``` +
+
+ +In this example, the `UserList` component uses an async function to fetch data from the JSONPlaceholder API using the `fetch` API and the `await` keyword. The `fetchData` function is defined as an async function that makes an API call to fetch a list of users. The `await` keyword pauses the execution of the function until the promise is resolved, allowing you to handle the response data and update the component's state with the fetched users. + +:::info +When using async/await in React components, make sure to handle errors using a `try/catch` block to gracefully handle any exceptions that may occur during the asynchronous operation. +::: + +## Conclusion + +Handling asynchronous operations in React is a crucial skill for building modern web applications that interact with external APIs, databases, and other services. By using promises, async/await, and the `useEffect` hook, you can manage asynchronous code effectively and update your application's state with the results of asynchronous tasks. Practice working with asynchronous operations in React to build responsive and interactive applications that provide a seamless user experience. \ No newline at end of file diff --git a/courses/react-js/intermidiate-level/working-with-apis/lesson_3.md b/courses/react-js/intermidiate-level/working-with-apis/lesson_3.md new file mode 100644 index 000000000..7b602b458 --- /dev/null +++ b/courses/react-js/intermidiate-level/working-with-apis/lesson_3.md @@ -0,0 +1,97 @@ +--- +id: lesson-3 +title: "Rendering fetched data from APIs" +sidebar_label: Lesson - 3 +sidebar_position: 3 +description: "Learn how to render data fetched from external APIs in React components. Rendering fetched data is a common task in web development, and React provides a way to update your application's UI with the data retrieved from API calls." +tags: [courses, react-js, intermediate-level, api-calls, fetch, axios, state-management, rendering-data] +--- + +import FetchDataExample from "./FetchDataExample"; + +In React applications, rendering data fetched from external APIs is a common task that allows you to display dynamic content in your components. You can use the data retrieved from API calls to update your application's state and render the content in your UI. This lesson will show you how to render data fetched from APIs in React components and handle loading and error states when fetching data. + +## Rendering fetched data in React components + +Rendering data fetched from external APIs in React components involves making API calls to fetch the data and updating the component's state with the response. Once the data is available, you can render it in your component's UI using JSX and JavaScript expressions. + +Here's an example of rendering fetched data in a React component: + +```jsx title="/src/components/FetchDataExample.js" +import React, { useState, useEffect } from "react"; +import axios from "axios"; + +function FetchDataExample() { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + const fetchData = async () => { + try { + const response = await axios.get("https://jsonplaceholder.typicode.com/users"); + setData(response.data); + setLoading(false); + } catch (error) { + setError(error.message); + setLoading(false); + } + }; + + fetchData(); + }, []); + + return ( +
+

Fetch Data Example

+ {loading ?

Loading...

: ( + error ?

Error: {error}

: ( +
    + {data && data.map((item) => ( +
  • {item.name}
  • + ))} +
+ ) + )} +
+ ); +} + +export default FetchDataExample; +``` + + + + + +In this example, the `FetchDataExample` component uses the `axios` library to make a GET request to an external API and fetch a list of items. The component's state includes variables to store the fetched data, loading state, and error message. The `useEffect` hook is used to fetch the data when the component mounts, and the component's UI is updated based on the loading and error states. + +## Key points to remember + +- Use the `fetch` API or libraries like `axios` to make API calls in React components. +- Update the component's state with the fetched data, loading state, and error state. +- Render the fetched data in your component's UI using JSX and JavaScript expressions. +- Handle loading and error states when fetching data to provide a better user experience. +- Use the `useEffect` hook to fetch data when the component mounts or when dependencies change. +- Consider using async/await for handling asynchronous operations in your React components. +- Test your components to ensure they render the fetched data correctly and handle loading and error states. +- Use conditional rendering to display loading indicators or error messages based on the component's state. +- Implement error handling to catch and display errors that occur during API calls. +- Update the component's state with the fetched data to trigger a re-render of the component. +- Use the `map` method to iterate over the fetched data and render it in your component's UI. +- Provide feedback to users when data is being fetched or an error occurs to improve the user experience. +- Use CSS styles or loading spinners to indicate loading states in your components. +- Consider using placeholders or skeleton screens to improve the perceived performance of your application. +- Optimize API calls by debouncing or throttling requests to prevent excessive requests to the server. + +In the next lesson, you will learn how to handle user input and update the component's state based on user interactions in React components. + +:::info Challenge🚀 + +Modify the `FetchDataExample` component to display a loading spinner while fetching data from the API. You can use CSS styles or a library like `react-spinners` to create a loading indicator. + +::: + +## Conclusion + +Rendering fetched data from APIs in React components is a common task that allows you to display dynamic content in your application. By making API calls, updating the component's state, and rendering the data in your UI, you can create interactive and data-driven components in React. Handling loading and error states when fetching data is essential to provide a better user experience and improve the performance of your application. \ No newline at end of file diff --git a/courses/react-js/intro.md b/courses/react-js/intro.md new file mode 100644 index 000000000..b4dde51ba --- /dev/null +++ b/courses/react-js/intro.md @@ -0,0 +1,18 @@ +--- +id: react-js-learning-path +title: Welcome to React.js Learning Path +sidebar_label: React.js Learning Path +sidebar_position: 1 +description: "Welcome to the React.js Learning Path! In this path, you will learn the fundamentals of React.js, including components, props, state, and more. You will also learn how to build interactive web applications, create dynamic user interfaces, and develop modern web applications using React.js. Let's get started!" +tags: [courses, react-js, web development, front-end development] +keywoards: [courses, react-js, web development, front-end development] +author: [CodeHarborHub, Ajay Dhangar] +--- + +Hello, and welcome to the React.js Learning Path! In this page, you will find a collection of resources to help you learn React.js from scratch. Whether you are a beginner or an experienced developer looking to refresh your React.js skills, this path will guide you through the fundamentals of React.js, including components, props, state, and more. + +## Levels of React.js Learning Path + +In this React.js Learning Path, you will find the following levels: + + \ No newline at end of file diff --git a/courses/recommend.md b/courses/recommend.md new file mode 100644 index 000000000..d164b2e0a --- /dev/null +++ b/courses/recommend.md @@ -0,0 +1,15 @@ +--- +id: recommended-courses +title: Recommended Courses +sidebar_label: Recommended Courses +sidebar_position: 2 +description: "Recommended courses for learning web development, data science, project management, security, and more." +tags: [courses] +keywoards: [courses] +author: [CodeHarborHub, Ajay Dhangar] +hide_table_of_contents: true +--- + +import courses from '@site/src/database/courses'; + + diff --git a/database/courses/css/css-foundations.json b/database/courses/css/css-foundations.json new file mode 100644 index 000000000..0a0156bef --- /dev/null +++ b/database/courses/css/css-foundations.json @@ -0,0 +1,136 @@ +{ + "course": { + "title": "CSS Foundations", + "sections": [ + { + "title": "Introduction", + "lessons": [ + { + "title": "Introduction" + } + ] + }, + { + "title": "CSS Basics", + "lessons": [ + { + "title": "CSS History & Basics" + }, + { + "title": "Selectors" + }, + { + "title": "Specificity" + }, + { + "title": "Color" + }, + { + "title": "Fonts & Typography" + } + ] + }, + { + "title": "Project", + "lessons": [ + { + "title": "Project Setup" + }, + { + "title": "Landing Page CSS & HTML" + }, + { + "title": "Creating Base CSS File & Variables" + } + ] + }, + { + "title": "Layout", + "lessons": [ + { + "title": "Layout Methods History" + }, + { + "title": "Flexbox & Grid" + }, + { + "title": "Combinators" + }, + { + "title": "Block Element Modifier (BEM)" + }, + { + "title": "CSS Header" + }, + { + "title": "Getting Started with CSS Q&A" + }, + { + "title": "The Box Model" + }, + { + "title": "Z-Index & Positioning" + }, + { + "title": "Border & Border Radius" + }, + { + "title": "Background" + }, + { + "title": "Dropshadow & Cursor" + }, + { + "title": "Pseudo Classes" + }, + { + "title": "Elements & Transitions" + } + ] + }, + { + "title": "Interactive & Responsive UI", + "lessons": [ + { + "title": "Home Page Layout" + }, + { + "title": "Styling Interactive Buttons" + }, + { + "title": "SVG" + }, + { + "title": "Align Items Q&A" + }, + { + "title": "Speakers Image & Grid Layout" + }, + { + "title": "Responsive Layout with Media Queries" + }, + { + "title": "Mobile Header Layout" + }, + { + "title": "Mobile Navigation Menu" + }, + { + "title": "Menu Transition" + }, + { + "title": "Color & Scrolling" + } + ] + }, + { + "title": "Wrapping Up", + "lessons": [ + { + "title": "Wrapping Up" + } + ] + } + ] + } +} diff --git a/database/courses/css/css-grid-flexbox.json b/database/courses/css/css-grid-flexbox.json new file mode 100644 index 000000000..493be37dd --- /dev/null +++ b/database/courses/css/css-grid-flexbox.json @@ -0,0 +1,184 @@ +{ + "course": { + "title": "CSS Grid & Flexbox for Responsive Layouts", + "sections": [ + { + "title": "Introduction", + "lessons": [ + { + "title": "Introduction" + }, + { + "title": "Responsive Design Overview" + } + ] + }, + { + "title": "Flexbox", + "lessons": [ + { + "title": "Flexbox" + }, + { + "title": "Starting CSS Setup" + }, + { + "title": "Container Flexbox Properties Demo" + }, + { + "title": "Child Flexbox Properties Demo" + } + ] + }, + { + "title": "Flexbox Grid System", + "lessons": [ + { + "title": "Overview & Setup" + }, + { + "title": "Coding a Flexbox Grid System" + }, + { + "title": "Responsive Media Queries" + }, + { + "title": "Flexbox Grid System Exercise" + }, + { + "title": "Flexbox Grid System Solution" + } + ] + }, + { + "title": "Flexbox Practice", + "lessons": [ + { + "title": "Text Overlay Effect with Flexbox" + }, + { + "title": "Flexbox Exercises Setup" + }, + { + "title": "Collections Practice" + }, + { + "title": "Mission Practice" + }, + { + "title": "Flexbox Footer Practice" + } + ] + }, + { + "title": "Flexbox Header & Navbar", + "lessons": [ + { + "title": "Header & Navbar" + }, + { + "title": "Header & Navbar Styling for Desktop" + }, + { + "title": "Header & Navbar Styling for Tablet" + }, + { + "title": "Header & Navbar Styling for Mobile" + } + ] + }, + { + "title": "Responsive Images & Picture Element", + "lessons": [ + { + "title": "Responsive Images Overview" + }, + { + "title": "Responsive Images Best Practices" + }, + { + "title": "srcset & sizes Demo" + }, + { + "title": "Banner Demo" + }, + { + "title": "Hero Demo" + }, + { + "title": "Final Flexbox Exercise" + }, + { + "title": "Final Flexbox Solution" + } + ] + }, + { + "title": "CSS Grid", + "lessons": [ + { + "title": "Introducing CSS Grid" + }, + { + "title": "Line-Based CSS Grid Layout Demo" + }, + { + "title": "Rows & Columns Practice" + }, + { + "title": "Sizing Rows & Columns" + }, + { + "title": "Grid Layout with Span Notation Demo" + } + ] + }, + { + "title": "Grid System", + "lessons": [ + { + "title": "Grid System with CSS Grid" + }, + { + "title": "Responsive Grid with CSS Grid" + }, + { + "title": "Figure & Figure Caption with CSS Grid" + }, + { + "title": "Combining Grid Cells & Animation" + }, + { + "title": "Mosaic Grid Exercise" + }, + { + "title": "Mosaic Grid Solution" + }, + { + "title": "Magazine-Style Layouts with Grid Template Areas" + }, + { + "title": "Card HTML Markup Practice" + }, + { + "title": "Card Layouts with Flexbox & Grid" + }, + { + "title": "Final CSS Grid Exercise" + }, + { + "title": "Final CSS Grid Solution" + } + ] + }, + { + "title": "Wrapping Up", + "lessons": [ + { + "title": "Wrapping Up" + } + ] + } + ] + } +} diff --git a/database/courses/css/css-layouts.json b/database/courses/css/css-layouts.json new file mode 100644 index 000000000..0c2fcfb9b --- /dev/null +++ b/database/courses/css/css-layouts.json @@ -0,0 +1,119 @@ +{ + "course": { + "title": "Practical CSS Layouts", + "sections": [ + { + "title": "Introduction", + "lessons": [ + { + "title": "Easy Design: Styleguide Exercise", + "topics": [ + "CSS Basics Setup", + "rem vs. em Units", + "Style Guide Type Sizes", + "Custom Font & Responsive Image", + "HTML Markup for a Simple Website", + "CSS for a Simple Responsive Layout", + "Mobile Tour Styles", + "Reviews & Images Styles", + "Margin Collapse", + "Basic CSS Footer Styles", + "CSS for Tablet Layout", + "Responsive Images with the Picture Element", + "Basic Tablet CSS Layout", + "CSS Styles for Desktop Layout" + ] + } + ] + }, + { + "title": "Medium Design", + "lessons": [ + { + "title": "Tour Page & Tracklist", + "topics": [ + "Tour Page Styles", + "Button Styling Practice", + "Button Interactive States", + "Tour Text Styles", + "Tour Layout Practice", + "Album & Tracklist Exercise", + "Album Solution", + "Album Styles", + "Tracklist Styles" + ] + }, + { + "title": "Reviews & Images", + "topics": [ + "Reviews & Images Mobile Styles", + "Reviews & Images Tablet Styles", + "Reviews & Images Tablet Styles Exercise", + "Reviews & Images Desktop Styles" + ] + }, + { + "title": "Audio Player & Hamburger Menu", + "topics": [ + "Audio Player Overview", + "Audio Player Markup", + "Audio Player Base Styles", + "Play & Mute Button Styles", + "Range Slider Styles", + "Album Cover Styles", + "Hamburger Menu Exercise", + "Hamburger Menu Logo Exercise", + "Hamburger Menu Styles Exercise", + "Hamburger Menu Tablet & Mobile Styles" + ] + }, + { + "title": "Final Site Assembly", + "topics": [ + "Medium Design Site Assembly Exercise", + "Medium Design Desktop Layout Exercise" + ] + } + ] + }, + { + "title": "Difficult Design", + "lessons": [ + { + "title": "Small Elements", + "topics": [ + "Small Elements Exercise", + "Small Elements Solution", + "Review Layout Exercise", + "Album Boxes Exercise & Solution", + "Double Border Corners", + "Navigation Exercise & Solution", + "Social Icons" + ] + }, + { + "title": "Advanced Styles", + "topics": [ + "Tracklist CSS", + "Tracklist Show & Hide JavaScript", + "Tracklist Grid for Tablet & Desktop", + "CSS Transitions & Custom Table Scrollbar", + "Diamond Images Mobile Layout", + "Diamond Images Tablet & Desktop Layout", + "Advanced Layout Exercise", + "Advanced Desktop Layout" + ] + } + ] + }, + { + "title": "Wrapping Up", + "lessons": [ + { + "title": "Wrapping Up" + } + ] + } + ] + } +} diff --git a/database/courses/css/getting-started-css.json b/database/courses/css/getting-started-css.json new file mode 100644 index 000000000..3bd6a09c1 --- /dev/null +++ b/database/courses/css/getting-started-css.json @@ -0,0 +1,121 @@ +{ + "course": { + "title": "Getting Started with CSS", + "sections": [ + { + "title": "Introduction", + "lessons": [ + { + "title": "Course Overview" + }, + { + "title": "Getting Set Up" + }, + { + "title": "Creating HTML Text Practice" + }, + { + "title": "Variables and Styling Setup" + }, + { + "title": "Styling HTML Text" + }, + { + "title": "Styling the Intro Section" + }, + { + "title": "Styling Text Exercise & Solution" + } + ] + }, + { + "title": "Navigation", + "lessons": [ + { + "title": "Nav Bar HTML Practice" + }, + { + "title": "Styling a Navbar with Flexbox" + }, + { + "title": "Styling a Navbar with Links" + }, + { + "title": "Font Awesome Icons" + }, + { + "title": "NavBae Icon Practice" + } + ] + }, + { + "title": "Additional Styles", + "lessons": [ + { + "title": "Styling a Call to Action Button" + }, + { + "title": "Making a Navbar Responsive" + }, + { + "title": "Footer Section Practice" + } + ] + }, + { + "title": "Detailed Styles", + "lessons": [ + { + "title": "Moving From Codepen to VS Code" + }, + { + "title": "Styling Page Sections" + }, + { + "title": "Creating Gradient Line Breaks" + } + ] + }, + { + "title": "Portfolio", + "lessons": [ + { + "title": "Portfolio Project Section Markup" + }, + { + "title": "Styling Portfolio Project Section" + }, + { + "title": "Responsive Project Layout" + }, + { + "title": "Overlapping Items with CSS Grid" + }, + { + "title": "Alternating Layouts Practice" + }, + { + "title": "Complete Homepage Practice" + }, + { + "title": "About Page Practice" + } + ] + }, + { + "title": "Conclusion", + "lessons": [ + { + "title": "Next Steps" + }, + { + "title": "Resources" + }, + { + "title": "Credits and Thanks" + } + ] + } + ] + } +} diff --git a/database/resources/README.md b/database/resources/README.md new file mode 100644 index 000000000..d3182ab0f --- /dev/null +++ b/database/resources/README.md @@ -0,0 +1,10 @@ +# Resources + + +## HTML + +## CSS +- [Getting Started with CSS](https://gettingstartedwith.css.education/) +- CSS Foundations +- [CSS Grid & Flexbox for Responsive Layouts](https://frontendmasters.github.io/grid-flexbox-v2/) +- [PRACTICAL CSS LAYOUTS](https://practical.css.education/) \ No newline at end of file diff --git a/docs/dsa/_category_.json b/docs/dsa/_category_.json new file mode 100644 index 000000000..8d0eb8cb7 --- /dev/null +++ b/docs/dsa/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "DSA", + "position": 6, + "link": { + "type": "generated-index", + "description": "Data Structures and Algorithms are the building blocks of computer science. This section will help you to prepare for your interviews and competitive programming." + } + } \ No newline at end of file diff --git a/docs/dsa/arrays/_category_.json b/docs/dsa/arrays/_category_.json new file mode 100644 index 000000000..e794c3655 --- /dev/null +++ b/docs/dsa/arrays/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Arrays", + "position": 6, + "link": { + "type": "generated-index", + "description": "In Data Structures, an array is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array." + } + } \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-bubblesort-dsa.md b/docs/dsa/arrays/arrays-bubblesort-dsa.md new file mode 100644 index 000000000..2da836dbb --- /dev/null +++ b/docs/dsa/arrays/arrays-bubblesort-dsa.md @@ -0,0 +1,194 @@ +--- +id: arrays-bubblesort-in-dsa +title: Arrays - Bubble Sort in DSA +sidebar_label: Bubble Sort +sidebar_position: 2 +description: "Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements 'bubble' to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position." +tags: [dsa, arrays, sorting, bubble-sort, algorithm of bubble-sort, pseudocode of bubble-sort, complexity of bubble-sort, example of bubble-sort, live example of bubble-sort, explanation of bubble-sort, quiz of bubble-sort, conclusion of bubble-sort] +--- + +**Bubble Sort** is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements bubble to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sorted order but may occasionally have some out-of-order elements nearly in position. + + + + +## Algorithm + +1. Start from the first element, compare the current element with the next element of the array. +2. If the current element is greater than the next element of the array, swap them. +3. If the current element is less than the next element, move to the next element. +4. Repeat steps 1-3 until the array is sorted. +5. The array is sorted. +6. Exit. +7. The time complexity of the bubble sort is O(n2). +8. The space complexity of the bubble sort is O(1). + +## Pseudocode + +```plaintext title="Bubble Sort" +procedure bubbleSort( A : list of sortable items ) + n = length(A) + repeat + swapped = false + for i = 1 to n-1 inclusive do + if A[i-1] > A[i] then + swap(A[i-1], A[i]) + swapped = true + end if + end for + until not swapped +end procedure +``` + +## Diagram + +```mermaid +graph TD + A([Start]) --> B("i = 0") + B --> C{"i < n-1"} + C -->|True| D("j = 0") + D --> E{"j < n - i - 1"} + E -->|True| F{arr j > arr j+1} + F -->|True| G{Swap arr j, arr j+1 } + G --> H{Increment j} + H --> |j++| D + F -->|False| I{Increment j} + I --> |j++| D + E --> |false i++| C + D --> |False| J{Increment i} + J --> |i++| C + C -->|False| K(Sorted Array) + K --> L([Stop]) + +``` + +## Example + +```js title="Bubble Sort" +function bubbleSort(arr) { + let n = arr.length; + let swapped; + do { + swapped = false; + for (let i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + let temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + swapped = true; + } + } + } while (swapped); + return arr; +} + +let arr = [64, 34, 25, 12, 22, 11, 90]; +console.log(bubbleSort(arr)); // [ 11, 12, 22, 25, 34, 64, 90 ] +``` + +## Complexity + +- **Time Complexity**: O(n2) + - Best Case: O(n) + - Average Case: O(n2) + - Worst Case: O(n2) +- **Space Complexity**: O(1) +- **Stable**: Yes + +## Live Example + +```js live +function bubbleSort() { + let arr = [64, 34, 25, 12, 22, 11, 90]; + let n = arr.length; + + for (let i = 0; i < n; i++) { + for (let j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + let temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + + return ( +
+

Bubble Sort

+

Array: [64, 34, 25, 12, 22, 11, 90]

+

+ Sorted Array: [{arr.join(", ")}] +

+
+ ) +} +``` + +## Explanation + +In the above example, we have an array of numbers `[64, 34, 25, 12, 22, 11, 90]`. We are using the bubble sort algorithm to sort the array in ascending order. The bubble sort algorithm compares each pair of adjacent items and swaps them if they are in the wrong order. The algorithm repeats this process until the array is sorted. The sorted array is `[11, 12, 22, 25, 34, 64, 90]`. The time complexity of the bubble sort is O(n2) and the space complexity is O(1). + +:::info Try it yourself +Change the array values and see how the bubble sort algorithm sorts the array. +::: + +:::tip 📝 Note +Bubble sort is not a practical sorting algorithm when the input is large. It is not suitable for large datasets due to its O(n2) time complexity. + +The main advantage of bubble sort is that it is easy to understand and implement. It is often used to teach the concept of sorting algorithms. + +Bubble sort is stable, meaning that it preserves the relative order of equal elements. + +Bubble sort is not an efficient algorithm for large datasets and is generally not used in practice. + +::: + +## References + +- [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort) +- [GeeksforGeeks](https://www.geeksforgeeks.org/bubble-sort/) +- [Programiz](https://www.programiz.com/dsa/bubble-sort) +- [TutorialsPoint](https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm) +- [StudyTonight](https://www.studytonight.com/data-structures/bubble-sort) +- [w3schools](https://www.w3schools.com/dsa/dsa_algo_bubblesort.php) + +## Related + +Insertion Sort, Selection Sort, Merge Sort, Quick Sort, etc. + + +## Quiz + +1. What is the time complexity of the bubble sort algorithm? + - [ ] O(n) + - [x] O(n2) ✔ + - [ ] O(log n) + - [ ] O(n!) + +2. Is bubble sort a stable sorting algorithm? + - [x] Yes ✔ + - [ ] No + - [ ] Maybe + - [ ] Not sure + +3. What is the space complexity of the bubble sort algorithm? + - [ ] O(n) + - [x] O(1) ✔ + - [ ] O(log n) + - [ ] O(n!) + +4. What is the main advantage of bubble sort? + - [ ] It is the fastest sorting algorithm + - [x] It is easy to understand and implement ✔ + - [ ] It is suitable for large datasets + - [ ] It is used in practice + +5. What is the main disadvantage of bubble sort? + - [ ] It is the fastest sorting algorithm + - [ ] It is easy to understand and implement + - [x] It is not suitable for large datasets ✔ + - [ ] It is used in practice + +## Conclusion + +In this tutorial, we learned about the bubble sort algorithm. We discussed the algorithm, pseudocode, diagram, example, complexity, and related concepts. We also implemented the bubble sort algorithm in JavaScript and saw a live example. We also discussed the advantages and disadvantages of the bubble sort algorithm. We hope you enjoyed this tutorial and found it helpful. Feel free to share your thoughts in the comments below. \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-dsa.md b/docs/dsa/arrays/arrays-dsa.md new file mode 100644 index 000000000..ce8da614f --- /dev/null +++ b/docs/dsa/arrays/arrays-dsa.md @@ -0,0 +1,584 @@ +--- +id: arrays-in-dsa +title: Arrays in Data Structures and Algorithms +sidebar_label: Arrays +sidebar_position: 1 +description: "An array is a collection of items stored at contiguous memory locations. It is a data structure that stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." +tags: [dsa, data-structures, arrays, array, array-data-structure, array-in-dsa, array-in-data-structure, array-in-algorithm, array-in-dsa-example, array-in-dsa-explanation, array-in-dsa-conclusion, array-in-dsa-importance, array-in-dsa-syntax, array-in-dsa-declaration, array-in-dsa-access, array-in-dsa-update, array-in-dsa-length, array-in-dsa-iterate, array-in-dsa-max-min, array-in-dsa-program, array-in-dsa-code, array-in-dsa-js, array-in-dsa-java, array-in-dsa-python, array-in-dsa-c, array-in-dsa-cpp, array-in-dsa-ts] +--- + +An array is a collection of items stored at contiguous memory locations. It is a data structure that stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. + +## Visualizations of Arrays in Data Structures and Algorithms (DSA) + + + +## Why are Arrays important? + +Arrays are important because they allow us to store multiple items of the same type in a single variable. They are used to store data in a structured way, and they are used in many algorithms and data structures. + +## How to declare an Array? + +An array can be declared in various programming languages using the following syntax: + + + + + ```js + // Declare an array in JavaScript + let arr = [1, 2, 3, 4, 5]; + ``` + + + + ```java + // Declare an array in Java + int[] arr = {1, 2, 3, 4, 5}; + ``` + + + + ```python + # Declare an array in Python + arr = [1, 2, 3, 4, 5] + ``` + + + + ```c + // Declare an array in C + int arr[] = {1, 2, 3, 4, 5}; + ``` + + + + ```cpp + // Declare an array in C++ + int arr[] = {1, 2, 3, 4, 5}; + ``` + + + + ```ts + // Declare an array in TypeScript + let arr: number[] = [1, 2, 3, 4, 5]; + ``` + + + +## How to access an Array? + +An array can be accessed using the index of the element. The index of the first element is 0, the index of the second element is 1, and so on. + + + + + ```js + // Access an array in JavaScript + let arr = [1, 2, 3, 4, 5]; + console.log(arr[0]); // 1 + console.log(arr[1]); // 2 + console.log(arr[2]); // 3 + console.log(arr[3]); // 4 + console.log(arr[4]); // 5 + ``` + + + + ```java + // Access an array in Java + int[] arr = {1, 2, 3, 4, 5}; + System.out.println(arr[0]); // 1 + System.out.println(arr[1]); // 2 + System.out.println(arr[2]); // 3 + System.out.println(arr[3]); // 4 + System.out.println(arr[4]); // 5 + ``` + + + + ```python + # Access an array in Python + arr = [1, 2, 3, 4, 5] + print(arr[0]) # 1 + print(arr[1]) # 2 + print(arr[2]) # 3 + print(arr[3]) # 4 + print(arr[4]) # 5 + ``` + + + + ```c + // Access an array in C + int arr[] = {1, 2, 3, 4, 5}; + printf("%d\n", arr[0]); // 1 + printf("%d\n", arr[1]); // 2 + printf("%d\n", arr[2]); // 3 + printf("%d\n", arr[3]); // 4 + printf("%d\n", arr[4]); // 5 + ``` + + + + ```cpp + // Access an array in C++ + int arr[] = {1, 2, 3, 4, 5}; + cout << arr[0] << endl; // 1 + cout << arr[1] << endl; // 2 + cout << arr[2] << endl; // 3 + cout << arr[3] << endl; // 4 + cout << arr[4] << endl; // 5 + ``` + + + + ```ts + // Access an array in TypeScript + let arr: number[] = [1, 2, 3, 4, 5]; + console.log(arr[0]); // 1 + console.log(arr[1]); // 2 + console.log(arr[2]); // 3 + console.log(arr[3]); // 4 + console.log(arr[4]); // 5 + ``` + + + +## How to update an Array? + +An array can be updated by assigning a new value to the index of the element. + + + + + ```js + // Update an array in JavaScript + let arr = [1, 2, 3, 4, 5]; + arr[0] = 10; + console.log(arr); // [10, 2, 3, 4, 5] + ``` + + + + ```java + // Update an array in Java + int[] arr = {1, 2, 3, 4, 5}; + arr[0] = 10; + System.out.println(Arrays.toString(arr)); // [10, 2, 3, 4, 5] + ``` + + + + ```python + # Update an array in Python + arr = [1, 2, 3, 4, 5] + arr[0] = 10 + print(arr) # [10, 2, 3, 4, 5] + ``` + + + + ```c + // Update an array in C + int arr[] = {1, 2, 3, 4, 5}; + arr[0] = 10; + for (int i = 0; i < 5; i++) { + printf("%d ", arr[i]); + } + // 10 2 3 4 5 + ``` + + + + ```cpp + // Update an array in C++ + int arr[] = {1, 2, 3, 4, 5}; + arr[0] = 10; + for (int i = 0; i < 5; i++) { + cout << arr[i] << " "; + } + // 10 2 3 4 5 + ``` + + + + ```ts + // Update an array in TypeScript + let arr: number[] = [1, 2, 3, 4, 5]; + arr[0] = 10; + console.log(arr); // [10, 2, 3, 4, 5] + ``` + + + +## How to find the length of an Array? + +The length of an array can be found using the `length` property. + + + + + ```js + // Find the length of an array in JavaScript + let arr = [1, 2, 3, 4, 5]; + console.log(arr.length); // 5 + ``` + + + + ```java + // Find the length of an array in Java + int[] arr = {1, 2, 3, 4, 5}; + System.out.println(arr.length); // 5 + ``` + + + + ```python + # Find the length of an array in Python + arr = [1, 2, 3, 4, 5] + print(len(arr)) # 5 + ``` + + + + ```c + // Find the length of an array in C + int arr[] = {1, 2, 3, 4, 5}; + int length = sizeof(arr) // sizeof(arr[0]); + printf("%d\n", length); // 5 + ``` + + + + ```cpp + // Find the length of an array in C++ + int arr[] = {1, 2, 3, 4, 5}; + int length = sizeof(arr) // sizeof(arr[0]); + cout << length << endl; // 5 + ``` + + + + ```ts + // Find the length of an array in TypeScript + let arr: number[] = [1, 2, 3, 4, 5]; + console.log(arr.length); // 5 + ``` + + + +## How to iterate through an Array? + +An array can be iterated using a loop such as `for` loop, `while` loop, or `for...of` loop. + + + + + ```js + // Iterate through an array in JavaScript + let arr = [1, 2, 3, 4, 5]; + for (let i = 0; i < arr.length; i++) { + console.log(arr[i]); + } + // 1 + // 2 + // 3 + // 4 + // 5 + ``` + + + + ```java + // Iterate through an array in Java + int[] arr = {1, 2, 3, 4, 5}; + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); + } + // 1 + // 2 + // 3 + // 4 + // 5 + ``` + + + + ```python + # Iterate through an array in Python + arr = [1, 2, 3, 4, 5] + for i in arr: + print(i) + # 1 + # 2 + # 3 + # 4 + # 5 + ``` + + + + ```c + // Iterate through an array in C + int arr[] = {1, 2, 3, 4, 5}; + for (int i = 0; i < 5; i++) { + printf("%d\n", arr[i]); + } + // 1 + // 2 + // 3 + // 4 + // 5 + ``` + + + + ```cpp + // Iterate through an array in C++ + int arr[] = {1, 2, 3, 4, 5}; + for (int i = 0; i < 5; i++) { + cout << arr[i] << endl; + } + // 1 + // 2 + // 3 + // 4 + // 5 + ``` + + + + ```ts + // Iterate through an array in TypeScript + let arr: number[] = [1, 2, 3, 4, 5]; + for (let i = 0; i < arr.length; i++) { + console.log(arr[i]); + } + // 1 + // 2 + // 3 + // 4 + // 5 + ``` + + + +## How to find the maximum and minimum elements in an Array? + +The maximum and minimum elements in an array can be found by iterating through the array and comparing each element with the current maximum and minimum elements. + + + + + ```js + // Find the maximum and minimum elements in an array in JavaScript + function findMaxMin(arr) { + let max = arr[0]; + let min = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] > max) { + max = arr[i]; + } + if (arr[i] < min) { + min = arr[i]; + } + } + return { max, min }; + } + + let arr = [2, 5, 1, 20, 10]; + console.log(findMaxMin(arr)); // { max: 20, min: 1 } + ``` + + + + ```java + public class Main { + // Find the maximum and minimum elements in an array in Java + static class MaxMin { + int max; + int min; + } + + static MaxMin findMaxMin(int arr[]) { + MaxMin result = new MaxMin(); + result.max = arr[0]; + result.min = arr[0]; + for (int i = 1; i < arr.length; i++) { + if (arr[i] > result.max) { + result.max = arr[i]; + } + if (arr[i] < result.min) { + result.min = arr[i]; + } + } + return result; + } + + public static void main(String[] args) { + int arr[] = {2, 5, 1, 20, 10}; + MaxMin result = findMaxMin(arr); + System.out.println("{ max: " + result.max + ", min: " + result.min + " }"); // { max: 20, min: 1 } + } + } + + ``` + + + + ```python + # Find the maximum and minimum elements in an array in Python + def find_max_min(arr): + max = arr[0] + min = arr[0] + for i in range(1, len(arr)): + if arr[i] > max: + max = arr[i] + if arr[i] < min: + min = arr[i] + return {"max": max, "min": min} + + arr = [2, 5, 1, 20, 10] + print(find_max_min(arr)) # { max: 20, min: 1 } + ``` + + + + ```c + // Find the maximum and minimum elements in an array in C + struct MaxMin { + int max; + int min; + }; + + struct MaxMin findMaxMin(int arr[], int n) { + struct MaxMin result; + result.max = arr[0]; + result.min = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > result.max) { + result.max = arr[i]; + } + if (arr[i] < result.min) { + result.min = arr[i]; + } + } + return result; + } + + int arr[] = {2, 5, 1, 20, 10}; + struct MaxMin result = findMaxMin(arr, 5); + printf("{ max: %d, min: %d }\n", result.max, result.min); // { max: 20, min: 1 } + ``` + + + + ```cpp + // Find the maximum and minimum elements in an array in C++ + struct MaxMin { + int max; + int min; + }; + + MaxMin findMaxMin(int arr[], int n) { + MaxMin result; + result.max = arr[0]; + result.min = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > result.max) { + result.max = arr[i]; + } + if (arr[i] < result.min) { + result.min = arr[i]; + } + } + return result; + } + + int arr[] = {2, 5, 1, 20, 10}; + MaxMin result = findMaxMin(arr, 5); + cout << "{ max: " << result.max << ", min: " << result.min << " }" << endl; // { max: 20, min: 1 } + ``` + + + + ```ts + // Find the maximum and minimum elements in an array in TypeScript + interface MaxMin { + max: number; + min: number; + } + + function findMaxMin(arr: number[]): MaxMin { + let max = arr[0]; + let min = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] > max) { + max = arr[i]; + } + if (arr[i] < min) { + min = arr[i]; + } + } + return { max, min }; + } + + let arr: number[] = [2, 5, 1, 20, 10]; + console.log(findMaxMin(arr)); // { max: 20, min: 1 } + ``` + + + +:::info 📝 Info +- The time complexity of finding the maximum and minimum elements in an array is O(n). +- The space complexity of finding the maximum and minimum elements in an array is O(1). +::: + +## Problems for Practice + +export const problems = [ + { + "problemName": "1. Two Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/two-sum/", + "solutionLink": "#" + }, + { + "problemName": "2. Best Time to Buy and Sell Stock", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/", + "solutionLink": "#" + }, + { + "problemName": "3. Contains Duplicate", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/contains-duplicate/", + "solutionLink": "#" + }, + { + "problemName": "4. Product of Array Except Self", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/product-of-array-except-self/", + "solutionLink": "#" + }, + { + "problemName": "5. Maximum Subarray", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-subarray/", + "solutionLink": "#" + } + +] + + + +## Conclusion + +In this tutorial, we learned about arrays in data structures and algorithms. We learned how to declare an array, access an array, update an array, find the length of an array, iterate through an array, and find the maximum and minimum elements in an array. Arrays are an important data structure that is used in many algorithms and data structures. \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-insertionsort.md b/docs/dsa/arrays/arrays-insertionsort.md new file mode 100644 index 000000000..02eeecee6 --- /dev/null +++ b/docs/dsa/arrays/arrays-insertionsort.md @@ -0,0 +1,168 @@ +--- +id: arrays-insertionsort +title: Arrays - Insertion Sort +sidebar_label: Insertion Sort +sidebar_position: 4 +description: "Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort." +tags: [dsa, arrays, sorting, insertion-sort, sorting-algorithms] +--- + +**Insertion Sort** is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. + +However, insertion sort provides several advantages: + +- **Simple implementation:** The code implementation of insertion sort is simple and easy to understand. +- **Efficient for small data sets:** Insertion sort is efficient for small data sets. +- **Adaptive:** It is adaptive, meaning it is efficient for data sets that are already substantially sorted. +- **Stable:** It is a stable sorting algorithm, meaning it preserves the relative order of equal elements. +- **In-place:** It requires only a constant amount of additional memory space. +- **Online:** It can sort a list as it receives it. +- **More efficient in practice:** It is more efficient in practice than other quadratic-time sorting algorithms like bubble sort and selection sort. +- **Simple to code:** It is simple to code and implement. + + + +
+ +The insertion sort algorithm takes value at a time from the unsorted part and places it in its correct position in the sorted part. The sorted part is built from left to right, and the unsorted part is on the right side of the array. The algorithm works by shifting the elements in the sorted part that are greater than the current element to the right, creating space for the current element to be inserted. + +:::info Key Points +- **Type:** Sorting Algorithm +- **Time Complexity:** + - **Best Case:** *O(n)* + - **Average Case:** *O(n2)* + - **Worst Case:** *O(n2)* +- **Space Complexity:** *O(1)* +- **Stable:** Yes +- **In-Place:** Yes +- **Online:** Yes +- **Adaptive:** Yes +- **Comparison Sort:** Yes +- **Suitable for:** Small data sets, partially sorted data sets +- **Efficient for:** Small data sets +- **Not efficient for:** Large data sets +- **Simple to code:** Yes +- **Efficient in practice:** Yes + +::: + +:::tip Real-World Analogy +Insertion sort can be compared to sorting a deck of cards. You start with an empty hand and pick one card at a time from the deck. You then insert the card into its correct position in your hand, shifting the other cards if necessary. This process is repeated until all the cards are sorted in your hand. + +## How Insertion Sort Works? + +Let's understand how the Insertion Sort algorithm works with an example: + +Consider an array `arr = [12, 11, 13, 5, 6]` that we want to sort in ascending order using the Insertion Sort algorithm. + +1. **Initial Array:** `[12, 11, 13, 5, 6]` +2. **Step 1:** Start from the second element (index 1) and compare it with the previous element. + - Compare `11` with `12`. Since `11` is smaller, swap them. + - **Array after Step 1:** `[11, 12, 13, 5, 6]` + - The array is partially sorted from index 0 to 1. + - The current array looks like this: `[11, 12, 13, 5, 6]` + - The sorted part is `[11, 12]`, and the unsorted part is `[13, 5, 6]`. + - The key element is `13`. + - The key element is compared with the elements in the sorted part. + - Since `13` is greater than `12`, no swap is needed. + - The array remains the same: `[11, 12, 13, 5, 6]` + - The array is partially sorted from index 0 to 2. + - The current array looks like this: `[11, 12, 13, 5, 6]` + - The sorted part is `[11, 12, 13]`, and the unsorted part is `[5, 6]`. + - The key element is `5`. + - The key element is compared with the elements in the sorted part. + - Since `5` is smaller than `13`, `12`, and `11`, it is moved to the left. + - **Array after Step 1:** `[5, 11, 12, 13, 6]` + - The array is partially sorted from index 0 to 3. + - The current array looks like this: `[5, 11, 12, 13, 6]` + - The sorted part is `[5, 11, 12, 13]`, and the unsorted part is `[6]`. + - The key element is `6`. + - The key element is compared with the elements in the sorted part. + - Since `6` is smaller than `13`, it is moved to the left. + - Since `6` is smaller than `12`, it is moved to the left. + - Since `6` is smaller than `11`, it is moved to the left. + - **Array after Step 1:** `[5, 6, 11, 12, 13]` + - The array is now sorted. + - The sorted array is `[5, 6, 11, 12, 13]`. + +3. **Final Sorted Array:** `[5, 6, 11, 12, 13]` +4. The array is now sorted in ascending order using the Insertion Sort algorithm. +5. The time complexity of the Insertion Sort algorithm is ***O(n2)*** in the worst-case scenario. +6. The space complexity of the Insertion Sort algorithm is ***O(1)***. +7. The Insertion Sort algorithm is efficient for small data sets and partially sorted data sets. + +## Visualization + +You can visualize the Insertion Sort algorithm using the following animation: + +
+ +
+ +You can select the Insertion Sort algorithm from the drop-down menu and visualize how it works on different arrays. + +::: + +## Algorithm + +The insertion sort algorithm works as follows: + +1. Start from the second element (index 1) and compare it with the previous elements. +2. If the current element is smaller than the previous element, swap them. +3. Repeat this process until the current element is greater than the previous element or until the first element is reached. +4. Move to the next element and repeat the process. +5. Continue this process until the entire array is sorted. +6. The array is now sorted. +7. The time complexity of the insertion sort algorithm is ***O(n2)*** in the worst-case scenario. +8. The space complexity of the insertion sort algorithm is ***O(1)***. + +## Pseudocode + +```plaintext +1. for i = 1 to n-1 +2. key = arr[i] +3. j = i - 1 +4. while j >= 0 and arr[j] > key +5. arr[j + 1] = arr[j] +6. j = j - 1 +7. arr[j + 1] = key +``` + +## Implementation + +Here's the implementation of the Insertion Sort algorithm in JavaScript: + +```javascript title="Insertion Sort" +function insertionSort(arr) { + const n = arr.length; + for (let i = 1; i < n; i++) { + let key = arr[i]; + let j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + return arr; +} + +const arr = [12, 11, 13, 5, 6]; +console.log(insertionSort(arr)); // Output: [5, 6, 11, 12, 13] +``` + +## Complexity Analysis + +The time complexity of the Insertion Sort algorithm is ***O(n2)*** in the worst-case scenario when the array is sorted in reverse order. The best-case time complexity is ***O(n)*** when the array is already sorted. + +The space complexity of the Insertion Sort algorithm is ***O(1)*** since it requires only a constant amount of additional memory space. + +## References + +- [Wikipedia - Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) +- [GeeksforGeeks - Insertion Sort](https://www.geeksforgeeks.org/insertion-sort/) +- [Programiz - Insertion Sort](https://www.programiz.com/dsa/insertion-sort) +- [Khan Academy - Insertion Sort](https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/a/insertion-sort) +- [TutorialsPoint - Insertion Sort](https://www.tutorialspoint.com/data_structures_algorithms/insertion_sort_algorithm.htm) +- [StudyTonight - Insertion Sort](https://www.studytonight.com/data-structures/insertion-sorting) +- [Insertion Sort Visualization](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) \ No newline at end of file diff --git a/docs/dsa/arrays/arrays-selectionsort.md b/docs/dsa/arrays/arrays-selectionsort.md new file mode 100644 index 000000000..706040c34 --- /dev/null +++ b/docs/dsa/arrays/arrays-selectionsort.md @@ -0,0 +1,152 @@ +--- +id: arrays-selectionsort-in-dsa +title: Arrays - Selection Sort in DSA +sidebar_label: Selection Sort +sidebar_position: 3 +description: "Selection Sort is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray." +tags: [dsa, arrays, sorting, selection-sort, algorithm of selection-sort, pseudocode of selection-sort, complexity of selection-sort, example of selection-sort, live example of selection-sort, explanation of selection-sort, quiz of selection-sort, conclusion of selection-sort] +--- + +**Selection Sort** is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. + + + +## Algorithm + +1. The selection sort algorithm divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. +2. The algorithm repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. +3. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. +4. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. +5. The array is sorted. +6. Exit. +7. The time complexity of the selection sort is O(n^2). +8. The space complexity of the selection sort is O(1). + +## Pseudocode + +```plaintext title="Selection Sort" +procedure selectionSort( A : list of sortable items ) + n = length(A) + for i = 0 to n-1 inclusive do + min = i + for j = i+1 to n inclusive do + if A[j] < A[min] then + min = j + end if + end for + swap(A[i], A[min]) + end for +end procedure +``` + +## Diagram + + +## Complexity + +The time complexity of the selection sort is O(n^2). The space complexity of the selection sort is O(1). + +## Example + +```js title="Selection Sort" +function selectionSort(arr) { + let n = arr.length; + for (let i = 0; i < n - 1; i++) { + let min = i; + for (let j = i + 1; j < n; j++) { + if (arr[j] < arr[min]) { + min = j; + } + } + let temp = arr[i]; + arr[i] = arr[min]; + arr[min] = temp; + } + return arr; +} + +const arr = [64, 25, 12, 22, 11]; + +console.log(selectionSort(arr)); // [11, 12, 22, 25, 64] +``` + +## Practice Problems + +- [Leetcode - Sort an Array](https://leetcode.com/problems/sort-an-array/) +- [HackerRank - The Full Counting Sort](https://www.hackerrank.com/challenges/countingsort4/problem) +- [Codeforces - Sort the Array](https://codeforces.com/problemset/problem/451/B) +- [CodeChef - Turbo Sort](https://www.codechef.com/problems/TSORT) + +## Quiz + +1. What is the time complexity of the selection sort? + - A) O(n) + - B) O(n^2) + - C) O(n log n) + - D) O(1) + - Correct Answer: B + +2. What is the space complexity of the selection sort? + - A) O(n) + - B) O(n^2) + - C) O(n log n) + - D) O(1) + - Correct Answer: D +- Explanation: The space complexity of the selection sort is O(1). + +3. What is the best-case time complexity of the selection sort? + - A) O(n) + - B) O(n^2) + - C) O(n log n) + - D) O(1) + - Correct Answer: B + +4. What is the worst-case time complexity of the selection sort? + - A) O(n) + - B) O(n^2) + - C) O(n log n) + - D) O(1) + - Correct Answer: B + +5. Is the selection sort stable? + - A) Yes + - B) No + - Correct Answer: A + + +:::info Try it yourself + +```js live +function selectionSort() { + let arr = [64, 25, 12, 22, 11]; + let n = arr.length; + for (let i = 0; i < n - 1; i++) { + let min = i; + for (let j = i + 1; j < n; j++) { + if (arr[j] < arr[min]) { + min = j; + } + } + let temp = arr[i]; + arr[i] = arr[min]; + arr[min] = temp; + } + return ( +
+

Selection Sort

+

Array: [64, 25, 12, 22, 11]

+

+ Sorted Array: [{arr.join(", ")}] +

+
+ ) +} +``` + +In the above example, we have an array of numbers `[64, 25, 12, 22, 11]`. We are using the selection sort algorithm to sort the array in ascending order. The selection sort algorithm divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. The sorted array is `[11, 12, 22, 25, 64]`. The time complexity of the selection sort is O(n^2) and the space complexity is O(1). + +::: + +## Conclusion + +In this article, we learned about the selection sort algorithm. Selection sort is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted. It repeatedly finds the minimum element from the unsorted part and puts it at the beginning of the unsorted part. The algorithm maintains two subarrays in a given array. The subarray which is already sorted and the remaining subarray which is unsorted. In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray. The time complexity of the selection sort is O(n^2) and the space complexity is O(1). Selection sort is a stable sorting algorithm. \ No newline at end of file diff --git a/docs/dsa/basic-concepts/_category_.json b/docs/dsa/basic-concepts/_category_.json new file mode 100644 index 000000000..b810bad9b --- /dev/null +++ b/docs/dsa/basic-concepts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Basic Concepts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Basic Concepts of Data Structures and Algorithms." + } + } \ No newline at end of file diff --git a/docs/dsa/basic-concepts/image-1.png b/docs/dsa/basic-concepts/image-1.png new file mode 100644 index 000000000..cd127aab3 Binary files /dev/null and b/docs/dsa/basic-concepts/image-1.png differ diff --git a/docs/dsa/basic-concepts/image.png b/docs/dsa/basic-concepts/image.png new file mode 100644 index 000000000..8a263334f Binary files /dev/null and b/docs/dsa/basic-concepts/image.png differ diff --git a/docs/dsa/basic-concepts/space-complexity.md b/docs/dsa/basic-concepts/space-complexity.md new file mode 100644 index 000000000..8bf46a6ea --- /dev/null +++ b/docs/dsa/basic-concepts/space-complexity.md @@ -0,0 +1,212 @@ +--- +id: space-complexity +title: Space Complexity +sidebar_label: Space Complexity +sidebar_position: 2 +description: "Space complexity is a measure of the amount of working storage an algorithm needs. It is a measure of the amount of memory space an algorithm needs to solve a problem as a function of the size of the input to the problem. It is the amount of memory space required by the algorithm to execute in its life cycle." +tags: [Space Complexity, Big O Notation, Memory, Algorithm, Complexity Analysis, Data Structure, DSA, JavaScript, Java, Python, C, C++, Space Complexity Example, Space Complexity Calculation, Space Complexity Analysis, Space Complexity Explanation, Space Complexity Conclusion, Space Complexity Importance, Space Complexity Formula, Space Complexity Constant Space, Space Complexity Auxiliary Space, Space Complexity Example, Space Complexity Program, Space Complexity Code] +--- + +Space complexity is a measure of the amount of working storage an algorithm needs. It is a measure of the amount of memory space an algorithm needs to solve a problem as a function of the size of the input to the problem. It is the amount of memory space required by the algorithm to execute in its life cycle. + +## Why is Space Complexity important? + +Space complexity is important because the memory that is allocated to the program is limited. If the program uses more memory than the available memory, the program will crash. Therefore, it is important to know the space complexity of the algorithm. + +## How to calculate Space Complexity? + +Space complexity is calculated by counting the amount of memory space used by the algorithm. It is calculated by counting the amount of memory space used by the algorithm as a function of the size of the input to the problem. + +## Example + +```js title="Space Complexity" +function sumOfN(n) { + let sum = 0; + for (let i = 1; i <= n; i++) { + sum += i; + } + return sum; +} +``` + +In the above example, the space complexity of the algorithm is O(1) because the algorithm uses a constant amount of memory space. + +## Example of Space Complexity + +1. Write a program to fine maximum and minimum element in an array. + + + + + ```js {6,9,12} + function findMaxMin(arr) { + let max = arr[0]; + let min = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] > max) { + max = arr[i]; + } + if (arr[i] < min) { + min = arr[i]; + } + } + return { max, min }; + } + + const arr = [2, 5, 1, 20, 10]; + console.log(findMaxMin(arr)); // { max: 20, min: 1 } + ``` + + + + + ```java + public class Main { + public static void main(String[] args) { + int[] arr = {2, 5, 1, 20, 10}; + System.out.println(findMaxMin(arr)); // { max: 20, min: 1 } + } + + public static Map findMaxMin(int[] arr) { + int max = arr[0]; + int min = arr[0]; + for (int i = 1; i < arr.length; i++) { + if (arr[i] > max) { + max = arr[i]; + } + if (arr[i] < min) { + min = arr[i]; + } + } + Map result = new HashMap<>(); + result.put("max", max); + result.put("min", min); + return result; + } + } + ``` + + + + + ```python + def find_max_min(arr): + max = arr[0] + min = arr[0] + for i in range(1, len(arr)): + if arr[i] > max: + max = arr[i] + if arr[i] < min: + min = arr[i] + return {"max": max, "min": min} + + arr = [2, 5, 1, 20, 10] + print(find_max_min(arr)) # { max: 20, min: 1 } + ``` + + + + + ```c + #include + + struct MaxMin { + int max; + int min; + }; + + struct MaxMin findMaxMin(int arr[], int n) { + struct MaxMin result; + result.max = arr[0]; + result.min = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > result.max) { + result.max = arr[i]; + } + if (arr[i] < result.min) { + result.min = arr[i]; + } + } + return result; + } + + int main() { + int arr[] = {2, 5, 1, 20, 10}; + struct MaxMin result = findMaxMin(arr, 5); + printf("{ max: %d, min: %d }\n", result.max, result.min); // { max: 20, min: 1 } + return 0; + } + ``` + + + + + ```cpp + #include + #include + #include + + std::map findMaxMin(std::vector arr) { + int max = arr[0]; + int min = arr[0]; + for (int i = 1; i < arr.size(); i++) { + if (arr[i] > max) { + max = arr[i]; + } + if (arr[i] < min) { + min = arr[i]; + } + } + std::map result; + result["max"] = max; + result["min"] = min; + return result; + } + + int main() { + std::vector arr = {2, 5, 1, 20, 10}; + std::map result = findMaxMin(arr); + std::cout << "{ max: " << result["max"] << ", min: " << result["min"] << " }\n"; // { max: 20, min: 1 } + return 0; + } + ``` + + + + +In the above example, the space complexity of the algorithm is O(1) because the algorithm uses a constant amount of memory space. + +**Explanation:** In the above example, we are finding the maximum and minimum element in an array. We are using two variables `max` and `min` to store the maximum and minimum element in the array. We are using a constant amount of memory space to store the maximum and minimum element in the array. Therefore, the space complexity of the algorithm is O(1). + +:::info Complexity Analysis +**Farmula to calculate Space Complexity** + +Space Complexity = Constant Space + Auxiliary Space + +**Constant Space:** The amount of space used by the algorithm that is not dependent on the size of the input to the problem. It is a constant amount of memory space used by the algorithm. + +**Auxiliary Space:** The amount of space used by the algorithm that is dependent on the size of the input to the problem. It is a variable amount of memory space used by the algorithm. + +```plaintext title="Space Complexity" +Space Complexity = O(1) + O(n) = O(n) +``` + +**For Example:** + +```js title="Space Complexity" +function sumOfN(n) { + let sum = 0; // Constant Space (O(1)) + for (let i = 1; i <= n; i++) { + sum += i; // Auxiliary Space (O(n)) + } + return sum; +} +``` + +In the above example, the space complexity of the algorithm is `O(1) + O(n) = O(n)`. + +::: + +## Conclusion + +Space complexity is a measure of the amount of working storage an algorithm needs. It is a measure of the amount of memory space an algorithm needs to solve a problem as a function of the size of the input to the problem. It is the amount of memory space required by the algorithm to execute in its life cycle. \ No newline at end of file diff --git a/docs/dsa/basic-concepts/time-complexity.md b/docs/dsa/basic-concepts/time-complexity.md new file mode 100644 index 000000000..eb10b2909 --- /dev/null +++ b/docs/dsa/basic-concepts/time-complexity.md @@ -0,0 +1,306 @@ +--- +id: time-complexity +title: Time Complexity +sidebar_label: Time Complexity +sidebar_position: 1 +description: "Time Complexity is a measure of the amount of time an algorithm takes to solve a problem as a function of the size of the input to the problem. It is commonly estimated by counting the number of elementary operations performed by the algorithm, where an elementary operation takes a fixed amount of time to perform." +tags: [time complexity, big o notation, algorithm, complexity analysis, data structure, dsa, javascript, java, python, c, c++, time complexity example, time complexity calculation, time complexity analysis, time complexity explanation, time complexity conclusion, time complexity importance, time complexity formula, time complexity constant time, time complexity linear time, time complexity logarithmic time, time complexity quadratic time, time complexity exponential time, time complexity factorial time, time complexity polynomial time, time complexity sublinear time, time complexity linearithmic time, time complexity quasilinear time, time complexity superpolynomial time, time complexity subexponential time, time complexity log factorial time, time complexity exponential factorial time, time complexity exponential exponential time, time complexity exponential factorial exponential time, time complexity exponential exponential factorial time] +--- + +Time Complexity is a measure of the amount of time an algorithm takes to solve a problem as a function of the size of the input to the problem. It is commonly estimated by counting the number of elementary operations performed by the algorithm, where an elementary operation takes a fixed amount of time to perform. + +## Why is Time Complexity Important? + +Time Complexity is important because it helps us understand the efficiency of an algorithm. It allows us to compare different algorithms and choose the most efficient one for a given problem. It also helps us analyze the performance of an algorithm as the size of the input grows. + +## Common Notations for Time Complexity + +The most common notations used to represent the time complexity of an algorithm are: + +- **Big O Notation (O):** It represents the upper bound of the time complexity of an algorithm. It gives the worst-case time complexity of an algorithm. +- **Omega Notation (Ω):** It represents the lower bound of the time complexity of an algorithm. It gives the best-case time complexity of an algorithm. +- **Theta Notation (Θ):** It represents the average-case time complexity of an algorithm. It gives the tight bound of the time complexity of an algorithm. + +### Big O Notation (O) + +Big O Notation is used to represent the upper bound of the time complexity of an algorithm. It gives the worst-case time complexity of an algorithm. It is commonly used to analyze the performance of an algorithm as the size of the input grows. + +![Big O Notation](image.png) + +The Big O Notation is written as `O(f(n))`, where `f(n)` is a function that represents the time complexity of the algorithm. It is read as "O of f of n" or "order of f of n". + +### Omega Notation (Ω) + +Omega Notation is used to represent the lower bound of the time complexity of an algorithm. It gives the best-case time complexity of an algorithm. It is commonly used to analyze the performance of an algorithm as the size of the input grows. + +![Omega Notation](image-1.png) + +The Omega Notation is written as `Ω(f(n))`, where `f(n)` is a function that represents the time complexity of the algorithm. It is read as "Omega of f of n". + +### Theta Notation (Θ) + +Theta Notation is used to represent the average-case time complexity of an algorithm. It gives the tight bound of the time complexity of an algorithm. It is commonly used to analyze the performance of an algorithm as the size of the input grows. + +The Theta Notation is written as `Θ(f(n))`, where `f(n)` is a function that represents the time complexity of the algorithm. It is read as "Theta of f of n". + + +## Examples of Time Complexity + +Here are some examples of time complexity for different algorithms: + +- **Constant Time (O(1)):** An algorithm that takes the same amount of time to run, regardless of the size of the input. +- **Linear Time (O(n)):** An algorithm that takes time proportional to the size of the input. +- **Logarithmic Time (O(log n)):** An algorithm that takes time proportional to the logarithm of the size of the input. +- **Quadratic Time (O(n^2)):** An algorithm that takes time proportional to the square of the size of the input. +- **Exponential Time (O(2^n)):** An algorithm that takes time proportional to an exponential function of the size of the input. +- **Factorial Time (O(n!)):** An algorithm that takes time proportional to the factorial of the size of the input. +- **Polynomial Time (O(n^k)):** An algorithm that takes time proportional to a polynomial function of the size of the input. +- **Sublinear Time (O(log log n)):** An algorithm that takes time proportional to the logarithm of the logarithm of the size of the input. +- **Linearithmic Time (O(n log n)):** An algorithm that takes time proportional to the product of the size of the input and the logarithm of the size of the input. +- **Quasilinear Time (O(n log^k n)):** An algorithm that takes time proportional to the product of the size of the input and the logarithm of the size of the input raised to the power of k. +- **Superpolynomial Time (O(n^k)):** An algorithm that takes time proportional to a function that grows faster than any polynomial function of the size of the input. +- **Subexponential Time (O(2^poly(n))):** An algorithm that takes time proportional to a function that grows slower than any exponential function of the size of the input. +- **Log Factorial Time (O(log n!)):** An algorithm that takes time proportional to the logarithm of the factorial of the size of the input. +- **Exponential Factorial Time (O(2^n!)):** An algorithm that takes time proportional to an exponential function of the factorial of the size of the input. +- **Exponential Exponential Time (O(2^2^n)):** An algorithm that takes time proportional to an exponential function of an exponential function of the size of the input. +- **Exponential Factorial Exponential Time (O(2^n!^2^n)):** An algorithm that takes time proportional to an exponential function of the factorial of an exponential function of the size of the input. +- **Exponential Exponential Factorial Time (O(2^2^n!)):** An algorithm that takes time proportional to an exponential function of an exponential function of the factorial of the size of the input. + +## Analyzing Time Complexity + +To analyze the time complexity of an algorithm, we can follow these steps: + +1. **Count the Operations:** Count the number of elementary operations performed by the algorithm. +2. **Identify the Dominant Term:** Identify the term that grows the fastest as the size of the input grows. +3. **Express the Time Complexity:** Express the time complexity using the Big O notation. +4. **Compare with Other Algorithms:** Compare the time complexity with other algorithms to choose the most efficient one. +5. **Analyze the Best, Worst, and Average Cases:** Analyze the best-case, worst-case, and average-case time complexity of the algorithm. +6. **Optimize the Algorithm:** Optimize the algorithm to improve its time complexity if possible. +7. **Test the Algorithm:** Test the algorithm with different input sizes to verify its time complexity. +8. **Benchmark the Algorithm:** Benchmark the algorithm to measure its actual performance. +9. **Profile the Algorithm:** Profile the algorithm to identify performance bottlenecks and optimize them. +10. **Analyze the Real-World Performance:** Analyze the real-world performance of the algorithm in different environments and scenarios. +11. **Contribute:** If you have any tips to share, feel free to contribute to this section. + +## For Example + +1. Calculating sum of array elements using loop. + + + + + ```js + function sum(arr) { + let result = 0; + for (let i = 0; i < arr.length; i++) { + result += arr[i]; + } + return result; + } + const arr = [1, 2, 3, 4, 5]; + console.log(sum(arr)); // Output: 15 + ``` + + + ```py + def sum(arr): + result = 0 + for i in arr: + result += i + return result + arr = [1, 2, 3, 4, 5] + print(sum(arr)) # Output: 15 + ``` + + + ```java + class Sum { + public static void main(String args[]) { + int arr[] = {1, 2, 3, 4, 5}; + int result = 0; + for (int i = 0; i < arr.length; i++) { + result += arr[i]; + } + System.out.println(result); // Output: 15 + } + } + ``` + + + ```c + #include + int main() { + int arr[] = {1, 2, 3, 4, 5}; + int result = 0; + for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { + result += arr[i]; + } + printf("%d\n", result); // Output: 15 + return 0; + } + ``` + + + ```go + package main + import "fmt" + func main() { + arr := []int{1, 2, 3, 4, 5} + result := 0 + for i := 0; i < len(arr); i++ { + result += arr[i] + } + fmt.Println(result) // Output: 15 + } + ``` + + + ```cpp + #include + using namespace std; + int main() { + int arr[] = {1, 2, 3, 4, 5}; + int result = 0; + for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { + result += arr[i]; + } + cout << result << endl; // Output: 15 + return 0; + } + ``` + + + ```swift + import Foundation + let arr = [1, 2, 3, 4, 5] + var result = 0 + for i in arr { + result += i + } + print(result) // Output: 15 + ``` + + + ```kotlin + fun main() { + val arr = intArrayOf(1, 2, 3, 4, 5) + var result = 0 + for (i in arr) { + result += i + } + println(result) // Output: 15 + } + ``` + + + ```rs + fn main() { + let arr = [1, 2, 3, 4, 5]; + let mut result = 0; + for i in arr.iter() { + result += i; + } + println!("{}", result); // Output: 15 + } + ``` + + + ```php + + ``` + + + ```cs + using System; + class Sum { + static void Main() { + int[] arr = {1, 2, 3, 4, 5}; + int result = 0; + foreach (int i in arr) { + result += i; + } + Console.WriteLine(result); // Output: 15 + } + } + ``` + + + ```ts + let arr: number[] = [1, 2, 3, 4, 5]; + let result: number = 0; + for (let i of arr) { + result += i; + } + console.log(result); // Output: 15 + ``` + + + ```scala + object Sum { + def main(args: Array[String]): Unit = { + val arr = Array(1, 2, 3, 4, 5) + var result = 0 + for (i <- arr) { + result += i + } + println(result) // Output: 15 + } + } + ``` + + + ```haskell + main = do + let arr = [1, 2, 3, 4, 5] + let result = sum arr + print result -- Output: 15 + ``` + + + ```r + arr <- c(1, 2, 3, 4, 5) + result <- sum(arr) + print(result) # Output: 15 + ``` + + + ```perl + my @arr = (1, 2, 3, 4, 5); + my $result = 0; + foreach my $i (@arr) { + $result += $i; + } + print $result; # Output: 15 + ``` + + + ```lua + arr = {1, 2, 3, 4, 5} + result = 0 + for i = 1, #arr do + result = result + arr[i] + end + print(result) -- Output: 15 + ``` + + + +Each of the above code snippets has a time complexity of `O(n)` because the number of iterations in the loop is directly proportional to the size of the input array. + +**Exlpanation:** The time complexity of the given code is `O(n)` because the loop iterates through the array elements one by one, and the number of iterations is directly proportional to the size of the input array. Therefore, the time complexity is linear, i.e., `O(n)`. + + +:::info +**Note:** The time complexity of an algorithm can be different for different programming languages, but the underlying logic and analysis remain the same. +::: + +## Conclusion + +Time Complexity is an important concept in computer science and programming. It helps us understand the efficiency of algorithms and make informed decisions about choosing the most efficient algorithm for a given problem. By analyzing the time complexity of algorithms, we can optimize them for better performance and improve the overall efficiency of our programs. \ No newline at end of file diff --git a/docs/dsa/data-structure-types.md b/docs/dsa/data-structure-types.md new file mode 100644 index 000000000..350d26e72 --- /dev/null +++ b/docs/dsa/data-structure-types.md @@ -0,0 +1,367 @@ +--- +id: data-structure-types +title: Data Structure Types +sidebar_label: Data Structure Types +sidebar_position: 2 +description: "Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. This section covers the different types of data structures and their applications." +tags: + [ + dsa, + data-structures, + types, + data structure types, + primitive data types, + abstract data types, + linear data structures, + non-linear data structures, + homogeneous data structures, + heterogeneous data structures, + static data structures, + dynamic data structures, + mutable data structures, + immutable data structures, + persistent data structures, + transient data structures, + stack, + queue, + linked list, + tree, + graph, + hash table, + set, + map, + dictionary, + priority queue, + heap, + trie, + bloom filter, + bit array, + bitset, + bitboard, + ] +--- + +A data structure is a way of organizing and storing data so that it can be accessed and modified efficiently. It is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. + +Data structures can be classified into different types based on various criteria. Here are some common types of data structures: + +```mermaid +graph TD + A[Data Structures] --> B[Primitive Data Structures] + A[Data Structures] --> C[Non-Primitive Data Structures] + + B[Primitive Data Structures] --> D(Integer) + B[Primitive Data Structures] --> E(Float) + B[Primitive Data Structures] --> F(Character) + B[Primitive Data Structures] --> G(Boolean) + + C[Non-Primitive Data Structures] --> H[Linear Data Structures] + C[Non-Primitive Data Structures] --> I[Non-Linear Data Structures] + + H[Linear Data Structures] --> J[Static Data Structures] + H[Linear Data Structures] --> K[Dynamic Data Structures] + + J[Static Data Structures] --> L(Array) + + K[Dynamic Data Structures] --> M(Linked List) + K[Dynamic Data Structures] --> N(Stack) + K[Dynamic Data Structures] --> O(Queue) + + I[Non-Linear Data Structures] --> P[Trees] + I[Non-Linear Data Structures] --> Q[Graphs] +``` + +### Primitive Data Structures + +Primitive data structures are the basic data structures that are directly operated upon by the machine instructions. They include: + +1. **Integer**: A data type that represents whole numbers. + + for example: `1`, `2`, `3`, `4`, `5`, ... + + ```javascript title="Integer" + let num = 10; + ``` + +2. **Float**: A data type that represents real numbers with decimal points. + + for example: `1.0`, `2.5`, `3.14`, `4.2`, `5.75`, ... + + ```javascript title="Float" + let num = 3.14; + ``` + +3. **Character**: A data type that represents a single character. + + for example: `a`, `b`, `c`, `d`, `e`, ... + + ```javascript title="Character" + let ch = "A"; + ``` + +4. **Boolean**: A data type that represents true or false values. + + for example: `true`, `false` + + ```javascript title="Boolean" + let isTrue = true; + ``` + +### Non-Primitive Data Structures + +Non-primitive data structures are the advanced data structures that are derived from primitive data structures. They include: + +1. **Linear Data Structures**: Data structures in which elements are arranged in a sequential manner. They include: + + - **Static Data Structures**: Data structures in which the size is fixed at compile time. They include: + + - **Array**: A collection of elements of the same data type stored in contiguous memory locations. + + ```javascript title="Array" + let arr = [1, 2, 3, 4, 5]; + ``` + + - **Dynamic Data Structures**: Data structures in which the size can be changed at runtime. They include: + + - **Linked List**: A collection of elements called nodes, where each node contains a data field and a reference (link) to the next node in the sequence. + + ```javascript title="Linked List" + class Node { + constructor(data) { + this.data = data; + this.next = null; + } + } + + class LinkedList { + constructor() { + this.head = null; + } + + add(data) { + const newNode = new Node(data); + + if (!this.head) { + this.head = newNode; + } else { + let current = this.head; + + while (current.next) { + current = current.next; + } + + current.next = newNode; + } + } + } + + const list = new LinkedList(); + list.add(1); + list.add(2); + list.add(3); + ``` + + - **Stack**: A collection of elements with two main operations: push (insert) and pop (delete). + + ```javascript title="Stack" + class Stack { + constructor() { + this.items = []; + } + + push(element) { + this.items.push(element); + } + + pop() { + if (this.items.length === 0) { + return "Underflow"; + } + return this.items.pop(); + } + } + + const stack = new Stack(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.pop(); + ``` + + - **Queue**: A collection of elements with two main operations: enqueue (insert) and dequeue (delete). + + ```javascript title="Queue" + class Queue { + constructor() { + this.items = []; + } + + enqueue(element) { + this.items.push(element); + } + + dequeue() { + if (this.items.length === 0) { + return "Underflow"; + } + return this.items.shift(); + } + } + + const queue = new Queue(); + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + queue.dequeue(); + ``` + +2. **Non-Linear Data Structures**: Data structures in which elements are not arranged in a sequential manner. They include: + + - **Trees**: A hierarchical data structure with a root node and subtrees of children nodes. + + ```javascript title="Tree" + class Node { + constructor(data) { + this.data = data; + this.children = []; + } + + addChild(data) { + const child = new Node(data); + this.children.push(child); + } + } + + const tree = new Node(1); + tree.addChild(2); + tree.addChild(3); + ``` + + - **Graphs**: A non-linear data structure consisting of nodes (vertices) and edges (connections between nodes). + + ```javascript title="Graph" + class Graph { + constructor() { + this.nodes = []; + this.edges = []; + } + + addNode(node) { + this.nodes.push(node); + } + + addEdge(node1, node2) { + this.edges.push([node1, node2]); + } + } + + const graph = new Graph(); + graph.addNode(1); + graph.addNode(2); + graph.addEdge(1, 2); + ``` + + - **Hash Table**: A data structure that stores key-value pairs and provides fast lookup of values based on keys. + + ```javascript title="Hash Table" + class HashTable { + constructor() { + this.table = {}; + } + + put(key, value) { + this.table[key] = value; + } + + get(key) { + return this.table[key]; + } + } + + const hashTable = new HashTable(); + hashTable.put("name", "John"); + hashTable.get("name"); + ``` + + - **Heap**: A specialized tree-based data structure that satisfies the heap property. + + ```javascript title="Heap" + class MinHeap { + constructor() { + this.heap = []; + } + + insert(value) { + this.heap.push(value); + this.heapifyUp(); + } + + heapifyUp() { + let index = this.heap.length - 1; + + while (index > 0) { + let parentIndex = Math.floor((index - 1) / 2); + + if (this.heap[parentIndex] <= this.heap[index]) { + break; + } + + [this.heap[parentIndex], this.heap[index]] = [ + this.heap[index], + this.heap[parentIndex], + ]; + index = parentIndex; + } + } + } + + const minHeap = new MinHeap(); + minHeap.insert(3); + minHeap.insert(2); + minHeap.insert(1); + ``` + +## Different Between Primitive and Non-Primitive Data Structures + +|No. |Primitive Data Structures|Non-Primitive Data Structures| +|----|--------------------------|-----------------------------| +|1. |Basic data structures that are directly operated upon by the machine instructions.|Advanced data structures that are derived from primitive data structures.| +|2. |Examples: Integer, Float, Character, Boolean.|Examples: Array, Linked List, Stack, Queue, Tree, Graph, Hash Table, Heap.| +|3. |Stored in contiguous memory locations.|Stored in non-contiguous memory locations.| +|4. |Fixed size at compile time.|Size can be changed at runtime.| +|5. |Efficient for simple data storage and retrieval.|Efficient for complex data storage and retrieval.| +|6. |Low-level data structures.|High-level data structures.| + +## Different Between Linear and Non-Linear Data Structures + +|No. |Linear Data Structures|Non-Linear Data Structures| +|----|-----------------------|-------------------------| +|1. |Data structures in which elements are arranged in a sequential manner.|Data structures in which elements are not arranged in a sequential manner.| +|2. |Examples: Array, Linked List, Stack, Queue.|Examples: Tree, Graph.| +|3. |Elements are stored in a linear sequence.|Elements are stored in a non-linear sequence.| +|4. |Efficient for simple data storage and retrieval.|Efficient for complex data storage and retrieval.| +|5. |Low-level data structures.|High-level data structures.| + +## Different Between Static and Dynamic Data Structures + +|No. |Static Data Structures|Dynamic Data Structures| +|----|----------------------|----------------------| +|1. |Data structures in which the size is fixed at compile time.|Data structures in which the size can be changed at runtime.| +|2. |Examples: Array.|Examples: Linked List, Stack, Queue.| +|3. |Size is determined at compile time.|Size can be changed at runtime.| +|4. |Efficient for fixed-size data storage and retrieval.|Efficient for variable-size data storage and retrieval.| +|5. |Low-level data structures.|High-level data structures.| + +## Different Between Mutable and Immutable Data Structures + +|No. |Mutable Data Structures|Immutable Data Structures| +|----|-----------------------|------------------------| +|1. |Data structures in which the data can be modified after creation.|Data structures in which the data cannot be modified after creation.| +|2. |Examples: Array, Linked List, Stack, Queue.|Examples: String, Tuple, Set, Map.| +|3. |Data can be changed after creation.|Data cannot be changed after creation.| +|4. |Efficient for data that needs to be modified frequently.|Efficient for data that needs to be shared and reused.| +|5. |Low-level data structures.|High-level data structures.| + +## Conclusion + +Data structures are the building blocks of computer science. They are the tools you'll use to build software systems. Understanding the different types of data structures and their applications is essential for designing efficient algorithms and solving complex problems. By learning data structures, you'll be able to represent data in a meaningful way, store and organize data in memory, and build software systems that are scalable, efficient, and reliable. \ No newline at end of file diff --git a/docs/dsa/dsa.md b/docs/dsa/dsa.md new file mode 100644 index 000000000..4f0fdce3e --- /dev/null +++ b/docs/dsa/dsa.md @@ -0,0 +1,127 @@ +--- +id: dsa +title: Data Structures and Algorithms +sidebar_label: Data Structures and Algorithms +sidebar_position: 1 +description: "Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms." +tags: [dsa, data-structures, algorithms, programming, computer-science, software-engineering, competitive-programming, interview-preparation, open-source, learning, teaching, problem-solving, performance, career-growth, understanding, competitive-programming, coding-competitions, open-source, building-systems, learning-new-technologies, programming-languages, tools, concepts, problem-solving, data-structures, algorithms, resources, books, websites, courses, youtube-channels, practice, interview-preparation, competitive-programming, community, contribute] +--- + +> Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms. + +## Introduction + +Data Structures and Algorithms are the fundamental concepts that every programmer must know. They are the tools you'll use to build software systems. Data Structures are a way of organizing and storing data so that it can be accessed and modified efficiently. Algorithms are a set of instructions to solve a problem or perform a task. + +## What is Algorithm? + +An algorithm is a set of instructions to solve a problem or perform a task. It is a step-by-step procedure that defines a set of actions to be executed in a certain order to get the desired output. + +### Quility of Good Algorithm + +- **Correctness**: An algorithm is correct if it produces the correct result for all instances of the problem it is designed to solve. +- **Efficiency**: An algorithm is efficient if it solves the problem within the resources (like time and space) available to it. +- **Simplicity**: An algorithm is simple if it is easy to understand and implement. +- **Optimality**: An algorithm is optimal if it produces the best result among all possible solutions for the given problem. +- **Scalability**: An algorithm is scalable if it can handle the input size efficiently. +- **Adaptability**: An algorithm is adaptable if it can be easily modified to solve a different problem. +- **Robustness**: An algorithm is robust if it can handle invalid input without crashing. +- **Maintainability**: An algorithm is maintainable if it can be easily modified and maintained. +- **Reusability**: An algorithm is reusable if it can be used in different programs. + +### Algorithm Examples + +- **Sorting Algorithms**: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, Radix Sort, Counting Sort, Bucket Sort, etc. +- **Searching Algorithms**: Linear Search, Binary Search, Jump Search, Interpolation Search, Exponential Search, etc. +- **Graph Algorithms**: Breadth-First Search (BFS), Depth-First Search (DFS), Dijkstra's Algorithm, Bellman-Ford Algorithm, Floyd-Warshall Algorithm, Prim's Algorithm, Kruskal's Algorithm, etc. +- **Dynamic Programming Algorithms**: Fibonacci Series, Longest Common Subsequence, Longest Increasing Subsequence, Knapsack Problem, Matrix Chain Multiplication, etc. +- **Greedy Algorithms**: Fractional Knapsack Problem, Job Sequencing Problem, Huffman Coding, Prim's Algorithm, Kruskal's Algorithm, etc. +- **Divide and Conquer Algorithms**: Binary Search, Merge Sort, Quick Sort, Strassen's Algorithm, etc. +- **Backtracking Algorithms**: N-Queens Problem, Sudoku Solver, Knight's Tour, Rat in a Maze, etc. +- **Branch and Bound Algorithms**: Traveling Salesman Problem, 0/1 Knapsack Problem, Job Assignment Problem, etc. +- **Randomized Algorithms**: Randomized Quick Sort, Randomized Selection, Las Vegas Algorithm, Monte Carlo Algorithm, etc. +- **Approximation Algorithms**: Traveling Salesman Problem, Knapsack Problem, Set Cover Problem, etc. + +## What is Data Structure? + +A data structure is a way of organizing and storing data so that it can be accessed and modified efficiently. It is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. + +![Data Structure](image.png) + +:::note +Data structures are the building blocks of computer science. They are the tools you'll use to build software systems. Data structures are used to represent data in a meaningful way. They provide a way to store and organize data in memory. +::: + +### Types of Data Structures + +Data structures can be classified into two categories: + +```mermaid +graph TD + A[Data Structures] --> B[Primative Data Structures] + A[Data Structures] --> C[Non-Primative Data Structures] + + B[Primative Data Structures] --> D(Integer) + B[Primative Data Structures] --> EFloat + B[Primative Data Structures] --> F(Character) + B[Primative Data Structures] --> G(Boolean) + + C[Non-Primative Data Structures] --> H[Linear Data Structures] + C[Non-Primative Data Structures] --> I[Non-Linear Data Structures] + + H[Linear Data Structures] --> J[Static Data Structures] + H[Linear Data Structures] --> K[Dynamic Data Structures] + + J[Static Data Structures] --> L(Array) + + K[Dynamic Data Structures] --> M(Linked List) + K[Dynamic Data Structures] --> N(Stack) + K[Dynamic Data Structures] --> O(Queue) + + I[Non-Linear Data Structures] --> Q(Trees) + I[Non-Linear Data Structures] --> R(Graphs) + +``` + +1. **Primitive Data Structures**: These are the basic data structures that are directly operated upon by the machine instructions. They include Integer, Float, Character, Boolean, etc. +2. **Non-Primitive Data Structures**: These are the advanced data structures that are derived from primitive data structures. They include Linear Data Structures (Array, Linked List, Stack, Queue), Non-Linear Data Structures (Trees, Graphs), etc. + +### Data Structure Examples + +- **Array**: A collection of elements of the same data type stored in contiguous memory locations. +- **Linked List**: A collection of elements called nodes, where each node contains a data field and a reference (link) to the next node in the sequence. +- **Stack**: A collection of elements with two main operations: push (insert) and pop (delete). +- **Queue**: A collection of elements with two main operations: enqueue (insert) and dequeue (delete). +- **Tree**: A hierarchical data structure with a root node and subtrees of children nodes. +- **Graph**: A non-linear data structure consisting of nodes (vertices) and edges (connections between nodes). +- **Hash Table**: A data structure that stores key-value pairs and provides fast lookup of values based on keys. +- **Heap**: A specialized tree-based data structure that satisfies the heap property. + +## Why Learn Data Structures and Algorithms? + +Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. Here are some reasons why you should learn Data Structures and Algorithms: + +1. **Problem Solving**: Data Structures and Algorithms help you solve complex problems efficiently. +2. **Performance**: Data Structures and Algorithms help you write efficient code that runs faster and uses less memory. +3. **Understanding**: Data Structures and Algorithms help you understand how software systems work under the hood. +4. **Career Growth**: Data Structures and Algorithms are essential skills for software engineers, data scientists, machine learning engineers, and other tech professionals. +5. **Interview Preparation**: Data Structures and Algorithms are commonly asked in technical interviews for software engineering roles. +6. **Competitive Programming**: Data Structures and Algorithms are essential for competitive programming and coding competitions. +7. **Open Source**: Data Structures and Algorithms are used in open-source projects and libraries. +8. **Learning New Technologies**: Data Structures and Algorithms help you learn new programming languages, tools, and concepts. +9. **Building Systems**: Data Structures and Algorithms are the foundation of building software systems. +10. **Community**: Data Structures and Algorithms have a vibrant community of learners, educators, and practitioners. + +## Resources + +Here are some resources to help you learn and master Data Structures and Algorithms: + +1. **Books**: Introduction to Algorithms, Data Structures and Algorithms in Python, Algorithms, The Algorithm Design Manual, etc. +2. **Websites**: GeeksforGeeks, LeetCode, HackerRank, CodeSignal, CodeChef, TopCoder, etc. +3. **Courses**: Coursera, edX, Udemy, Khan Academy, MIT OpenCourseWare, Stanford Online, etc. +4. **YouTube Channels**: freeCodeCamp, HackerRank, GeeksforGeeks, mycodeschool, Abdul Bari, etc. +5. **Practice**: LeetCode, HackerRank, GeeksforGeeks, CodeChef, TopCoder, etc. + +## Conclusion + +Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms. Happy learning! \ No newline at end of file diff --git a/docs/dsa/image.png b/docs/dsa/image.png new file mode 100644 index 000000000..1fc9d0d8c Binary files /dev/null and b/docs/dsa/image.png differ diff --git a/docs/dsa/master-theorem.md b/docs/dsa/master-theorem.md new file mode 100644 index 000000000..9c4e48f33 --- /dev/null +++ b/docs/dsa/master-theorem.md @@ -0,0 +1,206 @@ +--- +id: master-theorem +title: Master Theorem for Divide and Conquer Recurrences +sidebar_label: Master Theorem +sidebar_position: 3 +description: "Master Theorem for solving divide and conquer recurrences. Explained with examples." +tags: + [ + dsa, + data-structures, + algorithms, + divide-and-conquer, + master-theorem, + recurrences, + ] +--- + +Master Theorem is a popular technique to solve recurrence relations of divide and conquer algorithms. It provides a way to determine the time complexity of recursive algorithms. The theorem is used to solve recurrences of the form: + +```plaintext title="Recurrence Relation" +T(n) = aT(n/b) + f(n) +``` + +where: + +- `T(n)` is the time complexity of the algorithm. +- `a` is the number of subproblems in the recursion. +- `n/b` is the size of each subproblem. +- `f(n)` is the time complexity of the work done outside the recursive calls. +- `n` is the size of the input. +- `a >= 1` and `b > 1` are constants. +- `f(n)` is a function that is asymptotically positive. +- `T(n)` is defined on non-negative integers. +- The recurrence relation is defined for `n >= n0` for some constant `n0`. + +The Master Theorem provides a way to determine the time complexity of the algorithm based on the values of `a`, `b`, and `f(n)`. + +## Master Theorem Cases {#master-theorem-cases} + +The Master Theorem has three cases based on the comparison of `f(n)` with `n^log_b(a)`: + +1. **Case 1**: If `f(n) = O(n^log_b(a - ε))` for some constant `ε > 0`, then `T(n) = Θ(n^log_b(a))`. +2. **Case 2**: If `f(n) = Θ(n^log_b(a))`, then `T(n) = Θ(n^log_b(a) * log(n))`. +3. **Case 3**: If `f(n) = Ω(n^log_b(a + ε))` for some constant `ε > 0`, if `a * f(n/b) <= c * f(n)` for some constant `c < 1` and sufficiently large `n`, then `T(n) = Θ(f(n))`. + +## Example {#example} + +Let's consider the recurrence relation for the Merge Sort algorithm: + +```plaintext title="Merge Sort Recurrence Relation" +T(n) = 2T(n/2) + Θ(n) +``` + +Here: + +- `a = 2` (number of subproblems). +- `b = 2` (size of each subproblem). +- `f(n) = Θ(n)` (time complexity of work done outside the recursive calls). +- `n` is the size of the input. +- `n0 = 1`. +- `f(n)` is asymptotically positive. +- `a >= 1` and `b > 1`. +- The recurrence relation is defined for `n >= n0`. +- The relation is of the form `T(n) = aT(n/b) + f(n)`. + +Now, let's compare `f(n)` with `n^log_b(a)`: + +- `n^log_b(a) = n^log_2(2) = n`. +- `f(n) = Θ(n)`. +- `f(n) = Θ(n) = n^log_b(a)`. + +Since `f(n) = Θ(n) = n^log_b(a)`, the recurrence relation falls under **Case 2** of the Master Theorem. Therefore, the time complexity of the Merge Sort algorithm is `T(n) = Θ(n * log(n))`. + +## Conclusion {#conclusion} + +The Master Theorem provides a way to determine the time complexity of divide and conquer algorithms. It simplifies the process of solving recurrence relations and helps in analyzing the time complexity of recursive algorithms. By comparing the function `f(n)` with `n^log_b(a)`, the Master Theorem classifies the recurrence relation into one of the three cases and provides the time complexity of the algorithm. + +Master Theorem is a powerful tool to analyze the time complexity of divide and conquer algorithms. It is widely used in the analysis of recursive algorithms to determine their time complexity. + +## Implementations + + + + ```js + function masterTheorem(a, b, f, n) { + if (a < 1 || b < 1) { + return "Invalid input"; + } + + const logBaseB = Math.log(a) / Math.log(b); + + if (f === n ** logBaseB) { + return `T(n) = Θ(n^${logBaseB} * log(n))`; + } else if (f < n ** logBaseB) { + return `T(n) = Θ(n^${logBaseB})`; + } else { + return "Case 3: Not covered by Master Theorem"; + } + } + ``` + + + ```java + public class MasterTheorem { + public static String masterTheorem(int a, int b, int f, int n) { + if (a < 1 || b < 1) { + return "Invalid input"; + } + + double logBaseB = Math.log(a) / Math.log(b); + + if (f == Math.pow(n, logBaseB)) { + return String.format("T(n) = Θ(n^%.2f * log(n))", logBaseB); + } else if (f < Math.pow(n, logBaseB)) { + return String.format("T(n) = Θ(n^%.2f)", logBaseB); + } else { + return "Case 3: Not covered by Master Theorem"; + } + } + + public static void main(String[] args) { + System.out.println(masterTheorem(2, 2, 2, 2)); + } + } + ``` + + + + ```python + def master_theorem(a, b, f, n): + if a < 1 or b < 1: + return "Invalid input" + + log_base_b = a / b + + if f == n ** log_base_b: + return f"T(n) = Θ(n^{log_base_b} * log(n))" + elif f < n ** log_base_b: + return f"T(n) = Θ(n^{log_base_b})" + else: + return "Case 3: Not covered by Master Theorem" + ``` + + + + ```cpp + #include + #include + #include + + std::string masterTheorem(int a, int b, int f, int n) { + if (a < 1 || b < 1) { + return "Invalid input"; + } + + double logBaseB = log(a) / log(b); + + if (f == pow(n, logBaseB)) { + return "T(n) = Θ(n^" + std::to_string(logBaseB) + " * log(n))"; + } else if (f < pow(n, logBaseB)) { + return "T(n) = Θ(n^" + std::to_string(logBaseB) + ")"; + } else { + return "Case 3: Not covered by Master Theorem"; + } + } + + int main() { + std::cout << masterTheorem(2, 2, 2, 2) << std::endl; + return 0; + } + ``` + + + + +## Live Coding Implementation + +```jsx live +function MasterTheoremExample() { + const a = 2, b = 2, f = 2, n = 4; + + function MasterTheorem(a, b, f, n) { + if (a < 1 || b < 1) { + return `Invalid input`; + } + + const logBaseB = Math.log(a) / Math.log(b); + + if (f === n ** logBaseB) { + return `T(n) = Θ(n^${logBaseB} * log(n))`; + } else if (f < n ** logBaseB) { + return `T(n) = Θ(n^${logBaseB})`; + } else { + return `Case 3: Not covered by Master Theorem`; + } + } + + return ( +
+

+ Output: {MasterTheorem(a, b, f, n)} +

+
+ ); +} +``` \ No newline at end of file diff --git a/docs/features.md b/docs/features.md new file mode 100644 index 000000000..1d00d5f39 --- /dev/null +++ b/docs/features.md @@ -0,0 +1,273 @@ +--- +id: features +sidebar_position: 2 +title: Features of CodeHarborHub Documentation +sidebar_label: Features +description: "This documentation is intended to help you get started with CodeHarborHub and to provide you with a comprehensive guide to the features and functionality of the platform. This is a place to learn about technology, programming, web development, data science, and more." +tags: [features, codeharborhub, documentation, technology, programming, web development, data science, collaboration, learning, teaching, code, data, projects, tutorials, resources, version control, issue tracking, git, github, collaboration, learning, technology, programming, web development, data science ] +--- + +## Diagrams + +```bash +npm install --save @docusaurus/theme-mermaid +``` + +````md title="Example Mermaid diagram" +```mermaid +graph TD; + A-->B; + A-->C; + B-->D; + C-->D; +``` +```` + +```mermaid +graph TD; + A-->B; + A-->C; + B-->D; + C-->D; +``` + +## Tabs + +```md title="Example Tabs" +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + This is an apple 🍎 + + + This is an orange 🍊 + + + This is a banana 🍌 + + +``` + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + This is an apple 🍎 + + + This is an orange 🍊 + + + This is a banana 🍌 + + + +## Interactive code editor + +```bash +npm install --save @docusaurus/theme-live-codeblock +``` + +````md title="Example Live Code Block" +```jsx live +function Clock(props) { + const [date, setDate] = useState(new Date()); + useEffect(() => { + const timerID = setInterval(() => tick(), 1000); + + return function cleanup() { + clearInterval(timerID); + }; + }); + + function tick() { + setDate(new Date()); + } + + return ( +
+

It is {date.toLocaleTimeString()}.

+
+ ); +} +``` +```` + +```jsx live +function Clock(props) { + const [date, setDate] = useState(new Date()); + useEffect(() => { + const timerID = setInterval(() => tick(), 1000); + + return function cleanup() { + clearInterval(timerID); + }; + }); + + function tick() { + setDate(new Date()); + } + + return ( +
+

It is {date.toLocaleTimeString()}.

+
+ ); +} +``` + +## Multi-language support code blocks + + + + +```js +function helloWorld() { + console.log("Hello, world!"); +} +``` + + + + +```py +def hello_world(): + print("Hello, world!") +``` + + + + +```java +class HelloWorld { + public static void main(String args[]) { + System.out.println("Hello, World"); + } +} +``` + + + + +```c +#include + +int main() { + printf("Hello, World\n"); + return 0; +} +``` + + + + +## Add Apple Style Window + +import BrowserWindow from '@site/src/components/BrowserWindow'; + + +
+ +
+ + +## Highlighting with metadata string + +```jsx {1,4-6,11} +import React from 'react'; + +function MyComponent(props) { + if (props.isBar) { + return
Bar
; + } + + return
Foo
; +} + +export default MyComponent; +``` + +## Line numbering + +```jsx {1,4-6,11} showLineNumbers +import React from 'react'; + +function MyComponent(props) { + if (props.isBar) { + return
Bar
; + } + + return
Foo
; +} + +export default MyComponent; +``` + +## npm2yarn + +```bash npm2yarn +npm install @docusaurus/remark-plugin-npm2yarn +``` + +## warning + +:::warning +Beware of the dark side. +::: + +## danger + +:::danger +I find your lack of faith disturbing. +::: + +## info + +:::info +Luke, I am your father. +::: + +## success + +:::success +The Force will be with you, always. +::: + +## Admonitions + +:::caution +This is a caution admonition +::: + +:::note +This is a note admonition +::: + +:::tip +This is a tip admonition +::: + +:::important +This is an important admonition +::: + +import TOCInline from '@theme/TOCInline'; +import CodeBlock from '@theme/CodeBlock'; + +The table of contents for this page, serialized: + +{JSON.stringify(toc, null, 2)} + +The front matter of this page: + +
    + {Object.entries(frontMatter).map(([key, value]) =>
  • {key}: {value}
  • )} +
+ + + + +--- \ No newline at end of file diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 000000000..3aa45ed99 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,32 @@ +--- +id: docs +title: Welcome to CodeHarborHub Tutorials +sidebar_label: Welcome to CodeHarborHub +sidebar_position: 1 +slug: / +--- + +Welcome to the CodeHarborHub documentation! This documentation is intended to help you get started with CodeHarborHub and to provide you with a comprehensive guide to the features and functionality of the platform. This is a place to learn about technology, programming, web development, data science, and more. + +## What is CodeHarborHub? + +CodeHarborHub is a platform for managing and sharing code and data. It is designed to help researchers, developers, and data scientists collaborate on projects, share code and data, and manage their work in a secure and efficient manner. + +It also helps to begginers to learn about technology, programming, web development, data structures, algorithms, and more. + +## Who is CodeHarborHub for? + +CodeHarborHub is designed for anyone who needs to manage and share code and data. This includes researchers, developers, data scientists, and anyone else who needs to collaborate on projects, share code and data, and manage their work in a secure and efficient manner. CodeHarborHub is particularly well-suited for teams that need to work together on code and data projects, as it provides a range of features for collaboration and project management. + +## What can I do with CodeHarborHub? + +CodeHarborHub provides a range of features for learning, teaching, and collaborating on code and data projects. Some of the key features of CodeHarborHub include: + +- **Web Development**: CodeHarborHub provides a range of tutorials and resources for learning web development, including HTML, CSS, JavaScript, React, and more. +- **Data Science**: CodeHarborHub provides a range of tutorials and resources for learning data science, including Python, R, and more. +- **Collaboration**: CodeHarborHub provides a range of features for collaborating on code and data projects, including version control, issue tracking, git & github, and more. +- **Learning**: CodeHarborHub provides a range of tutorials and resources for learning technology, programming, web development, data science, and more. + +## Getting Started + +To get started with CodeHarborHub, you can follow the tutorials and resources in this documentation. You can also explore the platform and try out the features for yourself. If you have any questions or need help, you can reach out to the CodeHarborHub community for support. \ No newline at end of file diff --git a/docs/javascript/_category_.json b/docs/javascript/_category_.json new file mode 100644 index 000000000..9fbbf122d --- /dev/null +++ b/docs/javascript/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "JavaScript", + "position": 4, + "link": { + "type": "generated-index", + "description": "JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. In this tutorial, you'll learn the basics of JavaScript and how to use it to create interactive web experiences." + } + } \ No newline at end of file diff --git a/docs/javascript/arrays.md b/docs/javascript/arrays.md new file mode 100644 index 000000000..1fd9c7fe2 --- /dev/null +++ b/docs/javascript/arrays.md @@ -0,0 +1,476 @@ +--- +id: arrays-in-javascript +title: Arrays in JavaScript for Beginners +sidebar_label: Arrays +sidebar_position: 15 +tags: [JavaScript, Arrays, Array Methods, Array Destructuring, Array Properties, Array Methods, Array Iterators, Array Object, Array Destructuring, Array Length, Access Array Elements, Change Array Elements, Add Array Elements, Remove Array Elements, Loop Through Array, Array Methods, Array Destructuring] +description: "In the JavaScript programming language, arrays are used to store multiple values in a single variable. In this section, you will learn how to create and manipulate arrays in JavaScript. You will also learn about the different methods that can be used to manipulate arrays. We are going to cover the following topics in this section:" +--- + +> Arrays are used to store multiple values in a single variable. They are written with square brackets. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +``` + +## Access the Elements of an Array + +You can access an array element by referring to the index number. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits[0]); // Apple +console.log(fruits[1]); // Banana +console.log(fruits[2]); // Mango +console.log(fruits[3]); // Orange +``` + +## Change an Array Element + +You can change the value of an array element by referring to the index number. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +fruits[0] = "Cherry"; +console.log(fruits); // ["Cherry", "Banana", "Mango", "Orange"] +``` + +## Add an Array Element + +You can add an element to an array using the `push()` method. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +fruits.push("Cherry"); +console.log(fruits); // ["Apple", "Banana", "Mango", "Orange", "Cherry"] +``` + +## Remove an Array Element + +You can remove an element from an array using the `pop()` method. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +fruits.pop(); +console.log(fruits); // ["Apple", "Banana", "Mango"] +``` + +## Array Length + +The `length` property returns the length of an array (number of elements). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits.length); // 4 +``` + +## Loop Through an Array + +You can use a `for` loop to loop through all the elements of an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +for (let i = 0; i < fruits.length; i++) { + console.log(fruits[i]); +} +``` + +## Array Methods + +JavaScript has a number of built-in methods for working with arrays. + +### `toString()` + +The `toString()` method converts an array to a string of (comma separated) array values. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits.toString()); // Apple,Banana,Mango,Orange +``` + +### `join()` + +The `join()` method joins all the elements of an array into a string. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits.join(" * ")); // Apple * Banana * Mango * Orange +``` + +### `pop()` + +The `pop()` method removes the last element from an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let lastFruit = fruits.pop(); +console.log(lastFruit); // Orange +console.log(fruits); // ["Apple", "Banana", "Mango"] +``` + +### `push()` + +The `push()` method adds a new element to an array (at the end). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +fruits.push("Cherry"); +console.log(fruits); // ["Apple", "Banana", "Mango", "Orange", "Cherry"] +``` + +### `shift()` + +The `shift()` method removes the first element from an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let firstFruit = fruits.shift(); +console.log(firstFruit); // Apple +console.log(fruits); // ["Banana", "Mango", "Orange"] +``` + +### `unshift()` + +The `unshift()` method adds a new element to an array (at the beginning). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +fruits.unshift("Cherry"); +console.log(fruits); // ["Cherry", "Apple", "Banana", "Mango", "Orange"] +``` + +### `concat()` + +The `concat()` method joins two or more arrays, and returns a new array. + +```js title="index.js" +let fruits1 = ["Apple", "Banana", "Mango", "Orange"]; +let fruits2 = ["Cherry", "Grapes", "Pineapple"]; + +let allFruits = fruits1.concat(fruits2); +console.log(allFruits); // ["Apple", "Banana", "Mango", "Orange", "Cherry", "Grapes", "Pineapple"] +``` + +### `slice()` + +The `slice()` method slices out a piece of an array into a new array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange", "Cherry", "Grapes", "Pineapple"]; + +let citrusFruits = fruits.slice(2, 5); +console.log(citrusFruits); // ["Mango", "Orange", "Cherry"] +``` + +### `splice()` + +The `splice()` method adds/removes items to/from an array, and returns the removed item(s). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange", "Cherry", "Grapes", "Pineapple"]; + +fruits.splice(2, 2, "Lemon", "Kiwi"); + +console.log(fruits); // ["Apple", "Banana", "Lemon", "Kiwi", "Cherry", "Grapes", "Pineapple"] +``` + +### `sort()` + +The `sort()` method sorts the elements of an array. + +```js title="index.js" +let fruits = ["Banana", "Orange", "Apple", "Mango"]; +console.log(fruits.sort()); // ["Apple", "Banana", "Mango", "Orange"] +``` + +### `reverse()` + +The `reverse()` method reverses the order of the elements in an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.reverse()); // ["Orange", "Mango", "Banana", "Apple"] +``` + +### `indexOf()` + +The `indexOf()` method searches the array for an element and returns its position. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.indexOf("Mango")); // 2 +``` + +### `lastIndexOf()` + +The `lastIndexOf()` method searches the array for an element, starting at the end, and returns its position. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.lastIndexOf("Banana")); // 1 +``` + +### `includes()` + +The `includes()` method checks if an array contains a specified element. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.includes("Mango")); // true +console.log(fruits.includes("Cherry")); // false +``` + +### `find()` + +The `find()` method returns the value of the first element in an array that passes a test (provided as a function). + +```js title="index.js" +let ages = [3, 10, 18, 20]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.find(checkAdult)); // 18 +``` + +### `findIndex()` + +The `findIndex()` method returns the index of the first element in an array that passes a test (provided as a function). + +```js title="index.js" +let ages = [3, 10, 18, 20]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.findIndex(checkAdult)); // 2 +``` + +### `every()` + +The `every()` method checks if all elements in an array pass a test (provided as a function). + +```js title="index.js" +let ages = [32, 33, 16, 40]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.every(checkAdult)); // false +``` + +### `some()` + +The `some()` method checks if some elements in an array pass a test (provided as a function). + +```js title="index.js" +let ages = [3, 10, 18, 20]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.some(checkAdult)); // true +``` + +### `filter()` + +The `filter()` method creates a new array with all elements that pass a test (provided as a function). + +```js title="index.js" +let ages = [32, 33, 16, 40]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.filter(checkAdult)); // [32, 33, 40] +``` + +### `map()` + +The `map()` method creates a new array with the result of calling a function for each array element. + +```js title="index.js" +let numbers = [4, 9, 16, 25]; + +function myFunction(value) { + return value * 2; +} + +console.log(numbers.map(myFunction)); // [8, 18, 32, 50] +``` + +### `reduce()` + +The `reduce()` method reduces the array to a single value (going left-to-right). + +```js title="index.js" +let numbers = [175, 50, 25]; + +function myFunction(total, num) { + return total - num; +} + +console.log(numbers.reduce(myFunction)); // 100 +``` + +### `reduceRight()` + +The `reduceRight()` method reduces the array to a single value (going right-to-left). + +```js title="index.js" +let numbers = [175, 50, 25]; + +function myFunction(total, num) { + return total - num; +} + +console.log(numbers.reduceRight(myFunction)); // -50 +``` + +### `forEach()` + +The `forEach()` method calls a function once for each array element. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +fruits.forEach(function (value, index, array) { + console.log(value); +}); +``` + +### `isArray()` + +The `isArray()` method checks if an object is an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(Array.isArray(fruits)); // true +``` + +### `from()` + +The `from()` method creates a new Array instance from an array-like or iterable object. + +```js title="index.js" +let myArr = Array.from("ABCDEFG"); + +console.log(myArr); // ["A", "B", "C", "D", "E", "F", "G"] +``` + +### `of()` + +The `of()` method creates a new Array instance with a variable number of arguments. + +```js title="index.js" +let myArr = Array.of(1, 2, 3, 4, 5); + +console.log(myArr); // [1, 2, 3, 4, 5] +``` + +### `fill()` + +The `fill()` method fills the elements of an array with a static value. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.fill("Cherry")); // ["Cherry", "Cherry", "Cherry", "Cherry"] +``` + +### `copyWithin()` + +The `copyWithin()` method copies array elements within the array, to and from specified positions. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.copyWithin(2, 0)); // ["Apple", "Banana", "Apple", "Banana"] +``` + +### `entries()` + +The `entries()` method returns a new Array Iterator object that contains the key/value pairs for each index in the array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let iterator = fruits.entries(); + +for (let e of iterator) { + console.log(e); +} +``` + +### `keys()` + +The `keys()` method returns a new Array Iterator object that contains the keys for each index in the array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let iterator = fruits.keys(); + +for (let e of iterator) { + console.log(e); +} +``` + +### `values()` + +The `values()` method returns a new Array Iterator object that contains the values for each index in the array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let iterator = fruits.values(); + +for (let e of iterator) { + console.log(e); +} +``` + +## Array Destructuring + +Array destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let [first, second, third, fourth] = fruits; + +console.log(first); // Apple +console.log(second); // Banana +console.log(third); // Mango +console.log(fourth); // Orange +``` + +:::info 📝 Note +**Best Practice** + +It is best practice to use the `const` keyword when declaring arrays, as the array values are not expected to change. + + ```js title="index.js" + const fruits = ["Apple", "Banana", "Mango", "Orange"]; + ``` +::: + + +## Conclusion + +In this section, you learned how to create and manipulate arrays in JavaScript. You also learned about the different methods that can be used to manipulate arrays. You can now use arrays to store multiple values in a single variable and perform various operations on them. \ No newline at end of file diff --git a/docs/javascript/arrow-func-js.md b/docs/javascript/arrow-func-js.md new file mode 100644 index 000000000..4a4fba564 --- /dev/null +++ b/docs/javascript/arrow-func-js.md @@ -0,0 +1,164 @@ +--- +id: arrow-function-in-js +title: Arrow Function in JavaScript +sidebar_label: Arrow Function +sidebar_position: 35 +tags: [JavaScript, Arrow Function, ES6, ES2015, ES6 Features, ES2015 Features, ES6 Tutorials, ES2015 Tutorials, ES6 Tutorial, ES2015 Tutorial, ES6 Arrow Function, ES2015 Arrow Function, Arrow Function in JavaScript, Arrow Function in ES6, Arrow Function in ES2015, JavaScript Arrow Function, ES6 Arrow Function Tutorial, ES2015 Arrow Function Tutorial, Arrow Function Tutorial, Arrow Function in JavaScript Tutorial, Arrow Function in ES6 Tutorial, Arrow Function in ES2015 Tutorial, JavaScript Arrow Function Tutorial, ES6 Arrow Function Example, ES2015 Arrow Function Example, Arrow Function Example, Arrow Function in JavaScript Example, Arrow Function in ES6 Example, Arrow Function in ES2015 Example, JavaScript Arrow Function Example, ES6 Arrow Function Syntax, ES2015 Arrow Function Syntax, Arrow Function Syntax, Arrow Function in JavaScript Syntax, Arrow Function in ES6 Syntax, Arrow Function in ES2015 Syntax, JavaScript Arrow Function Syntax, ES6 Arrow Function Syntax Example, ES2015 Arrow Function Syntax Example, Arrow Function Syntax Example, Arrow Function in JavaScript Syntax Example, Arrow Function in ES6 Syntax Example, Arrow Function in ES2015 Syntax Example, JavaScript Arrow Function Syntax Example, ES6 Arrow Function Syntax Tutorial, ES2015 Arrow Function Syntax Tutorial, Arrow Function Syntax Tutorial, Arrow Function in JavaScript Syntax Tutorial, Arrow Function in ES6 Syntax Tutorial, Arrow Function in ES2015 Syntax Tutorial, JavaScript Arrow Function Syntax Tutorial, ES6 Arrow Function Syntax Example Tutorial, ES2015 Arrow Function Syntax Example Tutorial, Arrow Function Syntax Example Tutorial, Arrow Function in JavaScript Syntax Example Tutorial, Arrow Function in ES6 Syntax Example Tutorial, Arrow Function in ES2015 Syntax Example Tutorial, JavaScript Arrow Function Syntax Example Tutorial] +description: "In this tutorial, we will learn about the Arrow Function in JavaScript with the help of examples." +--- + +Arrow Function is a new feature introduced in ES6 (ES2015) that allows you to write shorter function syntax. It provides a more concise way to write functions in JavaScript. + +In this tutorial, you will learn about Arrow Function in JavaScript with the help of examples. + +## Arrow Function Syntax + +The syntax of the Arrow Function is as follows: + +```javascript title="Arrow Function Syntax" +const functionName = (param1, param2, ..., paramN) => { + // function body +}; +``` + +- `functionName`: It is the name of the function. +- `param1, param2, ..., paramN`: These are the parameters of the function. +- `=>`: It is the arrow notation that separates the parameters from the function body. +- `{}`: It contains the function body. +- `return`: If the function body contains a single statement, you can omit the `{}` and `return` keyword. +- `this`: Arrow functions do not have their own `this` value. They inherit the `this` value from the enclosing scope. +- `arguments`: Arrow functions do not have their own `arguments` object. You can use the `arguments` object of the enclosing scope. +- `new`: Arrow functions cannot be used as constructors and will throw an error if you try to use them with the `new` keyword. +- `super`: Arrow functions do not have their own `super` value. They inherit the `super` value from the enclosing scope. +- `prototype`: Arrow functions do not have the `prototype` property. +- `arguments.length`: Arrow functions do not have the `arguments.length` property. +- `new.target`: Arrow functions do not have the `new.target` property. +- `yield`: Arrow functions cannot be used as generators and will throw an error if you try to use them with the `yield` keyword. +- `this` binding: Arrow functions do not bind their own `this` value. They inherit the `this` value from the enclosing scope. + +## Arrow Function Examples + +Let's see some examples to understand how Arrow Functions work in JavaScript. + +### Example 1: Arrow Function with No Parameters + +The following example demonstrates an Arrow Function with no parameters: + +```javascript title="Arrow Function with No Parameters" +const greet = () => { + return 'Hello, World!'; +}; + +console.log(greet()); // Output: Hello, World! +``` + +In this example, the Arrow Function `greet` does not take any parameters and returns the string `'Hello, World!'`. + +### Example 2: Arrow Function with One Parameter + +The following example demonstrates an Arrow Function with one parameter: + +```javascript title="Arrow Function with One Parameter" +const greet = (name) => { + return `Hello, ${name}!`; +}; + +console.log(greet('John')); // Output: Hello, John! +``` + +In this example, the Arrow Function `greet` takes one parameter `name` and returns the string `'Hello, John!'`. + +### Example 3: Arrow Function with Multiple Parameters + +The following example demonstrates an Arrow Function with multiple parameters: + +```javascript title="Arrow Function with Multiple Parameters" + +const add = (a, b) => { + return a + b; +}; + +console.log(add(5, 3)); // Output: 8 +``` + +In this example, the Arrow Function `add` takes two parameters `a` and `b` and returns the sum of the two numbers. + +### Example 4: Arrow Function with a Single Statement + +If the function body contains a single statement, you can omit the `{}` and `return` keyword. The statement will be automatically returned. + +```javascript title="Arrow Function with a Single Statement" +const greet = (name) => `Hello, ${name}!`; + +console.log(greet('John')); // Output: Hello, John! +``` + +In this example, the Arrow Function `greet` takes one parameter `name` and returns the string `'Hello, John!'`. + +### Example 5: Arrow Function with Multiple Statements + +If the function body contains multiple statements, you need to use `{}` and the `return` keyword. + +```javascript title="Arrow Function with Multiple Statements" +const add = (a, b) => { + const sum = a + b; + return sum; +}; + +console.log(add(5, 3)); // Output: 8 +``` + +In this example, the Arrow Function `add` takes two parameters `a` and `b`, calculates the sum of the two numbers, and returns the result. + +### Example 6: Arrow Function with Default Parameters + +You can also use default parameters with Arrow Functions: + +```javascript title="Arrow Function with Default Parameters" +const greet = (name = 'World') => `Hello, ${name}!`; + +console.log(greet()); // Output: Hello, World! + + +console.log(greet('John')); // Output: Hello, John! +``` + +In this example, the Arrow Function `greet` takes one parameter `name` with a default value `'World'` and returns the string `'Hello, World!'` if no argument is passed. + +### Example 7: Arrow Function with Rest Parameters + +You can also use rest parameters with Arrow Functions: + +```javascript title="Arrow Function with Rest Parameters" +const sum = (...numbers) => { + let total = 0; + for (const num of numbers) { + total += num; + } + return total; +}; + +console.log(sum(1, 2, 3, 4, 5)); // Output: 15 +``` + +In this example, the Arrow Function `sum` takes rest parameters `...numbers` and calculates the sum of all the numbers passed as arguments. + +### Example 8: Arrow Function with Object Literal + +You can also return an object literal from an Arrow Function: + +```javascript title="Arrow Function with Object Literal" +const person = (name, age) => ({ name, age }); + +console.log(person('John', 30)); // Output: { name: 'John', age: 30 } +``` + +In this example, the Arrow Function `person` takes two parameters `name` and `age` and returns an object literal with the properties `name` and `age`. + +:::info 📝 Note +When returning an object literal from an Arrow Function, you need to wrap the object literal in parentheses `()` to avoid the confusion with the function body. +::: + +## Conclusion + +In this tutorial, you learned about Arrow Function in JavaScript with the help of examples. Arrow Functions provide a more concise way to write functions in JavaScript. They are a powerful feature introduced in ES6 (ES2015) that allows you to write shorter function syntax. \ No newline at end of file diff --git a/docs/javascript/basic-js.md b/docs/javascript/basic-js.md new file mode 100644 index 000000000..474ad7f5a --- /dev/null +++ b/docs/javascript/basic-js.md @@ -0,0 +1,118 @@ +--- +id: basic-javascript +title: Basic JavaScript Concepts +sidebar_label: Basic JavaScript +sidebar_position: 3 +tags: [JavaScript, Introduction of js, Introduction of JavaScript, Basic JavaScript Concepts, basic js concepts, basic js] +description: Basic concepts of JavaScript. Learn about displaying output in JavaScript, JavaScript display possibilities, and more. +--- + +In this tutorial, you will learn about the basic concepts of JavaScript. We know that JavaScript is easy to manipulate and can be used to create dynamic content on the web pages. That means JavaScript can be used to change the content of the web page without refreshing the page. Content may be text, images, or any other HTML element. + +**So, let's start with the basic concepts of JavaScript.** + +## Displaying Output in JavaScript + +To display output in JavaScript, we use the `console.log()` method. The `console.log()` method is used to display the output in the console of the web browser. + +```js title="index.js" +console.log('Hello World!'); +``` + +## JavaScript Display Possibilities + +JavaScript can display data in different ways. Here are some of the ways to display data in JavaScript: + +### 1. Alert Box + +The `alert()` method is used to display an alert box with a message and an OK button. + +```js title="index.js" +alert('Hello World!'); +``` + +### 2. Writing into an HTML Element + +The `document.write()` method is used to write into the HTML document. + +```js title="index.js" +document.write('Hello World!'); +``` + +### 3. Writing into the Browser Console + +The `console.log()` method is used to write into the browser console. + +```js title="index.js" +console.log('Hello World!'); +``` + +### 4. Writing into an HTML Element Using `innerHTML` + +The `innerHTML` property is used to write into an HTML element. + +```js title="index.html" + + + + +

+ + + + + +``` + + +

Hello World!

+
+ +### 5. Writing into an HTML Element Using `window.alert()` + +The `window.alert()` method is used to write into an HTML element. + +```js title="index.html" + + + + +

+ + + + + +``` + +### 6. Writing into an HTML Element Using `document.getElementById().innerText` + +The `document.getElementById().innerText` method is used to write into an HTML element. + +```js title="index.html" + + + + +

+ + + + + +``` + + +

Hello World!

+
+ +:::info +**Before moving to the next section, make sure you have a basic understanding of the above concepts.** +You can use any of the above methods to display the output in JavaScript. +::: \ No newline at end of file diff --git a/docs/javascript/best-practices-js.md b/docs/javascript/best-practices-js.md new file mode 100644 index 000000000..a91ed4ee6 --- /dev/null +++ b/docs/javascript/best-practices-js.md @@ -0,0 +1,136 @@ +--- +id: best-practices-in-js +title: Best Practices in JavaScript +sidebar_label: Best Practices +sidebar_position: 41 +tags: + [ JavaScript, Best Practices, Best Practices in JavaScript, JavaScript Best Practices, JavaScript Best Practices Tutorial, JavaScript Best Practices Example, JavaScript Best Practices Coding Standards, JavaScript Best Practices Recommendations, JavaScript Best Practices Conventions, JavaScript Best Practices Rules, JavaScript Best Practices Linting, JavaScript Best Practices ESLint, JavaScript Best Practices Prettier ] +description: "In this tutorial, we will learn about the best practices in JavaScript. We will learn about the coding standards, recommendations, conventions, rules, linting, ESLint, Prettier." +--- + +Best Practices in JavaScript are a set of coding standards, recommendations, conventions, and rules that developers should follow while writing JavaScript code. They help in maintaining the code quality, readability, and consistency across the codebase. They also help in avoiding common pitfalls and bugs in the code. + +There are various tools available for enforcing the best practices in JavaScript such as ESLint, Prettier, etc. These tools help in automatically checking the code against the best practices and providing suggestions or warnings to fix the issues. + +In this tutorial, we will learn about the best practices in JavaScript and how to enforce them using ESLint and Prettier. + +## Best Practices Rules + +The best practices in JavaScript consist of various rules that developers should follow while writing code. These rules cover various aspects of coding such as naming conventions, indentation, spacing, comments, etc. Some common rules in the best practices are: + +### Naming Conventions + +- Use camelCase for variable names. + + + + + ```javascript + let myVariable = 10; + ``` + + + + + ```javascript + let my_variable = 10; + ``` + + + + + +### Indentation + +- Use 2 spaces for indentation. + + + + + ```javascript + if (true) { + console.log("Hello"); + } + ``` + + + + + ```javascript + if (true) { + console.log("Hello"); + } + ``` + + + + + +### Spacing + +- Use spaces around operators. + + + + + ```javascript + let sum = a + b; + ``` + + + + + ```javascript + let sum=a+b; + ``` + + + + + +### Comments + +- Use comments to explain the code. + + + + + ```javascript + // This is a comment + let sum = a + b; // This is an inline comment + ``` + + + + + ```javascript + let sum = a + b; + ``` + + + + + +These are some of the common rules in the best practices in JavaScript. Following these rules helps in writing clean, readable, and maintainable code. + +## Linting + +Linting is the process of analyzing the code for potential errors, bugs, stylistic issues, and enforcing the best practices. ESLint is a popular linting tool for JavaScript that helps in identifying and fixing the issues in the code. + +ESLint can be configured to enforce the best practices rules and provide warnings or errors when the code violates these rules. It helps in maintaining the code quality and consistency across the codebase. + +## Prettier + +Prettier is an opinionated code formatter that helps in automatically formatting the code according to a predefined set of rules. It helps in maintaining a consistent code style across the codebase. + +Prettier can be integrated with ESLint to format the code automatically and enforce the best practices rules. It helps in saving time and effort in manually formatting the code. + +:::info 📝 Info + +In this tutorial, we learned about the best practices in JavaScript. We learned about the coding standards, recommendations, conventions, rules, linting, ESLint, and Prettier. Following the best practices helps in writing clean, readable, and maintainable code. It also helps in avoiding common pitfalls and bugs in the code. + +::: + +## Conclusion + +In this tutorial, we learned about the best practices in JavaScript. We learned about the coding standards, recommendations, conventions, rules, linting, ESLint, and Prettier. Following the best practices helps in writing clean, readable, and maintainable code. It also helps in avoiding common pitfalls and bugs in the code. \ No newline at end of file diff --git a/docs/javascript/breack-statement.md b/docs/javascript/breack-statement.md new file mode 100644 index 000000000..f945f635e --- /dev/null +++ b/docs/javascript/breack-statement.md @@ -0,0 +1,134 @@ +--- +id: breack-statement-in-javascript +title: Break Statement in JavaScript +sidebar_label: Break +sidebar_position: 25 +tags: + [ + JavaScript, + Break, + Statement, + Control, + Flow, + Loop, + Iteration, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the break statement in JavaScript. We will learn how to use the break statement to exit a loop prematurely in JavaScript." +--- + +In JavaScript, the `break` statement is used to exit a loop prematurely. It is often used when you want to terminate the loop based on a certain condition. + +## Syntax + +The syntax of the `break` statement is as follows: + +```js title="app.js" +for (let i = 1; i <= 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +- The `break` statement is used to exit the loop prematurely. +- It can be used inside a `for`, `while`, or `do...while` loop. +- When the `break` statement is encountered, the loop is terminated, and the program continues with the next statement after the loop. +- If the loop is inside a function, the `break` statement will terminate the loop and the function. +- The `break` statement should be used only within a loop, otherwise, it will produce a syntax error. +- The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. +- The `break` statement can be used to avoid an infinite loop by providing a way to exit the loop when a certain condition is met. +- The `break` statement can be used to optimize the performance of a loop by avoiding unnecessary iterations. +- The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. +- The `break` statement can be used to avoid an infinite loop by providing a way to exit the loop when a certain condition is met. + +## Flow Chart of the `break` Statement + +```mermaid +graph LR; + Start([Start]) --> Condition{Condition}; + Condition -- True --> Action1[Action1]; + Condition -- False --> Action2[Action2]; + Action1 --> Break{Break used?}; + Break -- Yes --> End((End)); + Break -- No --> Continue[Continue]; + Continue -- Next --> Condition; + Action2 --> End([End]); + End --> Stop([Stop]); + +``` + +## Example + +The following example demonstrates how to use the `break` statement to exit a loop based on a certain condition: + +```js title="app.js" +for (let i = 1; i <= 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +In this example, the `for` loop initializes the loop variable `i` to `1`. It then checks if `i` is less than or equal to `5`. If the condition is `true`, it executes the code inside the loop and increments `i` by `1`. However, when `i` is equal to `3`, the `break` statement is encountered, and the loop is terminated. The program then continues with the next statement after the loop. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +``` + +In this example, the loop is terminated when `i` is equal to `3`, and the program continues with the next statement after the loop. The numbers `1` and `2` are printed to the console before the loop is terminated. + +The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. It is often used to optimize the performance of a loop by avoiding unnecessary iterations. The `break` statement should be used with caution, as it can make the code harder to read and understand. It is recommended to use the `break` statement sparingly and only when necessary. + +## Example + +The following example demonstrates how to use the `break` statement to exit a loop based on a certain condition: + +```js title="app.js" +let numbers = [1, 2, 3, 4, 5]; +for (let i = 0; i < numbers.length; i++) { + if (numbers[i] === 3) { + break; + } + console.log(numbers[i]); +} +``` + +In this example, the `for` loop iterates over the elements of the `numbers` array. It checks if the current element is equal to `3`. If the condition is `true`, the `break` statement is encountered, and the loop is terminated. The program then continues with the next statement after the loop. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +``` + +In this example, the loop is terminated when the current element is equal to `3`, and the program continues with the next statement after the loop. The numbers `1` and `2` are printed to the console before the loop is terminated. + +The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. It is often used to optimize the performance of a loop by avoiding unnecessary iterations. The `break` statement should be used with caution, as it can make the code harder to read and understand. It is recommended to use the `break` statement sparingly and only when necessary. + +:::tip 🤔 Remember + +- The `break` statement is used to exit a loop prematurely. +- It can be used inside a `for`, `while`, or `do...while` loop. +- When the `break` statement is encountered, the loop is terminated, and the program continues with the next statement after the loop. +- The `break` statement should be used only within a loop, otherwise, it will produce a syntax error. +- The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. +- The `break` statement can be used to avoid an infinite loop by providing a way to exit the loop when a certain condition is met. +- The `break` statement can be used to optimize the performance of a loop by avoiding unnecessary iterations. + +::: + +## Summary + +In this tutorial, we learned about the `break` statement in JavaScript. We learned how to use the `break` statement to exit a loop prematurely based on a certain condition. We also learned about the syntax of the `break` statement and how to use it to optimize the performance of a loop. We also learned about the best practices for using the `break` statement and when to use it sparingly. diff --git a/docs/javascript/classes-js.md b/docs/javascript/classes-js.md new file mode 100644 index 000000000..ae65fc7b0 --- /dev/null +++ b/docs/javascript/classes-js.md @@ -0,0 +1,159 @@ +--- +id: classes-in-js +title: Classes in JavaScript +sidebar_label: Classes +sidebar_position: 36 +tags: [JavaScript, Classes, ES6, ES2015, ES6 Features, ES2015 Features, ES6 Tutorials, ES2015 Tutorials, ES6 Tutorial, ES2015 Tutorial, ES6 Classes, ES2015 Classes, Classes in JavaScript, Classes in ES6, Classes in ES2015, JavaScript Classes, ES6 Classes Tutorial, ES2015 Classes Tutorial, Classes Tutorial, Classes in JavaScript Tutorial, Classes in ES6 Tutorial, Classes in ES2015 Tutorial, JavaScript Classes Tutorial, ES6 Classes Example, ES2015 Classes Example, Classes Example, Classes in JavaScript Example, Classes in ES6 Example, Classes in ES2015 Example, JavaScript Classes Example, ES6 Classes Syntax, ES2015 Classes Syntax, Classes Syntax, Classes in JavaScript Syntax, Classes in ES6 Syntax, Classes in ES2015 Syntax, JavaScript Classes Syntax, ES6 Classes Syntax Example, ES2015 Classes Syntax Example, Classes Syntax Example, Classes in JavaScript Syntax Example, Classes in ES6 Syntax Example, Classes in ES2015 Syntax Example, JavaScript Classes Syntax Example, ES6 Classes Syntax Tutorial, ES2015 Classes Syntax Tutorial, Classes Syntax Tutorial, Classes in JavaScript Syntax Tutorial, Classes in ES6 Syntax Tutorial, Classes in ES2015 Syntax Tutorial, JavaScript Classes Syntax Tutorial, ES6 Classes Syntax Example Tutorial, ES2015 Classes Syntax Example Tutorial, Classes Syntax Example Tutorial, Classes in JavaScript Syntax Example Tutorial, Classes in ES6 Syntax Example Tutorial, Classes in ES2015 Syntax Example Tutorial, JavaScript Classes Syntax Example Tutorial] +description: "In this tutorial, you will learn about classes in JavaScript, a new feature introduced in ES6 (ES2015) that allows you to create objects using the class keyword." +--- + +In JavaScript, classes are a new feature introduced in ES6 (ES2015) that allows you to create objects using the `class` keyword. Classes are a template for creating objects, providing initial values for state and implementations of behavior. + +In this tutorial, you will learn about classes in JavaScript with the help of examples. + +## Classes in JavaScript + +The syntax for defining a class in JavaScript is as follows: + +```javascript title="Class Syntax" +class ClassName { + constructor(param1, param2, ..., paramN) { + // constructor body + } + + method1(param1, param2, ..., paramN) { + // method1 body + } + + method2(param1, param2, ..., paramN) { + // method2 body + } + + // more methods... +} +``` + +- `ClassName`: It is the name of the class. +- `constructor`: It is a special method for creating and initializing objects created with a class. It is called when a new instance of the class is created. +- `method1, method2, ..., methodN`: These are the methods of the class. +- `param1, param2, ..., paramN`: These are the parameters of the constructor and methods. +- `this`: It is a reference to the current instance of the class. +- `new`: It is used to create a new instance of the class. +- `extends`: It is used to create a subclass that inherits from another class. +- `super`: It is used to call the constructor of the parent class. +- `static`: It is used to define static methods on a class. +- `get`: It is used to define a getter method for a property. +- `set`: It is used to define a setter method for a property. +- `prototype`: It is used to add properties and methods to the class prototype. + +## Classes Examples + +Let's see some examples to understand how classes work in JavaScript. + +### Example 1: Creating a Class + +The following example demonstrates how to create a class in JavaScript: + +```javascript title="Creating a Class" +class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + + greet() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +} + +const john = new Person('John', 30); + +console.log(john.greet()); // Output: Hello, my name is John and I am 30 years old. +``` + +In this example, we have defined a class `Person` with a constructor that initializes the `name` and `age` properties of the class. The `greet` method returns a greeting message with the name and age of the person. + +We have created an instance of the `Person` class named `john` and called the `greet` method on it. + +### Example 2: Inheritance in Classes + +The following example demonstrates how to create a subclass that inherits from another class in JavaScript: + +```javascript title="Inheritance in Classes" +class Animal { + constructor(name) { + this.name = name; + } + + speak() { + return `${this.name} makes a sound.`; + } +} + +class Dog extends Animal { + constructor(name, breed) { + super(name); + this.breed = breed; + } + + speak() { + return `${this.name} barks loudly.`; + } +} + +const dog = new Dog('Buddy', 'Labrador'); + +console.log(dog.speak()); // Output: Buddy barks loudly. +``` + +In this example, we have defined a class `Animal` with a constructor that initializes the `name` property and a `speak` method. We have also defined a subclass `Dog` that inherits from the `Animal` class using the `extends` keyword. + +The `Dog` class has its own constructor that initializes the `name` and `breed` properties and overrides the `speak` method to return a different message. + +We have created an instance of the `Dog` class named `dog` and called the `speak` method on it. + +### Example 3: Static Methods in Classes + +The following example demonstrates how to define static methods on a class in JavaScript: + +```javascript title="Static Methods in Classes" +class MathUtils { + static add(a, b) { + return a + b; + } + + static subtract(a, b) { + return a - b; + } +} + +console.log(MathUtils.add(5, 3)); // Output: 8 +console.log(MathUtils.subtract(5, 3)); // Output: 2 +``` + +In this example, we have defined a class `MathUtils` with two static methods `add` and `subtract` that perform addition and subtraction operations, respectively. + +We have called the static methods directly on the class without creating an instance of the class. + +:::info 📝 Note +**Importent Points:** + +- The `constructor` method is a special method that is called when a new instance of the class is created. +- The `this` keyword is used to refer to the current instance of the class. +- The `extends` keyword is used to create a subclass that inherits from another class. +- Static methods are called on the class itself, not on instances of the class. +- The `super` keyword is used to call the constructor of the parent class. +- Getters and setters are used to define getter and setter methods for properties. +- The `prototype` property is used to add properties and methods to the class prototype. +- Arrow functions are not suitable for defining class methods as they do not have their own `this` value. +- Classes in JavaScript are syntactic sugar over the existing prototype-based inheritance model. +- Classes in JavaScript are first-class citizens and can be passed as arguments, returned from functions, and assigned to variables. +- Classes in JavaScript are not hoisted, so they must be defined before they are used. +- Classes in JavaScript can be defined in strict mode or non-strict mode. +- Classes in JavaScript can be defined in the global scope or inside a function. +- Classes in JavaScript can be defined using the `class` keyword or the `function` keyword. +::: + +## Conclusion + +In this tutorial, you learned about classes in JavaScript, a new feature introduced in ES6 (ES2015) that allows you to create objects using the `class` keyword. You also learned about constructors, methods, inheritance, static methods, and other features of classes in JavaScript. \ No newline at end of file diff --git a/docs/javascript/comments-js.md b/docs/javascript/comments-js.md new file mode 100644 index 000000000..6b0a45f4d --- /dev/null +++ b/docs/javascript/comments-js.md @@ -0,0 +1,101 @@ +--- +id: comments-in-javascript +title: Comments in JavaScript +sidebar_label: Comments in JavaScript +sidebar_position: 6 +tags: [JavaScript, Comments in JavaScript, comments in js, JavaScript comments] +description: Write comments in JavaScript to explain the code and make it more readable. Learn about single-line comments and multi-line comments in JavaScript. +--- + +In this tutorial, you will learn about comments in JavaScript. Comments are used to explain the code and make it more readable. They are ignored by the JavaScript interpreter. + +There are two types of comments in JavaScript: + +1. Single-line comments +2. Multi-line comments + +## Single-line Comments + +Single-line comments start with `//`. They are used to add comments to a single line. + +For example, + +```js title="single-line-comments.js" +// This is a single-line comment + +console.log("Hello, World!"); // Output: Hello, World! +``` + +## Multi-line Comments + +Multi-line comments start with `/*` and end with `*/`. They are used to add comments to multiple lines. + +For example, + +```js title="multi-line-comments.js" +/* +This is a multi-line comment +It can span multiple lines +*/ + +console.log("Hello, World!"); // Output: Hello, World! +``` + +In this example, the multi-line comment spans multiple lines. + +**Now Let's Get Started with html** + +```html title="index.html" + + + + + + Comments in JavaScript + + +

Comments in JavaScript

+

Open the console to see the output.

+ + + +``` + +In this example, we have added a single-line comment and a single-line comment at the end of the line. + +**Now Let's Get Started with multi-line comments** + +```html title="index.html" + + + + + + Comments in JavaScript + + +

Comments in JavaScript

+

Open the console to see the output.

+ + + +``` + +In this example, we have added a multi-line comment that spans multiple lines. + +:::note +Comments are used to explain the code and make it more readable. They are ignored by the JavaScript interpreter. +::: + +## Conclusion + +In this tutorial, you learned about comments in JavaScript. You learned about single-line comments and multi-line comments. Comments are used to explain the code and make it more readable. They are ignored by the JavaScript interpreter. \ No newline at end of file diff --git a/docs/javascript/const-js.md b/docs/javascript/const-js.md new file mode 100644 index 000000000..3252f5b0e --- /dev/null +++ b/docs/javascript/const-js.md @@ -0,0 +1,151 @@ +--- +id: const-in-javascript +title: Const Keyword in JavaScript +sidebar_label: Const Keyword +sidebar_position: 9 +tags: [JavaScript, const, ES6, Variables, Block Scope, Hoisting, Redeclaration, Best Practices, Comparison, let, var, Constants, ECMAScript 6, ES6, ES2015, Syntax, Example, Block Scope, Reassignment, Best Practices, Comparison with let, Comparison with var, Hoisting, Summary] +description: What is the const keyword in JavaScript and how to use it. +--- + +In JavaScript, the `const` keyword is used to declare a block-scoped variable that cannot be reassigned. It was introduced in ECMAScript 6 (ES6) and is the preferred way to declare constants in modern JavaScript. + +> ***ES6 (ECMAScript 2015) is a major update to JavaScript that adds new syntax and features to the language. It was officially released in June 2015.*** + +## Syntax + +The syntax to declare a constant using the `const` keyword is: + +```js title="Syntax" +const variableName = value; +``` + +Here, `variableName` is the name of the constant and `value` is the value assigned to the constant. + +## Example + +Let's see an example to understand how to use the `const` keyword in JavaScript: + +```js title="Example" +const PI = 3.14159; +console.log(PI); // Output: 3.14159 +``` + +In the above example, we have declared a constant `PI` using the `const` keyword and assigned it a value `3.14159`. We then printed the value of the constant using `console.log()`. + +## Block Scope + +The `const` keyword is block-scoped, which means that the constant declared using `const` is only available within the block in which it is defined. + +```js title="Block Scope" +{ + const x = 10; + console.log(x); // Output: 10 +} + +console.log(x); // Uncaught ReferenceError: x is not defined +``` + +In the above example, the constant `x` is only available within the block in which it is defined. If we try to access it outside the block, it will result in a `ReferenceError`. + +## Reassignment + +The `const` keyword does not allow reassignment of the same constant once it has been initialized. + +```js title="Reassignment" +const x = 10; +x = 20; // Uncaught TypeError: Assignment to constant variable. +``` + +In the above example, we are trying to reassign the value of the constant `x`, which results in a `TypeError`. + +## Best Practices + +- Use the `const` keyword for values that are not intended to be reassigned. +- Use descriptive variable names to improve code readability. +- Use uppercase letters and underscores to name constants (e.g., `MAX_LENGTH`, `PI`, `TAX_RATE`). +- Avoid using `const` for complex objects or arrays, as it only prevents reassignment of the variable itself, not its properties or elements. +- Use `let` or `var` for values that need to be reassigned. +- Use `const` for values that are known at compile time and are not expected to change. +- Use `const` for function expressions, arrow functions, and classes to prevent accidental reassignment. +- Use `const` for values that are shared across multiple files or modules. +- Use `const` for values that are used as configuration settings or constants in your application. +- Use `const` for values that are used as default parameters in functions. + +## Comparison with let + +The `const` keyword is similar to the `let` keyword in that it is block-scoped and cannot be hoisted. However, the main difference is that a variable declared using `const` cannot be reassigned, whereas a variable declared using `let` can be reassigned. + +```js title="Comparison with let" +const x = 10; +x = 20; // Uncaught TypeError: Assignment to constant variable + +let y = 10; +y = 20; // No error +``` + +In the above example, we are trying to reassign the value of the constant `x`, which results in a `TypeError`. However, we can reassign the value of the variable `y` without any error. + +## Comparison with var + +The `const` keyword differs from the `var` keyword in terms of block scope, reassignment, and hoisting. + +### Block Scope + +Variables declared using the `var` keyword are function-scoped or globally-scoped, whereas variables declared using the `const` keyword are block-scoped. + +```js title="Block Scope" +// var +function varExample() { + if (true) { + var x = 10; + } + console.log(x); // Output: 10 +} + +// const + +{ + const y = 10; + console.log(y); // Output: 10 +} + +console.log(y); // Uncaught ReferenceError: y is not defined +``` + +In the above example, the variable `x` declared using the `var` keyword is available outside the block in which it is defined, whereas the constant `y` declared using the `const` keyword is not available outside the block. + +### Redeclaration + +The `var` keyword allows redeclaration of the same variable within the same block scope, whereas the `const` keyword does not allow redeclaration of the same constant within the same block scope. + +```js title="Redeclaration" +var x = 10; +var x = 20; // No error + +const y = 10; +const y = 20; // Uncaught SyntaxError: Identifier 'y' has already been declared +``` + +In the above example, we are trying to redeclare the variable `x` using the `var` keyword, which does not result in an error. However, we are trying to redeclare the constant `y` using the `const` keyword, which results in a `SyntaxError`. + +### Hoisting + +Variables declared using the `var` keyword are hoisted to the top of their function or global scope, whereas variables declared using the `const` keyword are not hoisted. + +```js title="Hoisting" +console.log(x); // Output: undefined +var x = 10; + +console.log(y); // Uncaught ReferenceError: y is not defined +const y = 10; +``` + +In the above example, the variable `x` declared using the `var` keyword is hoisted to the top of the global scope, whereas the constant `y` declared using the `const` keyword is not hoisted. + +:::info 📝 Note +It is recommended to use the `const` keyword for values that are not intended to be reassigned and are known at compile time. This helps prevent accidental reassignment and improves code readability. +::: + +## Summary + +Constants are block-scoped variables that cannot be reassigned once they are initialized. The `const` keyword is used to declare constants in JavaScript and is the preferred way to declare constants in modern JavaScript. It is similar to the `let` keyword in terms of block scope and hoisting, but it differs in that it does not allow reassignment. It also differs from the `var` keyword in terms of block scope, redeclaration, and hoisting. It is recommended to use the `const` keyword for values that are not intended to be reassigned and are known at compile time. \ No newline at end of file diff --git a/docs/javascript/datatypes/_category_.json b/docs/javascript/datatypes/_category_.json new file mode 100644 index 000000000..35b597457 --- /dev/null +++ b/docs/javascript/datatypes/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "Data Types in JavaScript", + "position": 11, + "link": { + "type": "generated-index", + "description": + "Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in JavaScript, data types are divided into two categories: primitive data types and object data types. Primitive data types are the most basic data types available in JavaScript. They are the building blocks for data manipulation. Object data types are more complex data types and are used to store collections of data and more complex entities." + } + } \ No newline at end of file diff --git a/docs/javascript/datatypes/datatypes-js.md b/docs/javascript/datatypes/datatypes-js.md new file mode 100644 index 000000000..6f571ae14 --- /dev/null +++ b/docs/javascript/datatypes/datatypes-js.md @@ -0,0 +1,217 @@ +--- +id: datatypes-in-javascript +title: Data Types in JavaScript +sidebar_label: Data Types +sidebar_position: 1 +tags: [JavaScript, Data Types, Primitive Data Types, Non-Primitive Data Types, String, Number, BigInt, Boolean, Undefined, Symbol, 'Null', Object, Array, Function, Type Conversion, Implicit Type Conversion, Explicit Type Conversion] +description: What is the data type in JavaScript? Learn about the primitive and non-primitive data types in JavaScript, including string, number, bigint, boolean, undefined, symbol, null, object, array, and function. +--- + +Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in JavaScript, data types are divided into two categories: + +1. **Primitive Data Types** +2. **Non-Primitive Data Types** + +## Primitive Data Types + +JavaScript has seven primitive data types: `string`, `number`, `bigint`, `boolean`, `undefined`, `symbol`, and `null`. + +### 1. String Data Type + +```js title="index.js" +let name = "John Doe"; +let message = 'Hello World!'; +``` + +### 2. Number Data Type + +The number data type is used to represent numeric values. It can be an integer or a floating-point number. For example: + +```js title="index.js" +let count = 100; +let price = 99.99; +``` + +### 3. Boolean Data Type + +The boolean data type represents a logical value. It can have only two values: `true` or `false`. For example: + +```js title="index.js" +let isTrue = true; +let isFalse = false; +``` + +### 4. Undefined Data Type + +The `undefined` data type represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. For example: + +```js title="index.js" +let data; +console.log(data); // Output: undefined +``` + +### 5. Null Data Type + +The `null` data type represents a null value. In JavaScript, `null` is not a reference to a non-existing object. It is simply a special value that represents "nothing", "empty", or "value unknown". For example: + +```js title="index.js" +let car = null; +``` + +### 6. Symbol Data Type + +The `symbol` data type represents a unique and immutable value and may be used as the key of an `Object` property. For example: + +```js title="index.js" +let id = Symbol('id'); +``` + +### 7. BigInt Data Type + +The `bigint` data type is used to represent whole numbers larger than `2^53 - 1`. It is a new feature in JavaScript and is not supported in all browsers. For example: + +```js title="index.js" +let value = 9007199254740991n; +``` + +## Non-Primitive Data Types + +Non-primitive data types are called reference types because they are accessed by reference. These data types are `Object`, `Array`, and `Function`. + +### 1. Object Data Type + +The `object` data type represents a collection of key-value pairs. For example: + +```js title="index.js" +let person = { + name: 'John Doe', + age: 25 +}; + +console.log(person.name); // Output: John Doe +``` + +### 2. Array Data Type + +The `array` data type represents a list of elements. For example: + +```js title="index.js" +let colors = ['red', 'green', 'blue']; +console.log(colors[0]); // Output: red +``` + +### 3. Function Data Type + +The `function` data type represents a function. For example: + +```js title="index.js" +function greet(name) { + return `Hello, ${name}!`; +} + +console.log(greet('John Doe')); // Output: Hello, John Doe! +``` + +## Type Conversion + +Type conversion is the process of converting the value from one data type to another. JavaScript provides two types of type conversion: + +1. **Implicit Type Conversion** +2. **Explicit Type Conversion** + +### 1. Implicit Type Conversion + +Implicit type conversion, also known as type coercion, is the automatic conversion of data types. For example: + +```js title="index.js" +let x = 10; +let y = "5"; +let z = x + y; + +console.log(z); // Output: 105 +``` + +In the above example, the number `10` is converted to a string and concatenated with the string `"5"`. + +### 2. Explicit Type Conversion + +Explicit type conversion, also known as type casting, is the manual conversion of data types. For example: + +```js title="index.js" +let x = "10"; +let y = 5; +let z = Number(x) + y; + +console.log(z); // Output: 15 +``` + +In the above example, the string `"10"` is converted to a number and added to the number `5`. + +:::tip tips and tricks +- In JavaScript, you can use the `Number()`, `String()`, `Boolean()`, and `BigInt()` functions to convert a value to a number, string, boolean, and bigint, respectively. +- The `parseInt()` and `parseFloat()` functions are used to convert a string to an integer and floating-point number, respectively. +::: + +:::info note +**1. Difference between primitive and non-primitive data types:** + +|No. |Primitive Data Types|Non-Primitive Data Types| +|--- |--- |--- | +|1. |Primitive data types are immutable.|Non-primitive data types are mutable.| +|2. |Primitive data types are stored in the stack.|Non-primitive data types are stored in the heap.| +|3. |Primitive data types are accessed by value.|Non-primitive data types are accessed by reference.| + +**2. Type conversion in JavaScript:** + +|No. |Implicit Type Conversion|Explicit Type Conversion| +|--- |--- |--- | +|1. |Implicit type conversion is the automatic conversion of data types.|Explicit type conversion is the manual conversion of data types.| +|2. |Implicit type conversion is performed by JavaScript.|Explicit type conversion is performed by the developer.| +|3. |Implicit type conversion is also known as type coercion.|Explicit type conversion is also known as type casting.| + +**3. Difference between pass by value and pass by reference:** + +|No. |Pass by Value|Pass by Reference| +|--- |--- |--- | +|1. |In pass by value, a copy of the actual value is passed to the function.|In pass by reference, the actual value is passed to the function.| +|2. |Pass by value is used for primitive data types.|Pass by reference is used for non-primitive data types.| +|3. |Pass by value is used in JavaScript for primitive data types.|Pass by reference is used in JavaScript for non-primitive data types.| +|4. |Pass by value is faster than pass by reference.|Pass by reference is slower than pass by value.| +|5. |Pass by value is used in the stack.|Pass by reference is used in the heap.| + +6. for example: + ```js title="pass by value" + let x = 10; + let y = x; + x = 20; + console.log(y); // Output: 10 + ``` + --- + + ```js title="Pass by Reference" + let person = { + name: 'Ajay Dhangar', + age: 25 + }; + let p = person; + person.name = 'Jane Doe'; + console.log(p.name); // Output: Jane Doe + ``` + +**4. Difference between `null` and `undefined`:** + +|No. |null|undefined| +|--- |--- |--- | +|1. |`null` represents a null value.|`undefined` represents an undefined value.| +|2. |`null` is an object.|`undefined` is a type.| +|3. |`null` is assigned to a variable.|`undefined` is the value of a variable that has not been assigned a value.| +|4. |`null` is used to represent "nothing", "empty", or "value unknown".|`undefined` is used to represent "undefined", "not defined", or "value unknown".| +|5. |`null` is a special value that represents "nothing", "empty", or "value unknown".|`undefined` is a special value that represents an undefined value.| +|6. |`let car = null;`|`let data;`| +| |`console.log(car); // Output: null`|`console.log(data); // Output: undefined`| + +::: + +## Conclusion + +In this article, we learned about the data types in JavaScript. We also learned about the type conversion in JavaScript. Understanding data types and type conversion is important for writing efficient and bug-free code. \ No newline at end of file diff --git a/docs/javascript/datatypes/non-primitive-data-types/_category_.json b/docs/javascript/datatypes/non-primitive-data-types/_category_.json new file mode 100644 index 000000000..d09ee00a1 --- /dev/null +++ b/docs/javascript/datatypes/non-primitive-data-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Non Primitive Data Types", + "position": 3, + "link": { + "type": "generated-index", + "description": "In JavaScript Non Primitive Data Types (object data types) are used to store complex data types. These are the reference data types. They are called so because they don't store the value directly, they store the reference of the value. The reference is a pointer to a location in memory where the value is stored. Non-primitive data types are used to store complex objects. They are also called reference data types because they refer to the objects. Non-primitive data types are Object, Array, and Function." + } + } \ No newline at end of file diff --git a/docs/javascript/datatypes/non-primitive-data-types/array-js.mdx b/docs/javascript/datatypes/non-primitive-data-types/array-js.mdx new file mode 100644 index 000000000..46fc94c0a --- /dev/null +++ b/docs/javascript/datatypes/non-primitive-data-types/array-js.mdx @@ -0,0 +1,306 @@ +--- +id: array-datatypes-in-javascript +title: Array Data Types in JavaScript +sidebar_label: Array +sidebar_position: 2 +tags: [JavaScript, Data Types, Non-Primitive Data Types, Array, 'Array in JavaScript', 'Array data type', 'Creating arrays in JavaScript', 'Accessing array elements', 'Modifying array elements', 'Adding array elements', 'Deleting array elements', 'Array methods', 'Array properties', 'Array styles', 'Typed arrays', 'Array-like objects', 'Array buffers', 'Array buffer views', 'Array destructuring', 'Array spread operator', Arrays Style, Dense Array, Sparse Array, Typed Arrays, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array] +description: What is the array data type in JavaScript? Learn about the array data type and how to create, access, modify, add, and delete array elements in JavaScript. +--- + +An `Array` is a non-primitive data type in JavaScript. It represents a collection of elements, where each element can be of any data type, including other arrays. + +```mermaid +graph TD; + subgraph "Arrays" + style arrayStyle fill:#FF00FF,color:#333,stroke-width:2px; + arrayStyle --> denseArray["Dense Array"]; + denseArray --> sparseArray["Sparse Array"]; + arrayStyle --> arrayLike["Array-like Objects"]; + arrayLike --> argumentsObject["Arguments Object"]; + end; + subgraph "Typed Arrays" + style typedArrayStyle fill:#FF00FF,color:#333,stroke-width:2px; + typedArrayStyle --> Int8Array["Int8Array"]; + typedArrayStyle --> Uint8Array["Uint8Array"]; + typedArrayStyle --> Uint8ClampedArray["Uint8ClampedArray"]; + typedArrayStyle --> Int16Array["Int16Array"]; + typedArrayStyle --> Uint16Array["Uint16Array"]; + typedArrayStyle --> Int32Array["Int32Array"]; + typedArrayStyle --> Uint32Array["Uint32Array"]; + typedArrayStyle --> Float32Array["Float32Array"]; + typedArrayStyle --> Float64Array["Float64Array"]; + end; + +``` + +## What is an Array in JavaScript? + +In JavaScript, an `Array` is a special type of object that represents a collection of elements. The elements can be of any data type, including other arrays. Arrays are used to store multiple values in a single variable. Each element in an array has a unique index, which is used to access the element. The index starts from `0` and goes up to `length - 1`, where `length` is the number of elements in the array. + + +## Creating Arrays in JavaScript + +You can create an array in JavaScript using the following syntax: + +```js title="Creating Arrays in JavaScript" +let numbers = [1, 2, 3, 4, 5]; +let names = ['John', 'Doe', 'Jane', 'Smith']; +let mixed = [1, 'John', true, null, undefined]; +``` + +In the above examples, we have created arrays of numbers, strings, and mixed data types. + +## Accessing Array Elements + +You can access elements of an array using their index. The index starts from `0` for the first element and goes up to `length - 1` for the last element. + +```js title="Accessing Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +console.log(numbers[0]); // Output: 1 +console.log(numbers[2]); // Output: 3 +console.log(numbers[4]); // Output: 5 +``` + +In the above example, we have accessed the first, third, and fifth elements of the `numbers` array using their indices. + +## Modifying Array Elements + +You can modify elements of an array using their index. + +```js title="Modifying Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +numbers[0] = 10; + +console.log(numbers); // Output: [10, 2, 3, 4, 5] +``` + +In the above example, we have modified the first element of the `numbers` array and changed its value to `10`. + +## Adding Array Elements + +You can add elements to the end of an array using the `push` method. + +```js title="Adding Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +numbers.push(6); + +console.log(numbers); // Output: [1, 2, 3, 4, 5, 6] +``` + +In the above example, we have added the number `6` to the end of the `numbers` array using the `push` method. + +## Deleting Array Elements + +You can delete elements from an array using the `delete` operator or the `splice` method. + +```js title="Deleting Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +delete numbers[2]; + +console.log(numbers); // Output: [1, 2, empty, 4, 5] +``` + +In the above example, we have deleted the third element of the `numbers` array using the `delete` operator. The element is replaced with `empty`, which is a placeholder for the deleted element. + +## Deleting Array Elements using `pop` Method + +You can also delete elements from the end of an array using the `pop` method. + +```js title="Deleting Array Elements using pop Method" +let numbers = [1, 2, 3, 4, 5]; + +numbers.pop(); + +console.log(numbers); // Output: [1, 2, 3, 4] +``` + +In the above example, we have deleted the last element of the `numbers` array using the `pop` method. + +:::info 📝 Note + +## Arrays Style in JavaScript + +There are different styles of arrays in JavaScript: + +### 1. Dense Array + +A dense array is an array in which the elements are stored in contiguous memory locations. It is the most common type of array in JavaScript. + +for example: + +```js title="Dense Array" +let numbers = [1, 2, 3, 4, 5]; +``` + +### 2. Sparse Array + +A sparse array is an array in which the elements are not stored in contiguous memory locations. It contains empty slots, which are placeholders for the missing elements. + +for example: + +```js title="Sparse Array" +let numbers = [1, , 3, , 5]; +``` + +### 3. Array-like Objects + +Array-like objects are objects that have a `length` property and indexed elements, but they are not instances of the `Array` constructor. + +for example: + +```js title="Array-like Objects" +let arrayLike = { + 0: 'a', + 1: 'b', + 2: 'c', + length: 3 +}; +``` + +### 4. Typed Arrays + +Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. They are used to represent raw binary data in memory and are used in various scenarios, such as working with WebGL, file I/O, and networking. + +for example: + +```js title="Typed Arrays" +let buffer = new ArrayBuffer(16); +let int32Array = new Int32Array(buffer); +``` + +## Typed Arrays in JavaScript + +Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. They are used to represent raw binary data in memory and are used in various scenarios, such as working with WebGL, file I/O, and networking. + +The following are the different types of typed arrays available in JavaScript: + +### 1. `Int8Array` + +The `Int8Array` represents an array of 8-bit signed integers. + +for example: + +```js title="Int8Array" +let buffer = new ArrayBuffer(16); +let int8Array = new Int8Array(buffer); +``` + +### 2. `Uint8Array` + +The `Uint8Array` represents an array of 8-bit unsigned integers. + +for example: + +```js title="Uint8Array" +let buffer = new ArrayBuffer(16); +let uint8Array = new Uint8Array(buffer); +``` + +### 3. `Uint8ClampedArray` + +The `Uint8ClampedArray` represents an array of 8-bit unsigned integers clamped to 0-255. + +for example: + +```js title="Uint8ClampedArray" +let buffer = new ArrayBuffer(16); +let uint8ClampedArray = new Uint8ClampedArray(buffer); +``` + +### 4. `Int16Array` + +The `Int16Array` represents an array of 16-bit signed integers. + +for example: + +```js title="Int16Array" +let buffer = new ArrayBuffer(16); +let int16Array = new Int16Array(buffer); +``` + +### 5. `Uint16Array` + +The `Uint16Array` represents an array of 16-bit unsigned integers. + +for example: + +```js title="Uint16Array" +let buffer = new ArrayBuffer(16); +let uint16Array = new Uint16Array(buffer); +``` + +### 6. `Int32Array` + +The `Int32Array` represents an array of 32-bit signed integers. + +for example: + +```js title="Int32Array" +let buffer = new ArrayBuffer(16); +let int32Array = new Int32Array(buffer); +``` + +### 7. `Uint32Array` + +The `Uint32Array` represents an array of 32-bit unsigned integers. + +for example: + +```js title="Uint32Array" +let buffer = new ArrayBuffer(16); +let uint32Array = new Uint32Array(buffer); +``` + +### 8. `Float32Array` + +The `Float32Array` represents an array of 32-bit floating-point numbers. + +for example: + +```js title="Float32Array" +let buffer = new ArrayBuffer(16); +let float32Array = new Float32Array(buffer); +``` + +### 9. `Float64Array` + +The `Float64Array` represents an array of 64-bit floating-point numbers. + +for example: + +```js title="Float64Array" +let buffer = new ArrayBuffer(16); +let float64Array = new Float64Array(buffer); +``` +::: + +--- + +:::tip Tips and Tricks + +1. **Array Literals**: The array literal syntax `[]` is the most common way to create arrays in JavaScript. +2. **Array Elements**: Arrays can contain elements of any data type, including other arrays. +3. **Accessing Array Elements**: You can access array elements using their index, which starts from `0`. +4. **Modifying Array Elements**: You can modify array elements using their index. +5. **Adding Array Elements**: You can add elements to the end of an array using the `push` method. +6. **Deleting Array Elements**: You can delete elements from an array using the `delete` operator or the `splice` method. +7. **Deleting Array Elements using `pop` Method**: You can delete elements from the end of an array using the `pop` method. +8. **Array Styles**: There are different styles of arrays in JavaScript, including dense arrays, sparse arrays, array-like objects, and typed arrays. +9. **Typed Arrays**: Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. +10. **Array Methods**: JavaScript provides various methods for working with arrays, such as `push`, `pop`, `shift`, `unshift`, `splice`, `slice`, `concat`, `join`, `reverse`, `sort`, `indexOf`, `lastIndexOf`, `includes`, `forEach`, `map`, `filter`, `reduce`, and `find`. +11. **Array Properties**: Arrays have various properties, such as `length`, `constructor`, and `prototype`. +12. **Array-like Objects**: Array-like objects are objects that have a `length` property and indexed elements, but they are not instances of the `Array` constructor. +13. **Typed Arrays**: Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. +14. **Array Buffers**: Array buffers are used to represent raw binary data in memory and are used in various scenarios, such as working with WebGL, file I/O, and networking. +15. **Array Buffer Views**: Array buffer views are used to read and write binary data to and from array buffers. +16. **Array Destructuring**: Array destructuring is a convenient way to extract multiple elements from an array and assign them to variables. +17. **Array Spread Operator**: The array spread operator (`...`) is used to expand an array into individual elements. +::: + +## Conclusion + +In this tutorial, you learned about the array data type in JavaScript and how to create, access, modify, add, and delete array elements. You can use arrays to store multiple values in a single variable and perform various operations on the elements of the array. \ No newline at end of file diff --git a/docs/javascript/datatypes/non-primitive-data-types/date-js.md b/docs/javascript/datatypes/non-primitive-data-types/date-js.md new file mode 100644 index 000000000..25bf66d77 --- /dev/null +++ b/docs/javascript/datatypes/non-primitive-data-types/date-js.md @@ -0,0 +1,163 @@ +--- +id: date-datatypes-in-javascript +title: Date Datatypes in JavaScript +sidebar_label: Date +sidebar_position: 4 +tags: [JavaScript, Date, Date Datatypes in JavaScript, Date in JavaScript, JavaScript Date, JavaScript Date Datatypes, JavaScript Date Object, JavaScript Date Methods, JavaScript Date Examples, JavaScript Date Tutorial, JavaScript Date and Time, JavaScript Date Format, JavaScript Date Operations, JavaScript Date Functions, JavaScript Date Properties, JavaScript Date Setters, JavaScript Date Getters, JavaScript Date Working with Dates and Times, JavaScript Date Difference, JavaScript Date Add Days, JavaScript Date Add Months, JavaScript Date Add Years, JavaScript Date Add Hours, JavaScript Date Add Minutes, JavaScript Date Add Seconds, JavaScript Date Add Milliseconds, JavaScript Date Add Time, JavaScript Date Format, JavaScript Date Format Examples, JavaScript Date Format Tutorial, JavaScript Date Format Options, JavaScript Date Format Locale, JavaScript Date Format Timezone, JavaScript Date Format Date, JavaScript Date Format Time, JavaScript Date Format Day, JavaScript Date Format Month, JavaScript Date Format Year, JavaScript Date Format Weekday, JavaScript Date Format Week, JavaScript Date Format Hour, JavaScript Date Format Minute, JavaScript Date Format Second, JavaScript Date Format Millisecond, JavaScript Date Format UTC, JavaScript Date Format Local, JavaScript Date Format ISO, JavaScript Date Format Short, JavaScript Date Format Medium, JavaScript Date Format Long, JavaScript Date Format Full, JavaScript Date Format Custom] +description: What is a Date in JavaScript and how to use it to work with dates and times. +--- + +Date is a built-in object in JavaScript that is used to work with dates and times. It is used to represent a date and time in JavaScript. It is used to work with dates and times in JavaScript. + +```mermaid +sequenceDiagram + participant User + participant JavaScriptEngine + participant DateObject + + User->>JavaScriptEngine: Create a new Date object + JavaScriptEngine->>DateObject: Create Date object + + loop Initialization + JavaScriptEngine->>DateObject: Initialize with current date and time + end + + User->>DateObject: Perform operations (e.g., getDate(), getMonth(), etc.) + DateObject-->>JavaScriptEngine: Return result + + loop Update + User->>JavaScriptEngine: Update Date object (e.g., setFullYear()) + JavaScriptEngine->>DateObject: Update Date object + end + + JavaScriptEngine-->>User: Return updated Date object +``` + +## What is a Date in JavaScript? + +A Date object in JavaScript is used to work with dates and times. It is used to represent a date and time in JavaScript. It is used to work with dates and times in JavaScript. + +## Creating a Date Object + +A Date object can be created using the `new` keyword followed by the `Date` constructor. + +```js title="Creating a Date object" +let date = new Date(); +``` + +This will create a new Date object initialized with the current date and time. + +## Date Methods + +The Date object has several methods that can be used to work with dates and times. Some of the most commonly used methods are: + +- `getDate()`: Returns the day of the month (1-31). +- `getMonth()`: Returns the month (0-11). +- `getFullYear()`: Returns the year. +- `getHours()`: Returns the hour (0-23). +- `getMinutes()`: Returns the minutes (0-59). +- `getSeconds()`: Returns the seconds (0-59). +- `getMilliseconds()`: Returns the milliseconds (0-999). +- `getTime()`: Returns the number of milliseconds since January 1, 1970. + +```js title="Using Date methods" +let date = new Date(); +console.log(date.getDate()); // 1-31 +console.log(date.getMonth()); // 0-11 +console.log(date.getFullYear()); // year +console.log(date.getHours()); // 0-23 +console.log(date.getMinutes()); // 0-59 +console.log(date.getSeconds()); // 0-59 +console.log(date.getMilliseconds()); // 0-999 +console.log(date.getTime()); // milliseconds since January 1, 1970 +``` + +```jsx live +function myDate() { + const [date, setDate] = useState(new Date()); + useEffect(() => { + const timerID = setInterval(() => tick(), 1000); + + return function cleanup() { + clearInterval(timerID); + }; + }); + + function tick() { + setDate(new Date()); + } + + return ( +
+

date.getDate(): {date.getDate()}

+

date.getMonth(): {date.getMonth()}

+

date.getFullYear(): {date.getFullYear()}

+

getHours(): {date.getHours()}

+

date.getMinutes(): {date.getMinutes()}

+

date.getSeconds(): {date.getSeconds()}

+

date.getMilliseconds(): {date.getMilliseconds()}

+

date.getTime(): {date.getTime()}

+
+ ); +} +``` + +## Updating a Date Object + +A Date object can be updated using the various `set` methods. + +- `setDate()`: Sets the day of the month (1-31). +- `setMonth()`: Sets the month (0-11). +- `setFullYear()`: Sets the year. +- `setHours()`: Sets the hour (0-23). +- `setMinutes()`: Sets the minutes (0-59). +- `setSeconds()`: Sets the seconds (0-59). +- `setMilliseconds()`: Sets the milliseconds (0-999). +- `setTime()`: Sets the number of milliseconds since January 1, 1970. + +```js title="Updating a Date object" +let date = new Date(); +date.setDate(15); // set the day of the month to 15 +date.setMonth(6); // set the month to July +date.setFullYear(2022); // set the year to 2022 +date.setHours(12); // set the hour to 12 +date.setMinutes(30); // set the minutes to 30 +date.setSeconds(45); // set the seconds to 45 +date.setMilliseconds(500); // set the milliseconds to 500 +date.setTime(1640999405500); // set the date to January 1, 2022 12:30:45.500 PM +``` + +## Working with Dates and Times + +The Date object can be used to work with dates and times in JavaScript. It can be used to perform various operations such as getting and updating date and time, calculating the difference between two dates, formatting dates, and so on. + +```js title="Working with Dates and Times" +let date1 = new Date(); +let date2 = new Date(2022, 6, 15, 12, 30, 0, 0); // July 15, 2022 12:30:00.000 PM + +// calculate the difference between two dates +let diff = date2 - date1; + +// format the date + +let options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}; + +console.log(date1.toLocaleDateString("en-US", options)); // Monday, January 1, 2022 + +// add 10 days to the date + +date1.setDate(date1.getDate() + 10); +``` + +:::info 📝 Note +The Date object in JavaScript uses a zero-based index for months (0-11) and a one-based index for days (1-31). +::: + +## Conclusion + +In this tutorial, we learned about the Date object in JavaScript and how to use it to work with dates and times. We learned how to create a Date object, use its methods to get and update date and time, and how to use it to work with dates and times in JavaScript. diff --git a/docs/javascript/datatypes/non-primitive-data-types/function-js.mdx b/docs/javascript/datatypes/non-primitive-data-types/function-js.mdx new file mode 100644 index 000000000..07db60514 --- /dev/null +++ b/docs/javascript/datatypes/non-primitive-data-types/function-js.mdx @@ -0,0 +1,211 @@ +--- +id: function-datatypes-in-javascript +title: Function Datatypes in JavaScript +sidebar_label: Function +sidebar_position: 3 +tags: [JavaScript, Function, Datatypes, JavaScript Tutorial, JavaScript Function, JavaScript Function Datatypes, JavaScript Function, Types of Function, JavaScript Function Types, JavaScript Function Expression, JavaScript Arrow Function, JavaScript IIFE, JavaScript Generator Function, JavaScript Function Parameters, JavaScript Function Return Value, JavaScript Function Definition, JavaScript Function Syntax, JavaScript Function Example, JavaScript Function Tutorial, JavaScript Function Basics, JavaScript Function Introduction, JavaScript Function Guide, JavaScript Function Fundamentals, JavaScript Function Overview, JavaScript Function Concepts, JavaScript Function Explained, JavaScript Function Quick Start, JavaScript Function Learning, JavaScript] +description: What is a function in JavaScript? How to define a function in JavaScript? What are the different ways to define a function in JavaScript? What are the different types of function in JavaScript? Learn all about functions in JavaScript in this guide. +--- + +In JavaScript, a function is a block of code that can be called and executed. It is a reusable piece of code that can be called multiple times. Functions are used to perform a specific task and can be defined using the `function` keyword. + +## Defining a Function + +A function can be defined using the `function` keyword followed by the function name and a pair of parentheses. The function body is enclosed within a pair of curly braces `{}`. + +```js title="Syntax" +function functionName() { + // function body +} +``` + +Here's an example of a simple function that logs a message to the console: + +```js title="Example" +function greet() { + console.log('Hello, World!'); +} + +greet(); // Output: Hello, World! +``` + +## Function Parameters + +A function can accept parameters, which are variables that are passed to the function when it is called. These parameters are used within the function to perform a specific task. + +```js title="Syntax" +function functionName(parameter1, parameter2, ...) { + // function body +} +``` + +Here's an example of a function that accepts a parameter: + +```js title="Example" +function greet(name) { + console.log(`Hello, ${name}!`); +} + +greet('John'); // Output: Hello, John! +greet('Jane'); // Output: Hello, Jane! +``` + +## Function Return Value + +A function can return a value using the `return` statement. The return value can be used by the calling code to perform further operations. + +```js title="Syntax" +function functionName() { + // function body + return value; +} +``` + +Here's an example of a function that returns a value: + +```js title="Example" +function add(a, b) { + return a + b; +} + +let result = add(2, 3); +console.log(result); // Output: 5 +``` + +## Function Expression + +A function can also be defined using a function expression, which is a function that is assigned to a variable. Function expressions can be named or anonymous. + +### Named Function Expression + +A named function expression is a function expression that has a name. The name can be used within the function to refer to itself. + +```js title="Syntax" +let functionName = function() { + // function body +}; +``` + +Here's an example of a named function expression: + +```js title="Example" +let greet = function sayHello() { + console.log('Hello, World!'); +}; + +greet(); // Output: Hello, World! + +// The function name can be used within the function + +sayHello(); // ReferenceError: sayHello is not defined +``` + +### Anonymous Function Expression + +An anonymous function expression is a function expression that does not have a name. It is assigned to a variable and can be called using the variable name. + +```js title="Syntax" +let functionName = function() { + // function body +}; +``` + +Here's an example of an anonymous function expression: + +```js title="Example" +let greet = function() { + console.log('Hello, World!'); +}; + +greet(); // Output: Hello, World! +``` + +## Arrow Function + +An arrow function is a concise way to define a function using the `=>` syntax. It is a shorthand for writing function expressions. + +```js title="Syntax" +let functionName = (parameter1, parameter2, ...) => { + // function body +}; +``` + +Here's an example of an arrow function: + +```js title="Example" +let greet = name => { + console.log(`Hello, ${name}!`); +}; + +greet('John'); // Output: Hello, John! + +// If the function body contains only one statement, the curly braces can be omitted + +let add = (a, b) => a + b; + +let result = add(2, 3); + +console.log(result); // Output: 5 +``` + +## IIFE (Immediately Invoked Function Expression) + +An IIFE is a function that is defined and called immediately. It is used to create a new scope and to avoid polluting the global scope. + +```js title="Syntax" +(function() { + // function body +})(); +``` + +Here's an example of an IIFE: + +```js title="Example" +(function() { + let message = 'Hello, World!'; + console.log(message); +})(); + +// Output: Hello, World! + +console.log(message); // ReferenceError: message is not defined +``` + +## Generator Function + +A generator function is a special type of function that can be paused and resumed. It is defined using the `function*` keyword and the `yield` keyword is used to pause the function. + +```js title="Syntax" +function* functionName() { + // function body +} +``` + +Here's an example of a generator function: + +```js title="Example" +function* count() { + yield 1; + yield 2; + yield 3; +} + +let generator = count(); + +console.log(generator.next().value); // Output: 1 +console.log(generator.next().value); // Output: 2 +console.log(generator.next().value); // Output: 3 +console.log(generator.next().value); // Output: undefined +``` + +:::info 📝 Note +1. **Function Declaration**: A function declaration is hoisted, which means it is available before it is defined. It can be called before it is defined. +2. **Function Expression**: A function expression is not hoisted, which means it is not available before it is defined. It cannot be called before it is defined. +3. **Arrow Function**: An arrow function does not have its own `this`, `arguments`, `super`, or `new.target`. It uses the `this`, `arguments`, `super`, and `new.target` of the enclosing scope. +4. **IIFE**: An IIFE is used to create a new scope and to avoid polluting the global scope. It is defined and called immediately. +5. **Generator Function**: A generator function is a special type of function that can be paused and resumed. It is defined using the `function*` keyword and the `yield` keyword is used to pause the function. +::: + +## Conclusion + +In this tutorial, we learned about functions in JavaScript. We learned how to define a function, how to pass parameters to a function, how to return a value from a function, and the different ways to define a function in JavaScript. We also learned about function expressions, arrow functions, IIFE, and generator functions. Functions are an important concept in JavaScript and are used to perform a specific task. They are reusable and can be called multiple times. \ No newline at end of file diff --git a/docs/javascript/datatypes/non-primitive-data-types/object-js.mdx b/docs/javascript/datatypes/non-primitive-data-types/object-js.mdx new file mode 100644 index 000000000..f79ba6c42 --- /dev/null +++ b/docs/javascript/datatypes/non-primitive-data-types/object-js.mdx @@ -0,0 +1,275 @@ +--- +id: object-datatypes-in-javascript +title: Object Data Types in JavaScript +sidebar_label: Object +sidebar_position: 1 +tags: [JavaScript, Data Types, Non-Primitive Data Types, Object, 'Object in JavaScript', 'Object data type', 'Object methods', 'Object properties', 'Object constructor', 'Creating objects in JavaScript', 'Accessing object properties', 'Modifying object properties', 'Adding object properties', 'Deleting object properties'] +description: What is the object data type in JavaScript? Learn about the object data type and how to create, access, modify, add, and delete object properties in JavaScript. +--- + +The `Object` is a non-primitive data type in JavaScript. It represents a collection of key-value pairs, where the keys are strings (or symbols) and the values can be of any data type, including other objects. + +```mermaid +classDiagram + class Object { + Object() + toString(): string + hasOwnProperty(prop: string): boolean + isPrototypeOf(obj: Object): boolean + propertyIsEnumerable(prop: string): boolean + } + + class Function { + Function() + apply(thisArg: any, argsArray?: any[]): any + call(thisArg: any, ...args: any[]): any + bind(thisArg: any, ...args: any[]): any + toString(): string + } + + class Array { + Array() + length: number + concat(...items: ConcatArray[]): T[] + push(...items: T[]): number + pop(): T | undefined + slice(start?: number, end?: number): T[] + splice(start: number, deleteCount?: number): T[] + indexOf(searchElement: T, fromIndex?: number): number + } + + class Date { + Date() + now(): number + toString(): string + getFullYear(): number + getMonth(): number + getDate(): number + getDay(): number + getHours(): number + getMinutes(): number + getSeconds(): number + getMilliseconds(): number + } + + Object <|-- Function + Object <|-- Array + Object <|-- Date + +``` + +## What is Object in JavaScript? + +In JavaScript, an `Object` is a non-primitive data type that represents a collection of key-value pairs. It is used to store various keyed collections and more complex entities. An object can be created using the object literal syntax `{}` or the `Object` constructor. + +## Syntax of Object in JavaScript + +The syntax for creating an object in JavaScript using the object literal syntax is as follows: + +```js title="Object Literal Syntax" +let object = { + key1: value1, + key2: value2, + // ... + keyN: valueN +}; +``` + +In the above syntax: + +- `object` is the name of the object. +- `key1`, `key2`, and `keyN` are the keys of the object. +- `value1`, `value2`, and `valueN` are the values associated with the keys. +- The keys and values are separated by a colon (`:`), and the key-value pairs are separated by commas (`,`). +- The keys can be strings or symbols, and the values can be of any data type, including other objects. +- The object literal syntax `{}` is the most common way to create objects in JavaScript. + +## How to Create Objects in JavaScript? + +You can create an `Object` in JavaScript using the following syntax: + +```js title="Creating Objects in JavaScript" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +console.log(person); // Output: { name: 'John Doe', age: 30, isEmployed: true } +``` + +In the above example, the `person` object is created using the object literal syntax `{}`. It contains three key-value pairs: `name`, `age`, and `isEmployed`. + +## Accessing Object Properties + +You can access the properties of an object using the dot notation (`.`) or the bracket notation (`[]`). + +### Dot Notation + +You can access the properties of an object using the dot notation (`.`) as follows: + +```js title="Accessing Object Properties using Dot Notation" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +console.log(person.name); // Output: John Doe +console.log(person.age); // Output: 30 +console.log(person.isEmployed); // Output: true +``` + +### Bracket Notation + +You can also access the properties of an object using the bracket notation (`[]`) as follows: + +```js title="Accessing Object Properties using Bracket Notation" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +console.log(person['name']); // Output: John Doe +console.log(person['age']); // Output: 30 +console.log(person['isEmployed']); // Output: true +``` + +## Modifying Object Properties + +You can modify the properties of an object using the assignment operator (`=`). + +```js title="Modifying Object Properties" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +person.age = 35; + +console.log(person.age); // Output: 35 +``` + +In the above example, the `age` property of the `person` object is modified from `30` to `35`. + +## Adding Object Properties + +You can add new properties to an object using the assignment operator (`=`). + +```js title="Adding Object Properties" +let person = { + name: 'Ajay Dhangar', + age: 23, + isEmployed: true +}; + +person.city = 'Mandsaur'; + +console.log(person.city); // Output: Mandsaur +``` + +In the above example, the `city` property is added to the `person` object with the value `'Mandsaur'`. + +## Deleting Object Properties + +You can delete properties from an object using the `delete` operator. + +```js title="Deleting Object Properties" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +delete person.isEmployed; + +console.log(person); // Output: { name: 'John Doe', age: 30 } +``` + +In the above example, the `isEmployed` property is deleted from the `person` object. + +## What Can an Object Contain? + +An object can contain properties and methods. Properties are key-value pairs, and methods are functions associated with the object. + +```js title="Object Properties and Methods" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true, + greet: function() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +}; + +console.log(person.name); // Output: John Doe +console.log(person.age); // Output: 30 +console.log(person.isEmployed); // Output: true +console.log(person.greet()); // Output: Hello, my name is John Doe and I am 30 years old. +``` + +In the above example, the `person` object contains four properties: `name`, `age`, `isEmployed`, and `greet`. The `greet` property is a method that returns a greeting message using the `name` and `age` properties of the object. + +## Object Methods + +An object can also contain methods, which are functions that are associated with the object. You can define methods as properties of an object. + +```js title="Object Methods" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true, + greet: function() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +}; + +console.log(person.greet()); // Output: Hello, my name is John Doe and I am 30 years old. +``` + +In the above example, the `greet` method is defined as a property of the `person` object. It returns a greeting message using the `name` and `age` properties of the object. + +## Object Constructor + +You can also create objects using the `Object` constructor. + +```js title="Creating Objects using Object Constructor" +let person = new Object(); + +person.name = 'John Doe'; + +console.log(person.name); // Output: John Doe +``` + +:::info 📝 Note +The object literal syntax `{}` is the preferred way to create objects in JavaScript. The `Object` constructor is rarely used to create objects. + +The object literal syntax is more concise and easier to read than the `Object` constructor. +::: + +:::tip tips and tricks + +**1. Object Literals**: The object literal syntax `{}` is the most common way to create objects in JavaScript. + +**2. Object Properties**: Objects can contain properties and methods. Properties are key-value pairs, and methods are functions associated with the object. + +**3. Accessing Object Properties**: You can access object properties using the dot notation (`.`) or the bracket notation (`[]`). + +**4. Modifying Object Properties**: You can modify object properties using the assignment operator (`=`). + +**5. Adding Object Properties**: You can add new properties to an object using the assignment operator (`=`). + +**6. Deleting Object Properties**: You can delete properties from an object using the `delete` operator. + +**7. Object Methods**: Objects can contain methods, which are functions associated with the object. + +**8. Object Constructor**: You can create objects using the `Object` constructor, but the object literal syntax is preferred. + +::: + + +## Conclusion + +In JavaScript, the `Object` is a non-primitive data type that represents a collection of key-value pairs. You can create objects using the object literal syntax `{}` or the `Object` constructor. Objects can contain properties and methods, and you can access, modify, add, and delete properties of an object using various techniques. \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/_category_.json b/docs/javascript/datatypes/primitive-data-types/_category_.json new file mode 100644 index 000000000..b8d89e854 --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Primitive Data Types", + "position": 2, + "link": { + "type": "generated-index", + "description": "In the JavaScript, Primitive Data Types are immutable and are passed by value. There are 7 primitive data types: string, number, bigint, boolean, undefined, null and symbol." + } + } \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/big-int-js.md b/docs/javascript/datatypes/primitive-data-types/big-int-js.md new file mode 100644 index 000000000..a450891a9 --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/big-int-js.md @@ -0,0 +1,82 @@ +--- +id: bigint-in-javascript +title: BigInt Data Types in JavaScript +sidebar_label: BigInt +sidebar_position: 6 +tags: [JavaScript, Data Types, Primitive Data Types, BigInt, 'BigInt in JavaScript', 'BigInt data type'] +description: What is the BigInt data type in JavaScript? Learn about the BigInt data type and how to create BigInt in JavaScript. +--- + +`BigInt` is a primitive data type in JavaScript. It represents an arbitrary-precision integer. It is used to represent integers larger than the maximum safe integer value. + +```mermaid +graph LR; + A(BigInt)-->|Represents an arbitrary-precision integer| B(BigIntValue); +``` + +## What is BigInt in JavaScript? + +In JavaScript, `BigInt` is a primitive data type that represents an arbitrary-precision integer. It is used to represent integers larger than the maximum safe integer value. + +## How to Create BigInt in JavaScript? + +You can create `BigInt` in JavaScript using the following syntax: + +```js title="Creating BigInt in JavaScript" +let bigNumber = 9007199254740991n; // BigInt + +console.log(bigNumber); // Output: 9007199254740991n +``` + +In the above example, the variable `bigNumber` is assigned the value `9007199254740991n`. The `n` at the end of the number indicates that it is a `BigInt`. + +## Checking for BigInt in JavaScript + +You can check if a variable is a `BigInt` using the `typeof` operator. + +```js title="Checking for BigInt in JavaScript" +let bigNumber = 9007199254740991n; + +console.log(typeof bigNumber); // Output: bigint +``` + +In the above example, the `typeof` operator returns `bigint` for the `bigNumber` variable, indicating that it is a `BigInt`. + +## BigInt vs. Number + +| No. | BigInt | Number | +| --- | ------ | ------ | +| 1. | `BigInt` is used to represent integers larger than the maximum safe integer value. | `Number` is used to represent both integer and floating-point numbers. | +| 2. | `BigInt` is suffixed with `n` to indicate that it is a `BigInt`. | `Number` is not suffixed with any character. | +| 3. | `BigInt` is a primitive data type. | `Number` is a primitive data type. | +| 4. | `BigInt` is used to perform arithmetic operations on large integers. | `Number` is used to perform arithmetic operations on numbers. | + +## BigInt Literals + +A `BigInt` literal is created by appending `n` to the end of an integer or by calling the `BigInt()` function. + +```js title="BigInt Literals" +let bigNumber1 = 9007199254740991n; // BigInt literal + +let bigNumber2 = BigInt(9007199254740991); // BigInt literal using BigInt() function +``` + +In the above example, `bigNumber1` and `bigNumber2` are both `BigInt` literals. + +:::info 📝 Note +- The `n` at the end of the number indicates that it is a `BigInt`. You can also create a `BigInt` using the `BigInt()` function. For example: `let bigNumber = BigInt(9007199254740991);`. +- `n` is not a part of the number, it is a part of the syntax to create a `BigInt`. +- You cannot perform arithmetic operations between `BigInt` and other number types. You need to convert the other number types to `BigInt` before performing arithmetic operations. + + ![perform arithmetic operations between BigInt and other number](image.png) + +- `BigInt` is not supported in all browsers. You should check for browser compatibility before using `BigInt`. +- `BigInt` is a new feature in JavaScript and is not supported in older versions of browsers. +- You can use the `typeof` operator to check if a variable is a `BigInt`. + +::: + + +## Conclusion + +In this tutorial, you learned about the `BigInt` data type in JavaScript, how to create `BigInt` in JavaScript, and how to check for `BigInt` in JavaScript. You also learned that `BigInt` is a primitive data type that represents an arbitrary-precision integer and is used to represent integers larger than the maximum safe integer value. \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/boolean-js.md b/docs/javascript/datatypes/primitive-data-types/boolean-js.md new file mode 100644 index 000000000..a4236440d --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/boolean-js.md @@ -0,0 +1,188 @@ +--- +id: boolean-in-javascript +title: Boolean Data Types in JavaScript +sidebar_label: Boolean +sidebar_position: 3 +tags: [JavaScript, Data Types, Primitive Data Types, Boolean, 'Boolean Data Type', 'Boolean Values', 'Boolean Methods', 'Truthy and Falsy'] +description: What is the boolean data type in JavaScript? Learn about the boolean data type in JavaScript, including how to create a boolean, boolean values, and boolean methods. +--- + +Booleans are a primitive data type in JavaScript. They are used to represent logical values. JavaScript uses the `Boolean` object to represent `true` or `false`. + +```mermaid +graph TD; + A(Boolean)-->|Logical Value| B(true); + A(Boolean)-->|Logical Value| C(false); +``` + +## What is a Boolean in JavaScript? + +In JavaScript, booleans are used to represent logical values. JavaScript uses the `Boolean` object to represent `true` or `false`. + +## How to Create a Boolean in JavaScript? + +You can create a boolean in JavaScript using the following syntax: + +```js title="Creating a Boolean in JavaScript" +let isTrue = true; +let isFalse = false; +``` + +In the above example, `isTrue` and `isFalse` are booleans. + +## Boolean Values + +The boolean data type has only two possible values: `true` and `false`. For example: + +```js title="Boolean Values" +let isTrue = true; +let isFalse = false; +``` + +## Boolean Methods + +The `Boolean` object has several methods that are used to perform operations on boolean values. For example: + +```js title="Boolean Methods" +let isTrue = true; +let isFalse = false; + +console.log(isTrue.toString()); // Output: "true" +console.log(isFalse.valueOf()); // Output: false +``` + +In the above example, the `toString()` method is used to convert a boolean to a string, and the `valueOf()` method is used to return the primitive value of a boolean. + +:::info 📝 Note +The `Boolean` object is a wrapper for a boolean value. It is rarely used in practice, as booleans can be created directly without using the `Boolean` object. + +The `Boolean` object is not a constructor. It does not have a `new` operator. It is a function that converts a value to a boolean. + +The `Boolean` object has a single property: `prototype`. It is the prototype for the `Boolean` object. + +for example: + +```js title="Boolean Object" +let isTrue = true; +let isFalse = false; + +console.log(Boolean(isTrue)); // Output: true +console.log(Boolean(isFalse)); // Output: false +``` + +In the above example, the `Boolean` object is used to convert a value to a boolean. + +**1. What is truthy and falsy in JavaScript?** + +In JavaScript, a value is considered "falsy" if it converts to `false` when evaluated in a boolean context. The following values are considered "falsy" in JavaScript: + +- `false` +- `0` +- `""` (empty string) +- `null` +- `undefined` +- `NaN` (Not a Number) +- `document.all` (an object that is present in Internet Explorer) + +All other values are considered "truthy" in JavaScript. + +For example: + +```js title="Truthy and Falsy Values" +let isTrue = true; +let isFalse = false; + +console.log(Boolean(isTrue)); // Output: true +console.log(Boolean(isFalse)); // Output: false +console.log(Boolean(0)); // Output: false +console.log(Boolean("")); // Output: false +console.log(Boolean(null)); // Output: false +console.log(Boolean(undefined)); // Output: false +console.log(Boolean(NaN)); // Output: false +console.log(Boolean(document.all)); // Output: false +``` + +In the above example, the `Boolean` object is used to convert values to booleans. The values `0`, `""`, `null`, `undefined`, `NaN`, and `document.all` are considered "falsy" in JavaScript. + +**2. Difference between truthy and falsy** + +The difference between truthy and falsy is that truthy values are considered `true` when evaluated in a boolean context, while falsy values are considered `false` when evaluated in a boolean context. + +For example: + +**Truthy Values** + +- `true`: The boolean value `true` is considered "truthy" in JavaScript. +- `1`: The number `1` is considered "truthy" in JavaScript. +- `"hello"`: The string `"hello"` is considered "truthy" in JavaScript. +- `[]` (empty array): An empty array is considered "truthy" in JavaScript. +- `{}` (empty object): An empty object is considered "truthy" in JavaScript. +- `function() {}` (empty function): An empty function is considered "truthy" in JavaScript. +- `new Date()`: A new date is considered "truthy" in JavaScript. +- `Infinity`: The value `Infinity` is considered "truthy" in JavaScript. +- `-Infinity`: The value `-Infinity` is considered "truthy" in JavaScript. +- `3.14`: The number `3.14` is considered "truthy" in JavaScript. + +**Falsy Values** + +- `false`: The boolean value `false` is considered "falsy" in JavaScript. +- `0`: The number `0` is considered "falsy" in JavaScript. +- `""` (empty string): An empty string is considered "falsy" in JavaScript. +- `null`: The value `null` is considered "falsy" in JavaScript. +- `undefined`: The value `undefined` is considered "falsy" in JavaScript. +- `NaN`: The value `NaN` is considered "falsy" in JavaScript. +- `0n`: The bigint value `0n` is considered "falsy" in JavaScript. +- `-0`: The number `-0` is considered "falsy" in JavaScript. + + +for example: + +```js title="Truthy Values" +let isTrue = true; +const num = 1; +const str = "hello"; +const arr = []; +const obj = {}; +const func = function() {}; +const date = new Date(); +const inf = Infinity; +const ninf = -Infinity; +const pi = 3.14; + +console.log(Boolean(isTrue)); // Output: true +console.log(Boolean(num)); // Output: true +console.log(Boolean(str)); // Output: true +console.log(Boolean(arr)); // Output: true +console.log(Boolean(obj)); // Output: true +console.log(Boolean(func)); // Output: true +console.log(Boolean(date)); // Output: true +console.log(Boolean(inf)); // Output: true +console.log(Boolean(ninf)); // Output: true +console.log(Boolean(pi)); // Output: true +``` + +```js title="Falsy Values" +let isFalse = false; +const zero = 0; +const emptyStr = ""; +const nul = null; +const undef = undefined; +const nan = NaN; +const bigZero = 0n; +const negZero = -0; + +console.log(Boolean(isFalse)); // Output: false +console.log(Boolean(zero)); // Output: false +console.log(Boolean(emptyStr)); // Output: false +console.log(Boolean(nul)); // Output: false +console.log(Boolean(undef)); // Output: false +console.log(Boolean(nan)); // Output: false +console.log(Boolean(bigZero)); // Output: false +console.log(Boolean(negZero)); // Output: false +``` + +::: + +## Conclusion + +In this tutorial, you learned about the boolean data type in JavaScript, including how to create a boolean, boolean values, and boolean methods. You also learned about the `Boolean` object and its methods. \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/image.png b/docs/javascript/datatypes/primitive-data-types/image.png new file mode 100644 index 000000000..56db1aefb Binary files /dev/null and b/docs/javascript/datatypes/primitive-data-types/image.png differ diff --git a/docs/javascript/datatypes/primitive-data-types/null-js.md b/docs/javascript/datatypes/primitive-data-types/null-js.md new file mode 100644 index 000000000..d66d878d0 --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/null-js.md @@ -0,0 +1,67 @@ +--- +id: null-in-javascript +title: Null Data Types in JavaScript +sidebar_label: "Null" +sidebar_position: 5 +tags: [JavaScript, Data Types, Primitive Data Types, 'Null', 'null data type', 'null in JavaScript'] +description: What is the null data type in JavaScript? Learn about the null data type and how to create null in JavaScript. +--- + +`null` is a primitive data type in JavaScript. It represents a null value. It is used to represent an empty value or no value at all. + +```mermaid +graph LR; + A(Null)-->|Represents a null value| B(NullValue); +``` + +## What is Null in JavaScript? + +In JavaScript, `null` is a primitive data type that represents a null value. It is used to represent an empty value or no value at all. + +## How to Create Null in JavaScript? + +You can create `null` in JavaScript using the following syntax: + +```js title="Creating Null in JavaScript" +let data = null; + +console.log(data); // Output: null +``` + +In the above example, the variable `data` is assigned the value `null`. When you log the value of `data`, it will output `null`. + +## Checking for Null in JavaScript + +You can check if a variable is `null` using the `typeof` operator or by comparing the variable to `null`. + +```js title="Checking for Null in JavaScript" +let data = null; + +console.log(typeof data); // Output: object + +if (data === null) { + console.log('The variable is null'); +} else { + console.log('The variable is not null'); +} +``` + +In the above example, the `typeof` operator returns `object` for the `data` variable, and the comparison `data === null` returns `true`, indicating that the variable is `null`. + + +:::info 📝Note +In JavaScript, `null` is of type `object`. This is a bug in the language that has been kept for compatibility reasons. + +## Null vs. Undefined + +`null` and `undefined` are both used to represent the absence of a value in JavaScript. However, they are not the same. + +- `null` is a primitive data type that represents a null value. It is often used to explicitly set a variable to have no value. + +- `undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +::: + +## Conclusion + +In this article, you learned about the `null` data type in JavaScript, how to create `null` in JavaScript, and how to check for `null` in JavaScript. You also learned that `null` is a primitive data type that represents a null value and is used to represent an empty value or no value at all. \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/number-js.md b/docs/javascript/datatypes/primitive-data-types/number-js.md new file mode 100644 index 000000000..e8721c33e --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/number-js.md @@ -0,0 +1,122 @@ +--- +id: number-datatypes-in-javascript +title: Number Data Types in JavaScript +sidebar_label: Number +sidebar_position: 1 +tags: [JavaScript, Data Types, Primitive Data Types, Number, Integer, Floating-Point Number, NaN, Infinity, BigInt, 'Number.MAX_VALUE', 'Number.MIN_VALUE', 'Number.EPSILON', 'Number.POSITIVE_INFINITY', 'Number.NEGATIVE_INFINITY', 'Number.NaN'] +description: What is the number data type in JavaScript? Learn about the number data type in JavaScript, including integers, floating-point numbers, NaN, Infinity, and BigInt. +--- + +Numbers are a primitive data type in JavaScript. They are used to represent numeric values. JavaScript uses the `Number` object to represent both integer and floating-point numbers. + +```mermaid +graph TD; + A(Number)-->|Integer| B(1, 2, 3, etc.); + A(Number)-->|Float| C(1.1, 2.2, 3.3, etc.); + A(Number)-->|NaN| D(Not a Number); + A(Number)-->|Infinity| E(Positive Infinity, Negative Infinity); + A(Number)-->|BigInt| F(9007199254740991n); + +``` + +## What is a Number in JavaScript? + +In JavaScript, numbers are used to represent numeric values. JavaScript uses the `Number` object to represent both integer and floating-point numbers. + +## How to Create a Number in JavaScript? + +You can create a number in JavaScript using the following syntax: + +```js title="Creating a Number in JavaScript" +let count = 100; // Integer +let price = 99.99; // Floating-point number +``` + +In the above example, `count` is an integer, and `price` is a floating-point number. + +## Integer + +An integer is a whole number, positive or negative, without decimals, of unlimited length. For example: + +```js title="Integer" +let count = 100; +let temperature = -10; +``` + +## Floating-Point Number + +A floating-point number is a number with a decimal point or an exponent. For example: + +```js title="Floating-Point Number" +let price = 99.99; +let pi = 3.14; +``` + +## NaN (Not a Number) + +`NaN` is a special value that represents "Not-a-Number". It indicates that a value is not a legal number. For example: + +```js title="NaN" +let result = 100 / "Apple"; +console.log(result); // Output: NaN +``` + +## Infinity + +`Infinity` is a special value that represents positive infinity. It is displayed when a number exceeds the upper limit of the floating-point numbers. For example: + +```js title="Infinity" +let max = Number.MAX_VALUE; +let infinity = max * 2; +console.log(infinity); // Output: Infinity +``` + +## BigInt + +The `bigint` data type is used to represent whole numbers larger than `2^53 - 1`. It is a new feature in JavaScript and is not supported in all browsers. For example: + +```js title="BigInt" +let value = 9007199254740991n; +``` + +:::info 📝 Note +- The `n` at the end of the number indicates that it is a `bigint`. You can also create a `bigint` using the `BigInt()` function. For example: `let value = BigInt(9007199254740991);`. +- `n` is not a part of the number, it is a part of the syntax to create a `bigint`. +- You cannot perform arithmetic operations between `bigint` and other number types. You need to convert the other number types to `bigint` before performing arithmetic operations. +- infinity is used to represent positive infinity, and `-Infinity` is used to represent negative infinity. +- `NaN` is used to represent "Not-a-Number". It indicates that a value is not a legal number. +- `Number.MAX_VALUE` is the largest positive finite value representable in JavaScript. +- `Number.MIN_VALUE` is the smallest positive value representable in JavaScript. +- `Number.EPSILON` is the smallest interval between two representable numbers. +- `Number.POSITIVE_INFINITY` is the positive infinity value. +::: + +:::tip tipes and tricks +1. Integers: + - An integer is a whole number, positive or negative, without decimals, of unlimited length. + - For example: `let count = 100;`, `let temperature = -10;` + - Output: `100`, `-10` +2. Floating-Point Numbers: + - A floating-point number is a number with a decimal point or an exponent. + - For example: `let price = 99.99;`, `let pi = 3.14;` + - Output: `99.99`, `3.14` +3. NaN (Not a Number): + - `NaN` is a special value that represents "Not-a-Number". + - It indicates that a value is not a legal number. + - For example: `let result = 100 / "Apple";` + - Output: `NaN` +4. Infinity: + - `Infinity` is a special value that represents positive infinity. + - It is displayed when a number exceeds the upper limit of the floating-point numbers. + - For example: `let max = Number.MAX_VALUE;`, `let infinity = max * 2;` + - Output: `Infinity` +5. BigInt: + - The `bigint` data type is used to represent whole numbers larger than `2^53 - 1`. + - It is a new feature in JavaScript and is not supported in all browsers. + - For example: `let value = 9007199254740991n;` + - Output: `9007199254740991n` +::: + +## Conclusion + +In this article, you learned about the number data type in JavaScript and how to use it. You also learned about integers, floating-point numbers, `NaN`, `Infinity`, and `BigInt`. You can use these data types to represent numeric values in JavaScript. \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/strings-js.md b/docs/javascript/datatypes/primitive-data-types/strings-js.md new file mode 100644 index 000000000..f0d3622f9 --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/strings-js.md @@ -0,0 +1,203 @@ +--- +id: string-datatypes-in-javascript +title: String Data Types in JavaScript +sidebar_label: String +sidebar_position: 2 +tags: [JavaScript, Data Types, Primitive Data Types, String, 'String Data Type', 'String Length', 'String Methods', 'Template Literals', 'Escape Characters', 'String Concatenation', 'String Interpolation'] +description: What is the string data type in JavaScript? Learn about the string data type in JavaScript, including how to create a string, escape characters, string length, string methods, and template literals. +--- + +Strings are a primitive data type in JavaScript. They are used to represent text. JavaScript uses the `String` object to represent a sequence of characters. + +```mermaid +graph TD; + A(String)-->|Text| B("Hello World!"); + A(String)-->|Text| C("John Doe"); +``` + +## What is a String in JavaScript? + +In JavaScript, strings are used to represent text. JavaScript uses the `String` object to represent a sequence of characters. + +## How to Create a String in JavaScript? + +You can create a string in JavaScript using the following syntax: + +```js title="Creating a String in JavaScript" +let name = "Ajay Dhangar"; // Double quotes +let message = 'Hello World!'; // Single quotes +``` + +In the above example, `name` and `message` are strings. + +## Double Quotes vs. Single Quotes + +| No. | Double Quotes | Single Quotes | +| --- | -------------- | -------------- | +| 1. | "Hello World!" | 'Hello World!' | +| 2. | "John Doe" | 'John Doe' | + +## Escape Characters + +In JavaScript, you can use the backslash (`\`) to escape characters in a string. The following table lists the escape characters in JavaScript: + +| Escape Character | Description | +| ---------------- | ---------------------------------------- | +| `\'` | Single quote | +| `\"` | Double quote | +| `\\` | Backslash | +| `\n` | New line | +| `\r` | Carriage return | +| `\t` | Tab | +| `\b` | Backspace | +| `\f` | Form feed | +| `\v` | Vertical tab | + +## String Length + +In JavaScript, you can use the `length` property to get the length of a string. For example: + +```js title="String Length" +let name = "John Doe"; + +console.log(name.length); // Output: 8 +``` + +In the above example, the length of the string `name` is `8`. + +## String Methods + +JavaScript provides several methods to work with strings. Some of the most commonly used string methods are: + +- `concat()`: Concatenates two or more strings. For example: + + ```js title="concat()" + let firstName = "John"; + let lastName = "Doe"; + + let fullName = firstName.concat(" ", lastName); + console.log(fullName); // Output: John Doe + ``` + +- `toUpperCase()`: Converts a string to uppercase. For example: + + ```js title="toUpperCase()" + let name = "John Doe"; + + console.log(name.toUpperCase()); // Output: JOHN DOE + ``` + +- `toLowerCase()`: Converts a string to lowercase. For example: + + ```js title="toLowerCase()" + let name = "John Doe"; + + console.log(name.toLowerCase()); // Output: john doe + ``` + +- `charAt()`: Returns the character at a specified index. For example: + + ```js title="charAt()" + let name = "John Doe"; + + console.log(name.charAt(0)); // Output: J + ``` + +- `indexOf()`: Returns the index of the first occurrence of a specified value. For example: + + ```js title="indexOf()" + let name = "John Doe"; + + console.log(name.indexOf("Doe")); // Output: 5 + ``` + +- `lastIndexOf()`: Returns the index of the last occurrence of a specified value. For example: + ```js title="lastIndexOf()" + let name = "John Doe"; + + console.log(name.lastIndexOf("Doe")); // Output: 5 + ``` + +- `includes()`: Returns `true` if a string contains a specified value, otherwise `false`. For example: + + ```js title="includes()" + let name = "John Doe"; + + console.log(name.includes("Doe")); // Output: true + ``` + +- `startsWith()`: Returns `true` if a string starts with a specified value, otherwise `false`. For example: + + ```js title="startsWith()" + let name = "John Doe"; + console.log(name.startsWith("John")); // Output: true + ``` + +- `endsWith()`: Returns `true` if a string ends with a specified value, otherwise `false`. For example: + + ```js title="endsWith()" + let name = "John Doe"; + console.log(name.endsWith("Doe")); // Output: true + ``` + +- `slice()`: Extracts a part of a string and returns a new string. For example: + + ```js title="slice()" + let name = "John Doe"; + console.log(name.slice(5)); // Output: Doe + ``` + +- `substring()`: Extracts a part of a string and returns a new string. For example: + + ```js title="substring()" + let name = "John Doe"; + console.log(name.substring(5)); // Output: Doe + ``` + +- `substr()`: Extracts a part of a string and returns a new string. For example: + + ```js title="substr()" + let name = "John Doe"; + console.log(name.substr(5)); // Output: Doe + ``` + +- `replace()`: Replaces a specified value with another value in a string. For example: + + ```js title="replace()" + let name = "John Doe"; + console.log(name.replace("Doe", "Smith")); // Output: John Smith + ``` + +- `split()`: Splits a string into an array of substrings. For example: + + ```js title="split()" + let name = "John Doe"; + console.log(name.split(" ")); // Output: ["John", "Doe"] + ``` + +- `trim()`: Removes whitespace from both ends of a string. For example: + + ```js title="trim()" + let name = " John Doe "; + console.log(name.trim()); // Output: John Doe + ``` + +## Template Literals + +Template literals are string literals that allow embedded expressions. You can use multi-line strings and string interpolation features with template literals. Template literals are enclosed by the backtick (\`) character. + +```js {2} title="Template Literals" +let name = "John Doe"; +let message = `Hello, ${name}!`; // String interpolation using template literals +console.log(message); // Output: Hello, John Doe! +``` + +In the above example, the `${name}` is a placeholder that is replaced by the value of the `name` variable. + +:::info 📝 Note +Template literals are a new feature in ECMAScript 6 (ES6). +::: + +## Conclusion + +In this tutorial, you learned about the string data type in JavaScript and how to use it. You also learned about escape characters, string length, and string methods. You can use strings to represent text in JavaScript. diff --git a/docs/javascript/datatypes/primitive-data-types/symbol-js.md b/docs/javascript/datatypes/primitive-data-types/symbol-js.md new file mode 100644 index 000000000..fd435fde2 --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/symbol-js.md @@ -0,0 +1,77 @@ +--- +id: symbol-in-javascript +title: Symbol Data Types in JavaScript +sidebar_label: Symbol +sidebar_position: 7 +tags: [JavaScript, Data Types, Primitive Data Types, Symbol, 'Symbol in JavaScript', 'Symbol data type'] +description: What is the symbol data type in JavaScript? Learn about the symbol data type and how to create symbols in JavaScript. +--- + +`Symbol` is a primitive data type in JavaScript. It represents a unique and immutable value. It is used to create unique identifiers for object properties. + +```mermaid +graph LR; + A(Symbol)-->|Represents a unique and immutable value| B(SymbolValue); +``` + +## What is Symbol in JavaScript? + +In JavaScript, `Symbol` is a primitive data type that represents a unique and immutable value. It is used to create unique identifiers for object properties. + +## How to Create Symbols in JavaScript? + +You can create `Symbol` in JavaScript using the following syntax: + +```js title="Creating Symbols in JavaScript" +let id = Symbol('id'); + +console.log(id); // Output: Symbol(id) +``` + +In the above example, the variable `id` is assigned the value `Symbol('id')`. The string `'id'` is used as a description for the symbol, which can be useful for debugging. + +## Checking for Symbols in JavaScript + +You can check if a variable is a `Symbol` using the `typeof` operator. + +```js title="Checking for Symbols in JavaScript" +let id = Symbol('id'); + +console.log(typeof id); // Output: symbol +``` + +In the above example, the `typeof` operator returns `symbol` for the `id` variable, indicating that it is a `Symbol`. + +## Symbol Descriptions + +When creating a `Symbol`, you can provide an optional description that can be used for debugging purposes. + +```js title="Symbol Descriptions" +let id = Symbol('id'); + +console.log(id.description); // Output: id +``` + +In the above example, the `description` property of the `id` symbol returns the string `'id'`, which was provided as a description when creating the symbol. + +## Unique Identifiers + +Symbols are unique and immutable. Even if you create multiple symbols with the same description, they are different values. + +```js title="Unique Identifiers" +let id1 = Symbol('id'); + +let id2 = Symbol('id'); + +console.log(id1 === id2); // Output: false +``` + +In the above example, `id1` and `id2` are both symbols with the same description, but they are different values. + +:::info 📝Note +The description of a `Symbol` is not used in any operations. It is purely a human-readable label for debugging purposes. +::: + +## Conclusion + +In this tutorial, you learned about the `Symbol` data type in JavaScript and how to create symbols. You also learned how to check for symbols and use symbol descriptions. Symbols are useful for creating unique identifiers for object properties and are often used in advanced JavaScript programming. \ No newline at end of file diff --git a/docs/javascript/datatypes/primitive-data-types/undefined-js.md b/docs/javascript/datatypes/primitive-data-types/undefined-js.md new file mode 100644 index 000000000..21b42af61 --- /dev/null +++ b/docs/javascript/datatypes/primitive-data-types/undefined-js.md @@ -0,0 +1,182 @@ +--- +id: undefined-in-javascript +title: Undefined Data Types in JavaScript +sidebar_label: Undefined +sidebar_position: 4 +tags: [JavaScript, Data Types, Primitive Data Types, Undefined] +description: What is the undefined data type in JavaScript? Learn about the undefined data type and how to create undefined in JavaScript. +--- + + +`undefined` is a primitive data type in JavaScript. It represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +```mermaid +flowchart TD + subgraph Undefined Data Types + Undefined -->|Represents the absence of a value| UndefinedValue + end + + classDef undefinedClass fill:#f9f,stroke:#333,stroke-width:2px; + class UndefinedValue undefinedClass; + + classDef highlight fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class UndefinedValue highlight; + + classDef visibleClass fill:#fff,stroke:#333,stroke-width:2px; + class UndefinedValue visibleClass; + + classDef arrowClass fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class arrow arrowClass; + + classDef hidden invisible; + + class UndefinedValue,undefinedClass visibleClass; + + UndefinedValue -->|Initialize a variable without assigning a value| Value; + Value -->|Use the variable without assigning a value| DisplayValue; + DisplayValue -->|Displays 'undefined'| DisplayUndefined; + DisplayUndefined -->|Output to the console or other output devices| OutputUndefined; + +``` + +## What is Undefined in JavaScript? + +In JavaScript, `undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +## How to Create Undefined in JavaScript? + +You can create `undefined` in JavaScript using the following syntax: + +```js title="Creating Undefined in JavaScript" +let data; + +console.log(data); // Output: undefined +``` + +In the above example, the variable `data` is declared but not assigned a value. When you log the value of `data`, it will output `undefined`. + +## Checking for Undefined in JavaScript + +You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. + +### Using the `typeof` Operator + +You can use the `typeof` operator to check if a variable is `undefined`: + +```js title="Using the typeof Operator to Check for Undefined" +let data; + +console.log(typeof data === 'undefined'); // Output: true +``` + +### Comparing to `undefined` + +You can also compare a variable to `undefined` to check if it is `undefined`: + +```js title="Comparing to Undefined to Check for Undefined" +let data; + +console.log(data === undefined); // Output: true +``` + +## Undefined vs. Null + +`undefined` and `null` are both used to represent the absence of a value in JavaScript. However, they are not the same. + +`undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +`null` is an object that represents the absence of a value. It is often used to explicitly set a variable to have no value. + +:::info 📝 Note +In JavaScript, `null` is of type `object`. This is a bug in the language that has been kept for compatibility reasons. + +You can check if a variable is `null` using the `typeof` operator or by comparing the variable to `null`. + +**1. Difference bitween `undefined` and `null`** + +```mermaid +flowchart TD + subgraph Undefined vs. Null + Undefined -->|Represents the absence of a value| UndefinedValue + Null -->|Represents the absence of a value| NullValue + end + + classDef undefinedClass fill:#f9f,stroke:#333,stroke-width:2px; + class UndefinedValue undefinedClass; + + classDef nullClass fill:#f9f,stroke:#333,stroke-width:2px; + class NullValue nullClass; + + classDef highlight fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class UndefinedValue highlight; + class NullValue highlight; + + classDef visibleClass fill:#fff,stroke:#333,stroke-width:2px; + class UndefinedValue,NullValue visibleClass; + + classDef arrowClass fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class arrow arrowClass; + + classDef hidden invisible; + + class UndefinedValue,undefinedClass visibleClass; + class NullValue,nullClass visibleClass; + + UndefinedValue -->|Initialize a variable without assigning a value| Value; + Value -->|Use the variable without assigning a value| DisplayValue; + DisplayValue -->|Displays 'undefined'| DisplayUndefined; + DisplayUndefined -->|Output to the console or other output devices| OutputUndefined; + + NullValue -->|Initialize a variable with a null value| Value; + Value -->|Use the variable with a null value| DisplayValue; + DisplayValue -->|Displays 'null'| DisplayNull; + DisplayNull -->|Output to the console or other output devices| OutputNull; +``` +::: + +:::tip tips and tricks +**Why use undefined?** + +`undefined` is used to represent the absence of a value. It is often used to check if a variable has been assigned a value or not. For example, you can use `undefined` to check if a function argument has been passed or not. + +**What means undefined?** + +`undefined` means that a variable has been declared, but has not been assigned a value. It is a primitive data type that represents an undefined value. + +**Why JavaScript has undefined?** + +JavaScript has `undefined` to represent the absence of a value. It is often used to check if a variable has been assigned a value or not. + +**Assume that a variable is undefined?** + +If a variable is `undefined`, it means that it has been declared, but has not been assigned a value. You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. + +**How to play with undefined?** + +You can create `undefined` in JavaScript by declaring a variable without assigning a value to it. You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. + +for example: + +```js title="Creating Undefined in JavaScript" +let data; + +console.log(data); // Output: undefined +``` + +```js title="Using the typeof Operator to Check for Undefined" +let data; + +console.log(typeof data === 'undefined'); // Output: true +``` + +```js title="Comparing to Undefined to Check for Undefined" +let data; + +console.log(data === undefined); // Output: true +``` +::: + + +## Conclusion + +In JavaScript, `undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. You can create `undefined` in JavaScript by declaring a variable without assigning a value to it. You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. \ No newline at end of file diff --git a/docs/javascript/debugging-js.md b/docs/javascript/debugging-js.md new file mode 100644 index 000000000..c161fce7c --- /dev/null +++ b/docs/javascript/debugging-js.md @@ -0,0 +1,162 @@ +--- +id: debugging-js +title: Debugging in JavaScript +sidebar_label: Debugging +sidebar_position: 39 +tags: + [ + JavaScript, + Debugging, + Console, + Breakpoints, + Sources, + Call Stack, + Watch, + Scope, + Network, + Performance, + Memory, + Profiling, + Code Coverage, + Chrome DevTools, + Error Messages, + Code Review, + Debugger Statement, + Debugging Techniques, + ] +description: "In this tutorial, you will learn how to debug JavaScript code in the browser using the Chrome DevTools. We will cover the basics of debugging, including breakpoints, console, sources, call stack, watch, scope, network, performance, memory, profiling, and code coverage." +--- + +Debugging is the process of finding and fixing errors in your code. It is an essential skill for developers to master, as it helps you identify and resolve issues quickly and efficiently. In this tutorial, you will learn how to debug JavaScript code in the browser using the Chrome DevTools. We will cover the basics of debugging, including breakpoints, console, sources, call stack, watch, scope, network, performance, memory, profiling, and code coverage. + +## Common Debugging Techniques + +Here are some common debugging techniques that you can use to debug JavaScript code: + +- **Breakpoints**: Pause the execution of your code at a specific line to inspect the state of your application. +- **Console**: Log messages to the console to track the flow of your code and inspect variables. +- **Sources**: View and edit the source code of your application. +- **Call Stack**: View the sequence of function calls that led to the current point in your code. +- **Watch**: Monitor the value of variables in real-time. +- **Scope**: Inspect the variables in the current scope. +- **Network**: Monitor network requests made by your application. +- **Performance**: Analyze the performance of your application. +- **Memory**: Inspect the memory usage of your application. +- **Profiling**: Profile the performance of your application. +- **Code Coverage**: Measure how much of your code is executed during a test. +- **Debugger Statement**: Use the `debugger` statement to pause the execution of your code. +- **Error Messages**: Read error messages in the console to identify issues in your code. +- **Code Review**: Review your code with a colleague to get a fresh perspective. + +## Debugging with Chrome DevTools + +Chrome DevTools is a set of web developer tools built into the Google Chrome browser. It provides a rich set of debugging tools that you can use to inspect and debug your web applications. To open Chrome DevTools, right-click on a web page and select "Inspect" or press `Ctrl+Shift+I` (Windows/Linux) or `Cmd+Option+I` (Mac). + +### Breakpoints + +Breakpoints allow you to pause the execution of your code at a specific line to inspect the state of your application. To set a breakpoint, click on the line number in the source code panel. When the code reaches the breakpoint, it will pause, and you can inspect the variables and step through the code using the controls in the debugger. + +![Breakpoints in Chrome DevTools](./img/breakpoints.gif) + +### Console + +The console is a powerful tool for logging messages to track the flow of your code and inspect variables. You can log messages using `console.log()`, `console.error()`, `console.warn()`, `console.info()`, and `console.debug()`. You can also evaluate expressions in the console and interact with the page using JavaScript. + +```javascript title="Console Logging" +console.log("Hello, World!"); +console.error("An error occurred!"); +console.warn("Warning: This is a warning!"); +console.info("Information: This is an information message!"); +console.debug("Debug: This is a debug message!"); +``` + +### Sources + +The sources panel allows you to view and edit the source code of your application. You can set breakpoints, step through the code, and inspect variables in the debugger. You can also search for files, navigate the call stack, and view the network requests made by your application. + +![Sources in Chrome DevTools](./img/source.gif) + +### Call Stack + +The call stack panel shows the sequence of function calls that led to the current point in your code. It helps you understand the flow of your code and identify where an error occurred. You can navigate the call stack, inspect the variables in each function, and step through the code using the controls in the debugger. + +![Call Stack in Chrome DevTools](./img/call-stack.gif) + +### Watch + +The watch panel allows you to monitor the value of variables in real-time. You can add variables to the watch list and see their values update as you step through the code. This is useful for tracking the state of your application and identifying issues in your code. + +### Scope + +The scope panel allows you to inspect the variables in the current scope. You can view the local, closure, and global variables, as well as the `this` context. This helps you understand the state of your application and debug issues related to variable scoping. + +### Network + +The network panel allows you to monitor the network requests made by your application. You can view the request and response headers, payloads, and timing information. This helps you identify performance issues, debug network-related errors, and optimize the performance of your application. + +### Performance + +The performance panel allows you to analyze the performance of your application. You can record performance profiles, analyze CPU and memory usage, and identify performance bottlenecks. This helps you optimize the performance of your application and deliver a better user experience. + +### Memory + +The memory panel allows you to inspect the memory usage of your application. You can take heap snapshots, analyze memory allocations, and identify memory leaks. This helps you optimize the memory usage of your application and prevent memory-related issues. + +### Profiling + +The profiling panel allows you to profile the performance of your application. You can record CPU profiles, analyze JavaScript execution, and identify performance bottlenecks. This helps you optimize the performance of your application and deliver a better user experience. + +### Code Coverage + +The code coverage panel allows you to measure how much of your code is executed during a test. You can record code coverage profiles, analyze the coverage of your code, and identify unused code. This helps you ensure that your tests cover all parts of your code and identify areas for improvement. + +### Debugger Statement + +The `debugger` statement allows you to pause the execution of your code at a specific point. When the code reaches the `debugger` statement, it will pause, and you can inspect the variables and step through the code using the controls in the debugger. This is useful for debugging complex issues and identifying errors in your code. + +```javascript title="Debugger Statement" +function add(a, b) { + debugger; + return a + b; +} + +add(1, 2); // The code will pause at the debugger statement +``` + +### Error Messages + +Error messages in the console provide valuable information about issues in your code. They help you identify syntax errors, runtime errors, and logic errors. By reading error messages, you can quickly pinpoint the source of the issue and fix it. + +### Code Review + +Code review is a collaborative process where you review your code with a colleague to get a fresh perspective. By sharing your code with others, you can identify issues, improve the quality of your code, and learn new techniques. Code review helps you catch bugs early, improve code readability, and foster a culture of collaboration. + +:::note +Debugging is an iterative process that requires patience and persistence. By mastering the debugging techniques and tools available to you, you can identify and fix errors in your code quickly and efficiently. +::: + +:::tip +When debugging, start with the simplest possible case and gradually add complexity. Break down the problem into smaller parts, test each part individually, and identify the source of the issue. By following a systematic approach, you can debug your code effectively and efficiently. +::: + +:::tip Major Browsers' Debugging Tools + +- **Chrome DevTools**: Built into Google Chrome, it provides a rich set of debugging tools for web developers. +- **Firefox Developer Tools**: Built into Mozilla Firefox, it provides a set of debugging tools for web developers. +- **Safari Web Inspector**: Built into Apple Safari, it provides a set of debugging tools for web developers. +- **Edge DevTools**: Built into Microsoft Edge, it provides a set of debugging tools for web developers. +- **Opera Developer Tools**: Built into Opera, it provides a set of debugging tools for web developers. +- **Internet Explorer Developer Tools**: Built into Internet Explorer, it provides a set of debugging tools for web developers. +- **Brave DevTools**: Built into Brave, it provides a set of debugging tools for web developers. +- **Vivaldi DevTools**: Built into Vivaldi, it provides a set of debugging tools for web developers. +- **Tor Browser DevTools**: Built into Tor Browser, it provides a set of debugging tools for web developers. +- **UC Browser DevTools**: Built into UC Browser, it provides a set of debugging tools for web developers. +- **Yandex Browser DevTools**: Built into Yandex Browser, it provides a set of debugging tools for web developers. +- **Samsung Internet DevTools**: Built into Samsung Internet, it provides a set of debugging tools for web developers. +- **Puffin Browser DevTools**: Built into Puffin Browser, it provides a set of debugging tools for web developers. + +::: + +## Conclusion + +In this tutorial, you learned how to debug JavaScript code in the browser using the Chrome DevTools. We covered the basics of debugging, including breakpoints, console, sources, call stack, watch, scope, network, performance, memory, profiling, and code coverage. By mastering these debugging techniques, you can identify and fix errors in your code quickly and efficiently. Happy debugging! diff --git a/docs/javascript/errors.md b/docs/javascript/errors.md new file mode 100644 index 000000000..f6a036635 --- /dev/null +++ b/docs/javascript/errors.md @@ -0,0 +1,178 @@ +--- +id: errors-in-javascript +title: Errors in JavaScript +sidebar_label: Errors +sidebar_position: 31 +tags: [JavaScript, Errors, Try Catch Finally, Error Object, Throw Error, Error Handling, DOMException, AggregateError, TypeError, RangeError, URIError, EvalError, InternalError, Error, AbortError, NotAllowedError, NotFoundError, SecurityError, try, catch, finally] +description: "In this tutorial, we will learn about errors in JavaScript. Errors are unexpected events that occur during the execution of a program. We will see the different types of errors in JavaScript and how to handle them using try...catch...finally blocks." +--- + +In JavaScript, an error is an unexpected event that occurs during the execution of a program. Errors can occur due to various reasons such as incorrect syntax, logical errors, or runtime errors. When an error occurs, JavaScript stops the execution of the program and generates an error message. + +JavaScript provides a built-in `Error` object that represents an error. The `Error` object contains information about the error such as the error message and the stack trace. The stack trace is a list of function calls that were in progress when the error occurred. + +There are several types of errors in JavaScript. Some common types of errors are: + +1. **SyntaxError**: This error occurs when there is a syntax error in the code. For example, missing parentheses, missing semicolons, or misspelled keywords. +2. **ReferenceError**: This error occurs when a variable or function is used without being declared. +3. **TypeError**: This error occurs when a value is not of the expected type. For example, trying to call a non-function value. +4. **RangeError**: This error occurs when a value is not within the expected range. For example, using an invalid index in an array. +5. **URIError**: This error occurs when a global URI handling function is used in a wrong way. +6. **EvalError**: This error occurs when an error occurs during the execution of `eval()` function. +7. **InternalError**: This error occurs when an internal error in the JavaScript engine occurs. +8. **Error**: This is the base class for all errors in JavaScript. +9. **AggregateError**: This error is a subclass of `Error` that represents an error when multiple errors need to be wrapped in a single error. +10. **DOMException**: This error is a subclass of `Error` that represents an error in the DOM. +11. **AbortError**: This error is a subclass of `DOMException` that represents an error when an operation is aborted. +12. **NotAllowedError**: This error is a subclass of `DOMException` that represents an error when an operation is not allowed. +13. **NotFoundError**: This error is a subclass of `DOMException` that represents an error when a requested resource is not found. +14. **SecurityError**: This error is a subclass of `DOMException` that represents a security error. +15. **TypeError**: This error is a subclass of `Error` that represents a type error. +16. **RangeError**: This error is a subclass of `Error` that represents a range error. + +## Handling Errors in JavaScript + +To handle errors in JavaScript, you can use the `try...catch...finally` statement. The `try` block contains the code that may throw an error. The `catch` block contains the code to handle the error. The `finally` block contains the code that will be executed regardless of whether an error occurs or not. + +Here is the syntax of the `try...catch...finally` statement: + +```javascript title="app.js" +try { + // Code that may throw an error +} catch (error) { + // Code to handle the error +} finally { + // Code that will be executed regardless of whether an error occurs or not +} +``` + +Let's see an example of handling errors in JavaScript using the `try...catch...finally` statement: + +```javascript title="app.js" +try { + let x = 10; + let y = 0; + let result = x / y; // Division by zero + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} finally { + console.log("Finally block executed"); +} +``` + +In this example, we are trying to divide a number by zero, which will throw a `TypeError` (division by zero). We are handling this error using the `try...catch...finally` statement. + +When you run the above code, you will get the following output: + +```bash title="Output" +An error occurred: Division by zero +Finally block executed +``` + +In the `catch` block, we are logging the error message using `error.message`. In the `finally` block, we are logging a message that will be executed regardless of whether an error occurs or not. + +That's all for handling errors in JavaScript. You can use the `try...catch...finally` statement to handle errors and prevent your program from crashing when an error occurs. + + +:::tip 🧠 Knowledge Check +1. Which of the following is not a type of error in JavaScript? + + A) SyntaxError
+ B) ReferenceError
+ C) TypeError
+ D) NullError + +
+ Answer +

+ + **Answer:** D) NullError + + `NullError` is not a type of error in JavaScript. The correct type of error is `TypeError`. + +

+
+ +2. Which block of code will be executed regardless of whether an error occurs or not? + + A) `try` block
+ B) `catch` block
+ C) `finally` block
+ D) None of the above + +
+ Answer +

+ + **Answer:** C) `finally` block + + The `finally` block will be executed regardless of whether an error occurs or not. + +

+
+ +::: + +:::info 📚 Learn More: + +**Throwing Errors in JavaScript:** + +You can throw an error in JavaScript using the `throw` statement. The `throw` statement allows you to create a custom error and throw it. Here is an example of throwing an error in JavaScript: + +```javascript title="app.js" +try { + let x = 10; + let y = 0; + if (y === 0) { + throw new Error("Division by zero"); + } + let result = x / y; + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} finally { + console.log("Finally block executed"); +} +``` + +In this example, we are throwing a custom error using the `throw` statement when the value of `y` is zero. The error message is "Division by zero". + +When you run the above code, you will get the following output: + +```bash title="Output" +An error occurred: Division by zero +Finally block executed +``` + +In the `catch` block, we are logging the error message using `error.message`. In the `finally` block, we are logging a message that will be executed regardless of whether an error occurs or not. + +**Error Object in JavaScript:** + +The `Error` object in JavaScript has two properties: `name` and `message`. The `name` property contains the name of the error (e.g., "SyntaxError", "ReferenceError", "TypeError"), and the `message` property contains the error message. + +Here is an example of creating a custom error using the `Error` object: + +```javascript title="app.js" +try { + throw new Error("Custom Error"); +} catch (error) { + console.log("An error occurred: " + error.message); +} +``` + +In this example, we are creating a custom error using the `Error` object with the message "Custom Error". + +When you run the above code, you will get the following output: + +```bash title="Output" +An error occurred: Custom Error +``` + +That's all for throwing errors in JavaScript. You can use the `throw` statement to throw custom errors and handle them using the `try...catch...finally` statement. + +::: + +## Summary + +In this tutorial, we learned about errors in JavaScript. Errors are unexpected events that occur during the execution of a program. We saw the different types of errors in JavaScript and how to handle them using the `try...catch...finally` statement. We also saw an example of handling errors in JavaScript. \ No newline at end of file diff --git a/docs/javascript/events-js.md b/docs/javascript/events-js.md new file mode 100644 index 000000000..ba28c98c4 --- /dev/null +++ b/docs/javascript/events-js.md @@ -0,0 +1,325 @@ +--- +id: events-in-javascript +title: Events in JavaScript +sidebar_label: Events +sidebar_position: 12 +tags: [JavaScript, Events, DOM, EventListener, EventObject, EventPropagation, PreventDefault, StopPropagation, EventTypes, ClickEvent, MouseoverEvent, MouseoutEvent, ChangeEvent, SubmitEvent, EventCapturePhase, EventBubblingPhase, EventTarget, EventListener, CallbackFunction, EventObject, EventProperties, UIEvents, MouseEvents, KeyboardEvents, FormEvents, FocusEvents, InputEvents, WheelEvents, TouchEvents, CustomEvents, AddEventListener, Options, Capture, Once, Passive, HandleEvent, EventPropagation, EventBubbling, EventCapture, EventPhase, EventTypes, EventListener, EventObject, EventProperties] +description: What is the event in JavaScript? How to handle events in JavaScript? Learn about different types of events, event listeners, event objects, event propagation, and how to prevent default behavior and stop event propagation. +--- + +An event is a signal that something has happened. For example, when a user clicks a button, the click event is triggered. Events are a part of the Document Object Model (DOM) and are used to interact with the user. + +```mermaid +graph LR +A[User] -->|Clicks Button| B[Event] +B -->|Triggers| C[Event Listener] +C -->|Executes| D[Function] +``` + +In the above diagram, when a user clicks a button, the click event is triggered. The event listener listens for the click event and executes the function when the event occurs. + +## Event Types + +There are many types of events in JavaScript. Some of the most common events are: + +### 1. `click` Event + +```html title="index.html" + + + + Click Event + + + + + + +``` + + + + + +### 2. `mouseover` Event + +```html title="index.html" + + + + Mouseover Event + + + + + + +``` + + + + + +### 3. `mouseout` Event + +```html title="index.html" + + + + Mouseout Event + + + + + + +``` + + + + + +### 3. `change` Event + +```html title="index.html" + + + + Change Event + + + + + + +``` + + + alert("Input Changed")} /> + + +### 4. `submit` Event + +```html title="index.html" + + + + Submit Event + + +
+ + + + + + +``` + + +
{e.preventDefault(); alert("Form Submitted")}}> + + {' '} + + +
+ +## Event Listener + +An event listener is a function that listens for a specific event to occur. It is used to handle the event when it occurs. The `addEventListener` method is used to add an event listener to an element. + +```js title="index.js" +document.getElementById("button").addEventListener("click", function () { + alert("Button Clicked"); +}); +``` + +In the above example, the `click` event listener is added to the button element. When the button is clicked, the function is executed. + +## Event Object + +The event object is passed to the event listener function as an argument. It contains information about the event that occurred. For example, the `target` property of the event object contains a reference to the element that triggered the event. + +```js title="index.js" +document.getElementById("button").addEventListener("click", function (event) { + alert("Button Clicked"); + console.log(event.target); +}); +``` + +In the above example, the `target` property of the event object is logged to the console. It contains a reference to the button element that triggered the event. + +## Event Propagation + +Event propagation is the process of event bubbling and event capturing. When an event occurs on an element, it first runs the event listeners on the element itself, then on its parent, and so on, until it reaches the top of the document. This is called event bubbling. Event capturing is the opposite, where the event listeners on the parent element are run first, then on the element itself. + +```html title="index.html" + + + + Event Propagation + + +
+
Click Me
+
+ + + +``` + + +
alert("Outer Div Clicked")}> +
alert("Inner Div Clicked")}>Click Me
+
+
+ +In the above example, when the inner div is clicked, the event bubbles up to the outer div, and the event listener on the outer div is also triggered. + +## Prevent Default + +The `preventDefault` method is used to prevent the default behavior of an event. For example, it can be used to prevent a form from being submitted or a link from being followed. + +```html title="index.html" + + + + Prevent Default + + + Click Me + + + +``` + + + {e.preventDefault(); alert("Link Clicked")}}>Click Me + + +In the above example, the `preventDefault` method is used to prevent the link from being followed when it is clicked. + +## Stop Propagation + +The `stopPropagation` method is used to stop the event from propagating to the parent elements. It prevents the event from bubbling up the DOM tree. + +```html title="index.html" + + + + Stop Propagation + + +
+
Click Me
+
+ + + +``` + + +
alert("Outer Div Clicked")}> +
{e.stopPropagation(); alert("Inner Div Clicked")}}>Click Me
+
+
+ +In the above example, when the inner div is clicked, the event does not bubble up to the outer div because the `stopPropagation` method is used. + +:::info +The `stopPropagation` method only stops the event from propagating to the parent elements. It does not stop the default behavior of the event. +::: + +```mermaid +flowchart TD + subgraph "DOM" + A[Event Phase] --> B[Event Capture Phase] + B --> C[Target Element] + C --> D[Event Bubbling Phase] + D --> E[Event Propagation] + end + subgraph "Event" + E --> F[Event Types] + F --> G[UI Events] + F --> H[Mouse Events] + F --> I[Keyboard Events] + F --> J[Form Events] + F --> K[Focus Events] + F --> L[Input Events] + F --> M[Wheel Events] + F --> N[Touch Events] + F --> O[Custom Events] + end + subgraph "Event Target" + C --> P[Target Element] + P --> Q[Parent Element] + Q --> R[Ancestor Elements] + end + subgraph "Event Listener" + S[AddEventListener] --> T[Options] + T --> U[Capture] + T --> V[Once] + T --> W[Passive] + end + subgraph "Callback Function" + X[Handle Event] --> Y[Event Object] + Y --> Z[Event Properties] + end +``` + +In the above diagram, the event capture phase occurs first, followed by the target element, and then the event bubbling phase. The event object contains information about the event, and the event listener is used to handle the event when it occurs. + +## Summary + +In this article, we learned about events in JavaScript. We learned about different types of events, event listeners, event objects, event propagation, and how to prevent default behavior and stop event propagation. Events are an important part of web development and are used to create interactive user interfaces. diff --git a/docs/javascript/for-in-loop.md b/docs/javascript/for-in-loop.md new file mode 100644 index 000000000..0672c8fd3 --- /dev/null +++ b/docs/javascript/for-in-loop.md @@ -0,0 +1,155 @@ +--- +id: for-in-loop-in-javascript +title: For In Loop in JavaScript +sidebar_label: For...In +sidebar_position: 22 +tags: + [ + JavaScript, + For In Loop, + Loop, + Iteration, + Control, + Flow, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the for...in loop in JavaScript. We will learn how to use the for...in loop to iterate over the properties of an object in JavaScript." +--- + +In JavaScript, the `for...in` loop is used to iterate over the properties of an object. It is often used when you want to perform an action on each property of an object. + +## Syntax + +The syntax of the `for...in` loop is as follows: + +```js title="app.js" +for (variable in object) { + // code to be executed +} +``` + +- The `for...in` loop starts with the `for` keyword followed by parentheses. +- Inside the parentheses, you need to specify a `variable` to hold the property name and the `object` over which you want to iterate. +- The `variable` will be assigned the property name of the object on each iteration. +- The code inside the loop will be executed for each property of the object. +- The loop will iterate over all enumerable properties of the object, including inherited properties from the object's prototype chain. +- The order of iteration is not guaranteed and may vary between different JavaScript engines. +- It is recommended to use the `hasOwnProperty` method to check if the property is a direct property of the object and not inherited from its prototype chain. +- The `for...in` loop should not be used to iterate over arrays, as it may produce unexpected results due to the iteration of array indices and inherited properties. +- The `for...in` loop should be used only for objects. + +## Example + +The following example demonstrates how to use the `for...in` loop to iterate over the properties of an object: + +```js title="app.js" +const person = { + name: "John", + age: 23, + // Method + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}; + +for (let property in person) { + console.log(property + ": " + person[property]); +} +``` + +In this example, the `for...in` loop iterates over the properties of the `person` object. On each iteration, the `property` variable is assigned the name of the property, and the code inside the loop logs the property name and its value to the console. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); +} +``` + +In each iteration, the property name and its value are printed to the console. + +## Using `hasOwnProperty` Method + +To check if the property is a direct property of the object and not inherited from its prototype chain, you can use the `hasOwnProperty` method. Here's an example: + +```js title="app.js" +const person = { + name: "John", + age: 23, + // Method + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}; + +for (let property in person) { + if (person.hasOwnProperty(property)) { + console.log(property + ": " + person[property]); + } +} +``` + +In this example, the `hasOwnProperty` method is used to check if the property is a direct property of the `person` object. If it is, the property name and its value are printed to the console. + +:::tip tips & tricks +The `hasOwnProperty` method returns `true` if the property is a direct property of the object, otherwise it returns `false`. + +The `for...in` loop should be used with caution, as it iterates over all enumerable properties of the object, including inherited properties from the object's prototype chain. It is recommended to use the `hasOwnProperty` method to check if the property is a direct property of the object. + +The `for...in` loop should not be used to iterate over arrays, as it may produce unexpected results due to the iteration of array indices and inherited properties. + +The `for...in` loop should be used only for objects. + +::: + +:::info 📚 Learn Extra + +## Array.forEach Method + +If you want to iterate over the elements of an array, you can use the `forEach` method. The `forEach` method is a more appropriate way to iterate over the elements of an array, as it provides a concise and readable syntax for performing actions on each element of the array. + +Here's an example that demonstrates the use of the `forEach` method to iterate over the elements of an array: + +```js title="app.js" +const numbers = [1, 2, 3, 4, 5]; + +numbers.forEach(function (number) { + console.log(number); +}); +``` + +In this example, the `forEach` method iterates over the elements of the `numbers` array and executes the provided function for each element. + +The `forEach` method is a convenient and concise way to iterate over the elements of an array in JavaScript. + +## Array.forEach Method vs. for...of Loop vs. for...in Loop Comparison + +| No. | forEach Method | for...of Loop | for...in Loop | +| :-: | :-------------------------------------------------------- | :-------------------------------------------------------- | :------------------------------------------------ | +| 1. | Iterates over the elements of an array. | Iterates over the elements of an iterable object. | Iterates over the properties of an object. | +| 2. | Provides a concise and readable syntax. | Provides a concise and readable syntax. | Provides a concise and readable syntax. | +| 3. | Should be used for arrays. | Should be used for iterable objects. | Should be used for objects. | +| 4. | Does not iterate over inherited properties. | Does not iterate over inherited properties. | Iterates over inherited properties. | +| 5. | Does not iterate over array indices. | Does not iterate over array indices. | Iterates over array indices. | +| 6. | Does not require a loop variable. | Requires a loop variable. | Requires a loop variable. | +| 7. | Does not require an explicit check for direct properties. | Does not require an explicit check for direct properties. | Requires an explicit check for direct properties. | + +::: + +## Summary + +In this tutorial, we learned about the `for...in` loop in JavaScript. We learned how to use the `for...in` loop to iterate over the properties of an object. We also learned about using the `hasOwnProperty` method to check if the property is a direct property of the object and not inherited from its prototype chain. diff --git a/docs/javascript/for-loop.md b/docs/javascript/for-loop.md new file mode 100644 index 000000000..009e783c5 --- /dev/null +++ b/docs/javascript/for-loop.md @@ -0,0 +1,145 @@ +--- +id: for-loop-in-javascript +title: For Loop in JavaScript +sidebar_label: For Loop +sidebar_position: 21 +tags: + [ + JavaScript, + For Loop, + Loop, + Iteration, + Control, + Flow, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the for loop in JavaScript. We will learn how to use the for loop to execute a block of code multiple times in JavaScript." +--- + +In JavaScript, the `for` loop is used to execute a block of code multiple times. It is often used when you know the number of iterations you want to perform. + +## Syntax + +The syntax of the `for` loop is as follows: + +```js title="app.js" +for (initialization; condition; increment / decrement) { + // code to be executed +} +``` + +- The `for` loop starts with the `for` keyword followed by parentheses. +- Inside the parentheses, you need to specify three expressions separated by semicolons: + - The `initialization` expression is executed only once before the loop starts. It is used to initialize the loop variable. + - The `condition` expression is evaluated before each iteration. If the condition is `true`, the code inside the loop is executed. If the condition is `false`, the loop terminates. + - The `increment/decrement` expression is executed at the end of each iteration. It is used to update the loop variable. + +## Flow Chart of the `for` Loop + +```mermaid +graph TD; + Start([Start]) --> Initialization; + Initialization -->|Condition| Condition{Condition}; + Condition -->|True| Action; + Action --> Increment[Increment/Decrement]; + Increment --> Condition{Condition}; + Condition -->|False| Stop; + Stop --> End([End]); +``` + +## Example + +The following example demonstrates how to use the `for` loop to print the numbers from 1 to 5: + +```js title="app.js" +for (let i = 1; i <= 5; i++) { + console.log(i); +} +``` + +In this example, the `for` loop initializes the loop variable `i` to `1`. It then checks if `i` is less than or equal to `5`. If the condition is `true`, it executes the code inside the loop and increments `i` by `1`. This process continues until `i` is no longer less than or equal to `5`. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +3 +4 +5 +``` + +In each iteration, the value of `i` is printed to the console. + +## Infinite `for` Loop + +If you omit the `condition` expression, the `for` loop will run indefinitely. This is known as an infinite loop. For example: + +```js title="app.js" +for (let i = 1; ; i++) { + console.log(i); +} +``` + +In this example, the `condition` expression is omitted, so the loop will run indefinitely. You can use the `break` statement to exit the loop when a certain condition is met. + +## Nested `for` Loop + +You can use a `for` loop inside another `for` loop. This is known as a nested `for` loop. For example: + +```js title="app.js" +for (let i = 1; i <= 3; i++) { + for (let j = 1; j <= 3; j++) { + console.log(`i = ${i}, j = ${j}`); + } +} +``` + +In this example, the outer `for` loop runs three times, and the inner `for` loop runs three times for each iteration of the outer loop. The output of the above example will be: + +```plaintext title="Output" +i = 1, j = 1 +i = 1, j = 2 +i = 1, j = 3 +i = 2, j = 1 +i = 2, j = 2 +i = 2, j = 3 +i = 3, j = 1 +i = 3, j = 2 +i = 3, j = 3 +``` + +In each iteration of the outer loop, the inner loop runs three times, printing the value of `i` and `j` to the console. + +:::info 📝 Note + +**1.** You can use the `break` statement to exit a `for` loop prematurely. You can also use the `continue` statement to skip the current iteration and continue with the next iteration. + +**2. Live Example** + +```js live +function printNumbers() { + return ( +
+ {(() => { + let numbers = []; + for (let i = 1; i <= 5; i++) { + numbers.push(

{i}

); + } + return numbers; + })()} +
+ ); +} +``` + +::: + +## Conclusion + +In this tutorial, you learned about the `for` loop in JavaScript and how to use it to execute a block of code multiple times. You also learned about infinite `for` loops and nested `for` loops. diff --git a/docs/javascript/for-of-loop.md b/docs/javascript/for-of-loop.md new file mode 100644 index 000000000..73af1b8f7 --- /dev/null +++ b/docs/javascript/for-of-loop.md @@ -0,0 +1,139 @@ +--- +id: for-of-loop-in-javascript +title: For Of Loop in JavaScript +sidebar_label: For...Of +sidebar_position: 23 +tags: + [ + JavaScript, + For Of Loop, + Loop, + Iteration, + Control, + Flow, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the for...of loop in JavaScript. We will learn how to use the for...of loop to iterate over the elements of an iterable object in JavaScript." +--- + +In JavaScript, the `for...of` loop is used to iterate over the elements of an iterable object. It is often used when you want to perform an action on each element of an array, set, map, string, or any other iterable object. + +## Syntax + +The syntax of the `for...of` loop is as follows: + +```js title="app.js" +for (variable of iterable) { + // code to be executed +} +``` + +- The `for...of` loop starts with the `for` keyword followed by parentheses. +- Inside the parentheses, you need to specify a `variable` to hold the element value and the `iterable` over which you want to iterate. +- The `variable` will be assigned the value of each element of the iterable on each iteration. +- The code inside the loop will be executed for each element of the iterable. +- The loop will iterate over the elements of the iterable object in the order of their insertion. +- The `for...of` loop can be used with arrays, sets, maps, strings, and any other iterable object. +- The `for...of` loop cannot be used to iterate over plain objects (i.e., objects created using `{}`) because they are not iterable. To iterate over the properties of an object, you should use the `for...in` loop or the `Object.keys`, `Object.values`, or `Object.entries` methods. +- The `for...of` loop can also be used with generator functions to iterate over the values generated by the generator. +- The `for...of` loop cannot be used to iterate over asynchronous iterators, such as the iterators returned by the `Symbol.asyncIterator` method. +- The `for...of` loop can be used with the `await` keyword to iterate over the values of asynchronous iterators in an asynchronous function. +- The `for...of` loop can be used with the `break` and `continue` statements to control the flow of the loop. + +## Example + +The following example demonstrates how to use the `for...of` loop to iterate over the elements of an array: + +```js title="app.js" +const numbers = [1, 2, 3, 4, 5]; + +for (const number of numbers) { + console.log(number); +} +``` + +In this example, the `for...of` loop iterates over the elements of the `numbers` array and assigns each element to the `number` variable on each iteration. It then executes the code inside the loop to log each element to the console. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +3 +4 +5 +``` + +The `for...of` loop is a convenient and concise way to iterate over the elements of an iterable object in JavaScript. It provides a simple and readable syntax for performing actions on each element of the iterable. + +## Flow Chart of the `for...of` Loop + +```mermaid +graph TD; + Start([Start]) --> Initialization; + Initialization -->|Condition| Condition{Condition}; + Condition -->|True| Action; + Action --> Increment[Next Element]; + Increment --> Condition{Condition}; + Condition -->|False| Stop; + Stop --> End([End]); +``` + +The flow chart above illustrates the flow of the `for...of` loop. It starts with the `Initialization` step, where the loop variable is initialized to the first element of the iterable. It then checks the `Condition` before each iteration. If the condition is `true`, it executes the `Action` and moves to the next element. This process continues until the condition is `false`, at which point the loop stops. + +## Using `break` and `continue` Statements + +You can use the `break` and `continue` statements to control the flow of the `for...of` loop. The `break` statement can be used to terminate the loop prematurely, while the `continue` statement can be used to skip the current iteration and move to the next element. + +Here's an example that demonstrates the use of the `break` and `continue` statements with the `for...of` loop: + +```js title="app.js" +const numbers = [1, 2, 3, 4, 5]; + +for (const number of numbers) { + if (number === 3) { + continue; // Skip the number 3 + } + + if (number === 5) { + break; // Terminate the loop when the number 5 is encountered + } + + console.log(number); +} +``` + +In this example, the `continue` statement is used to skip the number `3`, and the `break` statement is used to terminate the loop when the number `5` is encountered. The code inside the loop logs the numbers to the console, skipping the number `3` and terminating the loop when the number `5` is encountered. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +4 +``` + +In each iteration, the code inside the loop checks if the current number is `3` or `5`. If the number is `3`, it skips the current iteration using the `continue` statement. If the number is `5`, it terminates the loop using the `break` statement. Otherwise, it logs the number to the console. + +The `for...of` loop is a powerful and flexible construct that provides a convenient way to iterate over the elements of an iterable object in JavaScript. It can be used with arrays, sets, maps, strings, and any other iterable object to perform actions on each element in a concise and readable manner. + +:::tip 📝 Note + +The `for...of` loop cannot be used to iterate over plain objects (i.e., objects created using `{}`) because they are not iterable. To iterate over the properties of an object, you should use the `for...in` loop or the `Object.keys`, `Object.values`, or `Object.entries` methods. + +The `for...of` loop can also be used with generator functions to iterate over the values generated by the generator. + +The `for...of` loop cannot be used to iterate over asynchronous iterators, such as the iterators returned by the `Symbol.asyncIterator` method. However, it can be used with the `await` keyword to iterate over the values of asynchronous iterators in an asynchronous function. + +The `for...of` loop can be used with the `break` and `continue` statements to control the flow of the loop. + +::: + +## Summary + +In this tutorial, we learned about the `for...of` loop in JavaScript. We learned how to use the `for...of` loop to iterate over the elements of an iterable object. We also learned about using the `break` and `continue` statements to control the flow of the loop. The `for...of` loop is a powerful and flexible construct that provides a convenient and concise way to iterate over the elements of an iterable object in JavaScript. diff --git a/docs/javascript/if-else.md b/docs/javascript/if-else.md new file mode 100644 index 000000000..266b6e693 --- /dev/null +++ b/docs/javascript/if-else.md @@ -0,0 +1,94 @@ +--- +id: if-else-in-javascript +title: If...Else in JavaScript +sidebar_label: If...Else +sidebar_position: 19 +tags: [JavaScript, Conditional, Statement, If, Else, Ternary, Operator, Nested, Switch, Nullish, Coalescing, Operator, Decision, Making, Control, Flow, Conditional, Statements] +description: "In this tutorial, we will learn about the if...else statement in JavaScript. We will learn how to use the if...else statement to make decisions in JavaScript." +--- + +In JavaScript, the `if...else` statement is used to execute a block of code if a specified condition is true. If the condition is false, another block of code can be executed. + +## Syntax + +The syntax of the `if...else` statement is as follows: + +```js title="app.js" +if (condition) { + // code to be executed if the condition is true +} else { + // code to be executed if the condition is false +} +``` + +## Example + +The following example demonstrates how to use the `if...else` statement to check if a number is even or odd: + +```js title="app.js" +let num = 10; + +if (num % 2 === 0) { + console.log(`${num} is even`); +} else { + console.log(`${num} is odd`); +} +``` + +In the above example, the `if...else` statement checks if the number `num` is even or odd and logs the result to the console. + +## Nested if...else + +You can also use the `if...else` statement inside another `if...else` statement. This is known as a nested `if...else` statement. + +The following example demonstrates how to use a nested `if...else` statement to check if a number is positive, negative, or zero: + +```js title="app.js" +let num = 10; + +if (num > 0) { + console.log(`${num} is positive`); +} else if (num < 0) { + console.log(`${num} is negative`); +} else { + console.log(`${num} is zero`); +} +``` + +In the above example, the nested `if...else` statement checks if the number `num` is positive, negative, or zero and logs the result to the console. + +## Ternary Operator + +The `if...else` statement can also be written using the ternary operator (`? :`). + +The following example demonstrates how to use the ternary operator to check if a number is even or odd: + +```js title="app.js" +let num = 10; + +const result = num % 2 === 0 ? `${num} is even` : `${num} is odd`; + +console.log(result); +``` + +In the above example, the ternary operator checks if the number `num` is even or odd and assigns the result to the `result` variable. + +:::info 📝 Note +

Conditional Statements

+ +The `if...else` statement is a conditional statement that executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. + +In JavaScript we have the following conditional statements: + +- **`if` statement:** executes a block of code if a specified condition is true. +- **`if...else` statement:** executes a block of code if a specified condition is true and another block of code if the condition is false. +- **`if...else if...else` statement:** executes a block of code if a specified condition is true, another block of code if another condition is true, and another block of code if the conditions are false. +- **`switch` statement:** selects one of many code blocks to be executed. +- **`ternary operator`:** assigns a value to a variable based on a specified condition. +- **`nullish coalescing operator`:** returns the right-hand operand when the left-hand operand is `null` or `undefined`. + +::: + +## Conclusion + +In this tutorial, we learned about the `if...else` statement in JavaScript. We learned how to use the `if...else` statement to make decisions in JavaScript. We also saw examples of how to use the `if...else` statement to check if a number is even or odd and to check if a number is positive, negative, or zero. \ No newline at end of file diff --git a/docs/javascript/img/breakpoints.gif b/docs/javascript/img/breakpoints.gif new file mode 100644 index 000000000..0e0debcf6 Binary files /dev/null and b/docs/javascript/img/breakpoints.gif differ diff --git a/docs/javascript/img/call-stack.gif b/docs/javascript/img/call-stack.gif new file mode 100644 index 000000000..c8952fccc Binary files /dev/null and b/docs/javascript/img/call-stack.gif differ diff --git a/docs/javascript/img/source.gif b/docs/javascript/img/source.gif new file mode 100644 index 000000000..32d83a284 Binary files /dev/null and b/docs/javascript/img/source.gif differ diff --git a/docs/javascript/intro-js.md b/docs/javascript/intro-js.md new file mode 100644 index 000000000..0f957956a --- /dev/null +++ b/docs/javascript/intro-js.md @@ -0,0 +1,233 @@ +--- +id: intro-js +title: Introduction to JavaScript +sidebar_label: Introduction to JavaScript +sidebar_position: 1 +tags: [JavaScript, Introduction of js, Introduction of JavaScript] +description: What is JavaScript? Why JavaScript? How to use JavaScript? Learn about JavaScript in this tutorial. +--- + +JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. + +> JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers. + +## What is JavaScript? + +JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. JavaScript is a scripting language. JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. + +:::note + +## Key Points + +- JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. +- It is a dynamic, weakly typed, prototype-based language with first-class functions. +- JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. +- JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. +- JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers. +- JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. +- JavaScript is a scripting language. +- JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. +- It is a dynamic, weakly typed, prototype-based language with first-class functions. +- JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. +- JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. + ::: + +## Why JavaScript? + +JavaScript is scripting language that enables you to create dynamically updating content, control multimedia, animate images, and much more. And it is the most popular programming language in the world. JavaScript is the programming language of the Web. The overwhelming majority of websites use JavaScript, and all modern web browsers—on desktops, game consoles, tablets, and smartphones—include JavaScript interpreters, making it an essential part of the web platform. + +## How to use JavaScript? + +JavaScript can be used in a lot of different ways. Here are a few examples: + +### 1. JavaScript Can Change HTML Content + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

Welcome CodeHarborHub Learners!

+
+ +### 2. JavaScript Can Change HTML Styles + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+
+ +### 3. JavaScript Can Hide HTML Elements + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+ +
+ +### 4. JavaScript Can Show HTML Elements + +```html title="index.html" + + + +

My First JavaScript

+ + + + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+ +
+ +### 5. JavaScript Can Change HTML Attributes + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+ +
+ +### 6. JavaScript Can Change HTML Image + +```html title="index.html" + + + +

My First JavaScript

+ + + + + + +``` + + +

My First JavaScript

+ + +
+ +### 7. JavaScript Can Validate Data + +```html title="index.html" + + + +

My First JavaScript

+ +
+ Email: + + + + + + +``` + +## Conclusion + +In this article, we have learned about JavaScript, its introduction, and its usage. We have also seen how JavaScript can be used to change HTML content, styles, and attributes. We have also seen how JavaScript can be used to validate data. \ No newline at end of file diff --git a/docs/javascript/js-versions/_category_.json b/docs/javascript/js-versions/_category_.json new file mode 100644 index 000000000..65cc4e4e1 --- /dev/null +++ b/docs/javascript/js-versions/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Versions of JavaScript", + "position": 44, + "link": { + "type": "generated-index", + "description": "JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997. Since then, there have been several versions of JavaScript, each adding new features and improving the language. This page provides an overview of the different versions of JavaScript, and the features they introduced." + } + } \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2016.md b/docs/javascript/js-versions/js-2016.md new file mode 100644 index 000000000..62a85076d --- /dev/null +++ b/docs/javascript/js-versions/js-2016.md @@ -0,0 +1,90 @@ +--- +id: es2016-version-of-javascript +title: JavaScript ES2016 Version (2016) +sidebar_label: ES2016 Version (2016) +sidebar_position: 3 +tags: [JavaScript, ES2016, CMAScript 2016, JavaScript ES2016, JavaScript ES2016, JavaScript ES2016 Version, JavaScript ES2016 Version] +description: "In this tutorial, we will learn about the ES2016 version of JavaScript, also known as ECMAScript 2016. We will discuss the new features introduced in ES2016 and how to use them in your JavaScript code." +--- + +JavaScript ES2016 (ECMAScript 2016) is the seventh major release of the JavaScript language specification. It was finalized in June 2016. ES2016 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2016 and how to use them in your JavaScript code. + +## Features of ES2016 + +ES2016 introduced several new features and enhancements to JavaScript. Some of the key features of ES2016 are: + +1. **Exponentiation Operator (`**`)**: ES2016 introduced the exponentiation operator (`**`), which allows you to raise one number to the power of another number. For example, `2 ** 3` is equivalent to `2 * 2 * 2`. + + For example: + + ```javascript title="Exponentiation Operator Example" + let result = 2 ** 3; // 2 raised to the power of 3 + console.log(result); // Output: 8 + ``` + +2. **Array.prototype.includes()**: ES2016 introduced the `Array.prototype.includes()` method, which allows you to check if an array includes a specific element. It returns `true` if the array contains the element, and `false` otherwise. + + For example: + + ```javascript title="Array.prototype.includes() Example" + let numbers = [1, 2, 3, 4, 5]; + console.log(numbers.includes(3)); // Output: true + console.log(numbers.includes(6)); // Output: false + ``` + +3. **Additional Features**: ES2016 also introduced other minor features and enhancements to JavaScript, such as the `TypedArray.prototype.includes()` method for typed arrays and the `Object.values()` and `Object.entries()` methods for objects. + + For example: + + ```javascript title="Object.values() and Object.entries() Example" + let person = { name: "Alice", age: 30 }; + console.log(Object.values(person)); // Output: ["Alice", 30] + console.log(Object.entries(person)); // Output: [["name", "Alice"], ["age", 30]] + ``` + +## Browser Support for ES2016 + +Most modern web browsers support ES2016 features, but some older browsers may not fully support all ES2016 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2016 code into ES5 code, which is compatible with older browsers. + +ES2016 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2016 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 52+ | | 49+ | | 10.1+ | | 14+ | | 39+ | | No | | +| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ❌| | + + +:::info 📝 Note + +- **Chrome**: 52+ (Latest ✅) + + Chrome has full support for ES2016 features. You can use ES2016 features in Chrome without any issues. Chrome 52 and later versions fully support ES2016 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 49+ (Latest ✅) + + Firefox has full support for ES2016 features. You can use ES2016 features in Firefox without any issues. Firefox 49 and later versions fully support ES2016 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 10.1+ (Latest ✅) + + Safari has full support for ES2016 features. You can use ES2016 features in Safari without any issues. Safari 10.1 and later versions fully support ES2016 features. Safari is a popular web browser, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 14+ (Latest ✅) + + Edge has full support for ES2016 features. You can use ES2016 features in Edge without any issues. Edge 14 and later versions fully support ES2016 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 39+ (Latest ✅) + + Opera has full support for ES2016 features. You can use ES2016 features in Opera without any issues. Opera 39 and later versions fully support ES2016 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No (Latest ❌) + + Internet Explorer does not support ES2016 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2016 code into ES5 code, which is compatible with Internet Explorer. + +::: + + +## Conclusion + +ES2016 introduced several new features and enhancements to JavaScript, such as the exponentiation operator, `Array.prototype.includes()` method, and `Object.values()` and `Object.entries()` methods. These features make it easier to work with numbers, arrays, and objects in JavaScript. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2017.md b/docs/javascript/js-versions/js-2017.md new file mode 100644 index 000000000..72fa4ba29 --- /dev/null +++ b/docs/javascript/js-versions/js-2017.md @@ -0,0 +1,123 @@ +--- +id: es2017-version-of-javascript +title: JavaScript ES2017 Version (2017) +sidebar_label: ES2017 Version (2017) +sidebar_position: 4 +tags: [JavaScript, ES2017, ECMAScript 2017, JavaScript ES2017, JavaScript ES2017, JavaScript ES2017 Version, JavaScript ES2017 Version] +description: "In this tutorial, we will learn about the ES2017 version of JavaScript, also known as ECMAScript 2017. We will discuss the new features introduced in ES2017 and how to use them in your JavaScript code." +--- + +JavaScript ES2017 (ECMAScript 2017) is the eighth major release of the JavaScript language specification. It was finalized in June 2017. ES2017 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2017 and how to use them in your JavaScript code. + +## Features of ES2017 + +ES2017 introduced several new features and enhancements to JavaScript. Some of the key features of ES2017 are: + +1. **Async/Await Functions**: ES2017 introduced the `async` and `await` keywords, which allow you to write asynchronous code that looks synchronous. The `async` keyword is used to define an asynchronous function, and the `await` keyword is used to pause the execution of an asynchronous function until a `Promise` is settled. + + For example: + + ```javascript title="Async/Await Example" + function delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + async function asyncFunction() { + console.log("Start"); + await delay(2000); + console.log("End"); + } + + asyncFunction(); + ``` + +2. **Object.values() and Object.entries()**: ES2017 introduced the `Object.values()` and `Object.entries()` methods, which allow you to get the values and entries of an object, respectively. The `Object.values()` method returns an array of the object's values, and the `Object.entries()` method returns an array of the object's key-value pairs. + + For example: + + ```javascript title="Object.values() and Object.entries() Example" + let person = { name: "Alice", age: 30 }; + console.log(Object.values(person)); // Output: ["Alice", 30] + console.log(Object.entries(person)); // Output: [["name", "Alice"], ["age", 30]] + ``` + +3. **String Padding**: ES2017 introduced the `String.prototype.padStart()` and `String.prototype.padEnd()` methods, which allow you to pad a string with spaces or other characters to a specified length. The `padStart()` method pads the string at the beginning, and the `padEnd()` method pads the string at the end. + + For example: + + ```javascript title="String Padding Example" + let str = "Hello"; + console.log(str.padStart(10, ".")); // Output: ".....Hello" + console.log(str.padEnd(10, ".")); // Output: "Hello....." + ``` + +4. **Shared Memory and Atomics**: ES2017 introduced the `SharedArrayBuffer` and `Atomics` objects, which allow you to work with shared memory and atomic operations in JavaScript. The `SharedArrayBuffer` object represents a shared memory region, and the `Atomics` object provides atomic operations for shared memory. + + For example: + + ```javascript title="Shared Memory and Atomics Example" + let buffer = new SharedArrayBuffer(16); + let view = new Int32Array(buffer); + view[0] = 42; + + Atomics.add(view, 0, 13); + console.log(view[0]); // Output: 55 + ``` + +## Browser Support for ES2017 + +Most modern web browsers support ES2017 features, but some older browsers may not fully support all ES2017 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2017 code into ES5 code, which is compatible with older browsers. + +ES2017 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2017 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 58+ | | 52+ | | 10.1+ | | 16+ | | 45+ | | No | | +| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ❌| | + +:::info 📝 Note + +- **Chrome**: 58+ (Latest ✅) + + Chrome has full support for ES2017 features. You can use ES2017 features in Chrome without any issues. Chrome 58 and later versions fully support ES2017 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 52+ (Latest ✅) + + Firefox has full support for ES2017 features. You can use ES2017 features in Firefox without any issues. Firefox 52 and later versions fully support ES2017 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 10.1+ (Latest ✅) + + Safari has full support for ES2017 features. You can use ES2017 features in Safari without any issues. Safari 10.1 and later versions fully support ES2017 features. Safari is a popular web browser, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 16+ (Latest ✅) + + Edge has full support for ES2017 features. You can use ES2017 features in Edge without any issues. Edge 16 and later versions fully support ES2017 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 45+ (Latest ✅) + + Opera has full support for ES2017 features. You can use ES2017 features in Opera without any issues. Opera 45 and later versions fully support ES2017 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No (Latest ❌) + + Internet Explorer does not support ES2017 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2017 code into ES5 code, which is compatible with Internet Explorer. + +::: + +:::tip Important + +

Why Internet Explorer does not support ES2017 features?

+ +Internet Explorer does not support ES2017 features because it is an outdated web browser that has been replaced by Microsoft Edge. Microsoft Edge is the modern web browser from Microsoft that supports the latest web standards and features, including ES2017. It is recommended to use Microsoft Edge or other modern web browsers to ensure compatibility with the latest JavaScript features. If you need to support Internet Explorer for legacy reasons, you can use a transpiler like Babel to convert your ES2017 code into ES5 code, which is compatible with Internet Explorer. + +::: + + +ES2017 introduced several new features and enhancements to JavaScript, making it easier to write asynchronous code, work with objects, manipulate strings, and work with shared memory. You can start using ES2017 features in your JavaScript code to take advantage of these new capabilities. + +## Conclusion + +ES2017 introduced several new features and enhancements to JavaScript, such as async/await functions, Object.values() and Object.entries() methods, string padding methods, and shared memory and atomics. These features make it easier to work with asynchronous code, objects, strings, and shared memory in JavaScript. + +By using ES2017 features, you can write more expressive and concise JavaScript code that takes advantage of the latest language features and capabilities. You can start using ES2017 features in your JavaScript code to improve readability, maintainability, and performance. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2018.md b/docs/javascript/js-versions/js-2018.md new file mode 100644 index 000000000..426c95a54 --- /dev/null +++ b/docs/javascript/js-versions/js-2018.md @@ -0,0 +1,141 @@ +--- +id: es2018-version-of-javascript +title: JavaScript ES2018 Version (2018) +sidebar_label: ES2018 Version (2018) +sidebar_position: 5 +tags: [JavaScript, ES2018, ECMAScript 2018, JavaScript ES2018, JavaScript ES2018, JavaScript ES2018 Version, JavaScript ES2018 Version] +description: "In this tutorial, we will learn about the ES2018 version of JavaScript, also known as ECMAScript 2018. We will discuss the new features introduced in ES2018 and how to use them in your JavaScript code." +--- + +JavaScript ES2018 (ECMAScript 2018) is the ninth major release of the JavaScript language specification. It was finalized in June 2018. ES2018 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2018 and how to use them in your JavaScript code. + +## Features of ES2018 + +ES2018 introduced several new features and enhancements to JavaScript. Some of the key features of ES2018 are: + +1. **Asynchronous Iteration**: ES2018 introduced asynchronous iteration, which allows you to iterate over asynchronous data sources such as asynchronous generators and asynchronous iterators. You can use the `for-await-of` loop to iterate over asynchronous data sources. + + For example: + + ```javascript title="Asynchronous Iteration Example" + async function* asyncGenerator() { + yield 1; + yield 2; + yield 3; + } + + (async () => { + for await (let num of asyncGenerator()) { + console.log(num); + } + })(); + ``` + +2. **Promise.prototype.finally()**: ES2018 introduced the `Promise.prototype.finally()` method, which allows you to run cleanup logic after a `Promise` is settled (either fulfilled or rejected). The `finally()` method is called when the `Promise` is settled, regardless of whether it was fulfilled or rejected. + + For example: + + ```javascript title="Promise.prototype.finally() Example" + let promise = new Promise((resolve, reject) => { + resolve("Success!"); + }); + + promise.then((value) => { + console.log(value); + }).catch((error) => { + console.error(error); + }).finally(() => { + console.log("Cleanup logic here"); + }); + ``` + +3. **Rest/Spread Properties**: ES2018 introduced the rest and spread properties for object literals. The rest properties allow you to extract the remaining properties of an object into a new object, while the spread properties allow you to spread the properties of an object into another object. + + For example: + + ```js title="Rest/Spread Properties Example" + let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; + console.log(x); // Output: 1 + console.log(y); // Output: 2 + console.log(z); // Output: { a: 3, b: 4 } + ``` + +4. **Object Rest/Spread Properties**: ES2018 also introduced rest and spread properties for object destructuring. The rest properties allow you to extract the remaining properties of an object into a new object, while the spread properties allow you to spread the properties of an object into another object. + + For example: + + ```js title="Object Rest/Spread Properties Example" + let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; + console.log(x); // Output: 1 + console.log(y); // Output: 2 + console.log(z); // Output: { a: 3, b: 4 } + ``` + +5. **RegExp Lookbehind Assertions**: ES2018 introduced lookbehind assertions for regular expressions. Lookbehind assertions allow you to match a pattern only if it is preceded by another pattern. + + For example: + + ```js title="RegExp Lookbehind Assertions Example" + let str = "Hello, World!"; + let regex = /(?<=Hello, )World/; + console.log(regex.test(str)); // Output: true + ``` + +6. **RegExp Unicode Property Escapes**: ES2018 introduced Unicode property escapes for regular expressions. Unicode property escapes allow you to match characters based on their Unicode properties. + + For example: + + ```js title="RegExp Unicode Property Escapes Example" + let str = "😀"; + let regex = /\p{Emoji}/u; + console.log(regex.test(str)); // Output: true + ``` + +## Browser Support for ES2018 + +Most modern web browsers support ES2018 features, but some older browsers may not fully support all ES2018 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2018 code into ES5 code, which is compatible with older browsers. + +ES2018 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2018 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 66+ | | 58+ | | 11.1+ | | 79+ | | 53+ | | No | | +| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ❌| | + +:::info 📝 Note + +- **Chrome**: 66+ (Latest ✅) + + Chrome has full support for ES2018 features. You can use ES2018 features in Chrome without any issues. Chrome 66 and later versions fully support ES2018 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 58+ (Latest ✅) + + Firefox has full support for ES2018 features. You can use ES2018 features in Firefox without any issues. Firefox 58 and later versions fully support ES2018 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 11.1+ (Latest ✅) + + Safari has full support for ES2018 features. You can use ES2018 features in Safari without any issues. Safari 11.1 and later versions fully support ES2018 features. Safari is a popular web browser, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 79+ (Latest ✅) + + Edge has full support for ES2018 features. You can use ES2018 features in Edge without any issues. Edge 79 and later versions fully support ES2018 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 53+ (Latest ✅) + + Opera has full support for ES2018 features. You can use ES2018 features in Opera without any issues. Opera 53 and later versions fully support ES2018 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No (Latest ❌) + + Internet Explorer does not support ES2018 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2018 code into ES5 code, which is compatible with Internet Explorer. + +::: + +ES2018 introduced several new features and enhancements to JavaScript, making it more powerful and expressive. You can start using ES2018 features in your JavaScript code to take advantage of these new capabilities and improve your development workflow. + +In the next tutorial, we will learn about the ES2019 version of JavaScript and the new features introduced in ES2019. + +## Conclusion + +ES2018 introduced several new features and enhancements to JavaScript, making it easier to write asynchronous code, work with objects, manipulate strings, and work with regular expressions. You can start using ES2018 features in your JavaScript code to take advantage of these new capabilities. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2019.md b/docs/javascript/js-versions/js-2019.md new file mode 100644 index 000000000..ce189fa63 --- /dev/null +++ b/docs/javascript/js-versions/js-2019.md @@ -0,0 +1,85 @@ +--- +id: es2019-version-of-javascript +title: JavaScript ES2019 Version (2019) +sidebar_label: ES2019 Version (2019) +sidebar_position: 6 +tags: + [ + JavaScript, + ES2019, + ECMAScript 2019, + JavaScript ES2019, + JavaScript ES2019, + JavaScript ES2019 Version, + JavaScript ES2019 Version, + ] +description: "In this tutorial, we will learn about the ES2019 version of JavaScript, also known as ECMAScript 2019. We will discuss the new features introduced in ES2019 and how to use them in your JavaScript code." +--- + +JavaScript ES2019 (ECMAScript 2019) is the tenth major release of the JavaScript language specification. It was finalized in June 2019. ES2019 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2019 and how to use them in your JavaScript code. + +## Features of ES2019 + +ES2019 introduced several new features and enhancements to JavaScript. Some of the key features of ES2019 are: + +1. **Array.prototype.flat() and Array.prototype.flatMap()**: ES2019 introduced the `Array.prototype.flat()` and `Array.prototype.flatMap()` methods for working with nested arrays. The `flat()` method flattens a nested array to a specified depth, while the `flatMap()` method maps each element using a mapping function and then flattens the result to a depth of 1. + + For example: + + ```javascript title="Array.prototype.flat() and Array.prototype.flatMap() Example" + let nestedArray = [1, [2, [3, 4], 5]]; + console.log(nestedArray.flat()); // Output: [1, 2, [3, 4], 5] + + let array = [1, 2, 3, 4, 5]; + console.log(array.flatMap((x) => [x, x * 2])); // Output: [1, 2, 2, 4, 3, 6, 4, 8, 5, 10] + ``` + +2. **Object.fromEntries()**: ES2019 introduced the `Object.fromEntries()` method, which allows you to create an object from an iterable of key-value pairs. It takes an iterable (such as an array) of key-value pairs and returns a new object with those key-value pairs. + + For example: + + ```javascript title="Object.fromEntries() Example" + let entries = [ + ["name", "Alice"], + ["age", 30], + ]; + let person = Object.fromEntries(entries); + console.log(person); // Output: { name: 'Alice', age: 30 } + ``` + +3. **String.prototype.trimStart() and String.prototype.trimEnd()**: ES2019 introduced the `String.prototype.trimStart()` and `String.prototype.trimEnd()` methods, which allow you to trim whitespace characters from the start and end of a string, respectively. These methods are also known as `String.prototype.trimLeft()` and `String.prototype.trimRight()`. + + For example: + + ```javascript title="String.prototype.trimStart() and String.prototype.trimEnd() Example" + let str = " Hello "; + console.log(str.trimStart()); // Output: 'Hello ' + console.log(str.trimEnd()); // Output: ' Hello' + ``` + +4. **Symbol.prototype.description**: ES2019 introduced the `Symbol.prototype.description` property, which allows you to access the description of a `Symbol`. The description is the optional string that was provided when the `Symbol` was created. + + For example: + + ```javascript title="Symbol.prototype.description Example" + let sym = Symbol("foo"); + console.log(sym.description); // Output: 'foo' + ``` + +## Browser Support for ES2019 + +Most modern web browsers support ES2019 features, but some older browsers may not fully support all ES2019 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2019 code into ES5 code, which is compatible with older browsers. + +ES2019 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2019 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 73+ | | 69+ | | 12.1+ | | 79+ | | 60+ | | No | | +| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ❌| | + + +## Conclusion + +ES2019 introduced several new features and enhancements to JavaScript, making it easier and more convenient to work with arrays, objects, strings, and symbols. By using ES2019 features, you can write more concise and expressive JavaScript code. Most modern web browsers support ES2019 features, allowing you to use them in your JavaScript code without the need for a transpiler in most cases. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2020.md b/docs/javascript/js-versions/js-2020.md new file mode 100644 index 000000000..d6fa7230e --- /dev/null +++ b/docs/javascript/js-versions/js-2020.md @@ -0,0 +1,128 @@ +--- +id: es2020-version-of-javascript +title: JavaScript ES2020 Version (2020) +sidebar_label: ES2020 Version (2020) +sidebar_position: 6 +tags: [JavaScript, ES2020, ECMAScript 2020, JavaScript ES2020, JavaScript ES2020, JavaScript ES2020 Version, JavaScript ES2020 Version] +description: "In this tutorial, we will learn about the ES2020 version of JavaScript, also known as ECMAScript 2020. We will discuss the new features introduced in ES2020 and how to use them in your JavaScript code." +--- + +JavaScript ES2020 (ECMAScript 2020) is the eleventh major release of the JavaScript language specification. It was finalized in June 2020. ES2020 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2020 and how to use them in your JavaScript code. + +## Features of ES2020 + +ES2020 introduced several new features and enhancements to JavaScript. Some of the key features of ES2020 are: + +1. **BigInt**: ES2020 introduced the `BigInt` primitive type, which allows you to represent arbitrarily large integers in JavaScript. The `BigInt` type is created by appending `n` to the end of an integer literal or by calling the `BigInt()` constructor with a numeric value. + + For example: + + ```javascript title="BigInt Example" + const bigNumber = 1234567890123456789012345678901234567890n; + console.log(bigNumber); // Output: 1234567890123456789012345678901234567890n + ``` + +2. **Dynamic Import**: ES2020 introduced dynamic `import()` expressions, which allow you to dynamically import modules in JavaScript. The `import()` function returns a `Promise` that resolves to the module namespace object of the requested module. + + For example: + + ```javascript title="Dynamic Import Example" + const modulePath = './module.js'; + import(modulePath) + .then((module) => { + console.log(module.default); + }) + .catch((error) => { + console.error(error); + }); + ``` + +3. **Nullish Coalescing Operator (`??`)**: ES2020 introduced the nullish coalescing operator (`??`), which allows you to provide a default value for variables that are `null` or `undefined`. The nullish coalescing operator returns the right-hand operand when the left-hand operand is `null` or `undefined`, and otherwise returns the left-hand operand. + + For example: + + ```javascript title="Nullish Coalescing Operator Example" + const name = null; + const defaultName = name ?? 'John Doe'; + console.log(defaultName); // Output: 'John Doe' + ``` + +4. **Optional Chaining Operator (`?.`)**: ES2020 introduced the optional chaining operator (`?.`), which allows you to safely access nested properties of an object without having to check if each property exists. If a property is `null` or `undefined`, the optional chaining operator short-circuits and returns `undefined`. + + For example: + + ```javascript title="Optional Chaining Operator Example" + const user = { + name: 'Alice', + address: { + city: 'New York', + }, + }; + + console.log(user.address?.city); // Output: 'New York' + console.log(user.address?.country); // Output: undefined + ``` + +5. **Promise.allSettled()**: ES2020 introduced the `Promise.allSettled()` method, which returns a `Promise` that resolves after all the input `Promises` have settled (either fulfilled or rejected). The `Promise` returned by `Promise.allSettled()` resolves with an array of objects that describe the outcome of each `Promise`. + + For example: + + ```javascript title="Promise.allSettled() Example" + const promises = [ + Promise.resolve(1), + Promise.reject(new Error('Error!')), + Promise.resolve(3), + ]; + + Promise.allSettled(promises) + .then((results) => { + results.forEach((result) => { + console.log(result.status, result.value); + }); + }); + ``` + +## Browser Support for ES2020 + +Most modern web browsers support ES2020 features, but some older browsers may not fully support all ES2020 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2020 code into ES5 code, which is compatible with older browsers. + +ES2020 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2020 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 85+ | | 79+ | | 14+ | | 79+ | | 71+ | | No | | +| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ✅| |Latest ❌| | + +:::info 📝 Note + +- **Chrome**: 85+ (Latest ✅) + + Chrome has full support for ES2020 features. You can use ES2020 features in Chrome without any issues. Chrome 85 and later versions fully support ES2020 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 79+ (Latest ✅) + + Firefox has full support for ES2020 features. You can use ES2020 features in Firefox without any issues. Firefox 79 and later versions fully support ES2020 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 14+ (Latest ✅) + + Safari has full support for ES2020 features. You can use ES2020 features in Safari without any issues. Safari 14 and later versions fully support ES2020 features. Safari is a popular web browser on macOS and iOS devices, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 79+ (Latest ✅) + + Edge has full support for ES2020 features. You can use ES2020 features in Edge without any issues. Edge 79 and later versions fully support ES2020 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 71+ (Latest ✅) + + Opera has full support for ES2020 features. You can use ES2020 features in Opera without any issues. Opera 71 and later versions fully support ES2020 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No support (Latest ❌) + + Internet Explorer does not support ES2020 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2020 code into ES5 code, which is compatible with Internet Explorer. + +::: + +## Conclusion + +ES2020 introduced several new features and enhancements to JavaScript, such as the `BigInt` primitive type, dynamic `import()` expressions, the nullish coalescing operator (`??`), the optional chaining operator (`?.`), and the `Promise.allSettled()` method. These features improve the expressiveness and flexibility of JavaScript, making it easier to write clean and concise code. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2021.md b/docs/javascript/js-versions/js-2021.md new file mode 100644 index 000000000..348ddb214 --- /dev/null +++ b/docs/javascript/js-versions/js-2021.md @@ -0,0 +1,116 @@ +--- +id: es2021-version-of-javascript +title: JavaScript ES2021 Version (2021) +sidebar_label: ES2021 Version (2021) +sidebar_position: 7 +tags: [JavaScript, ES2021, ECMAScript 2021, JavaScript ES2021, JavaScript ES2021, JavaScript ES2021 Version, JavaScript ES2021 Version] +description: "In this tutorial, we will learn about the ES2021 version of JavaScript, also known as ECMAScript 2021. We will discuss the new features introduced in ES2021 and how to use them in your JavaScript code." +--- + +JavaScript ES2021 (ECMAScript 2021) is the twelfth major release of the JavaScript language specification. It was finalized in June 2021. ES2021 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2021 and how to use them in your JavaScript code. + +## Features of ES2021 + +ES2021 introduced several new features and enhancements to JavaScript. Some of the key features of ES2021 are: + +1. **String.prototype.replaceAll()**: ES2021 introduced the `String.prototype.replaceAll()` method, which allows you to replace all occurrences of a substring within a string with another substring. The `replaceAll()` method replaces all occurrences of a specified substring with another substring and returns a new string. + + For example: + + ```javascript title="String.prototype.replaceAll() Example" + let str = "Hello, World!"; + let newStr = str.replaceAll("o", "0"); + console.log(newStr); // Output: Hell0, W0rld! + ``` + +2. **Logical Assignment Operators**: ES2021 introduced the logical assignment operators `||=` (logical OR assignment) and `&&=` (logical AND assignment). These operators allow you to assign a value to a variable only if the variable is `null`, `undefined`, `false`, `0`, `NaN`, or an empty string (`""`). + + For example: + + ```javascript title="Logical Assignment Operators Example" + let x = 10; + x ||= 20; // Equivalent to: x = x || 20; + console.log(x); // Output: 10 + + let y = 0; + y &&= 5; // Equivalent to: y = y && 5; + console.log(y); // Output: 0 + ``` + +3. **Numeric Separators**: ES2021 introduced numeric separators, which allow you to use underscores (`_`) as separators in numeric literals to make them more readable. Numeric separators are ignored by the JavaScript engine and are used only for formatting purposes. + + For example: + + ```javascript title="Numeric Separators Example" + let billion = 1_000_000_000; + console.log(billion); // Output: 1000000000 + + let pi = 3.14159_26535; + console.log(pi); // Output: 3.1415926535 + ``` + +4. **WeakRef**: ES2021 introduced the `WeakRef` object, which allows you to create weak references to objects. Weak references do not prevent the garbage collector from collecting the object they reference. The `WeakRef` object is useful for implementing caches or other data structures that need to hold references to objects without preventing them from being garbage collected. + + For example: + + ```javascript title="WeakRef Example" + let obj = { name: "Alice" }; + let weakRef = new WeakRef(obj); + console.log(weakRef.deref()); // Output: { name: 'Alice' } + ``` + +5. **FinalizationRegistry**: ES2021 introduced the `FinalizationRegistry` object, which allows you to register objects for cleanup when they are garbage collected. The `FinalizationRegistry` object is used to perform cleanup actions on objects before they are collected by the garbage collector. + + For example: + + ```javascript title="FinalizationRegistry Example" + let obj = { name: "Alice" }; + let finalizationRegistry = new FinalizationRegistry((heldValue) => { + console.log(`Cleaning up: ${heldValue.name}`); + }); + finalizationRegistry.register(obj, "held value"); + obj = null; // Allow obj to be garbage collected + ``` + +6. **Promise.any()**: ES2021 introduced the `Promise.any()` method, which takes an iterable of `Promises` and returns a new `Promise` that resolves as soon as one of the input `Promises` is fulfilled. If all the input `Promises` are rejected, the `Promise` returned by `Promise.any()` is rejected with an `AggregateError` that contains an array of rejection reasons. + + For example: + + ```javascript title="Promise.any() Example" + const promises = [ + Promise.reject("Error 1"), + Promise.resolve("Success 1"), + Promise.reject("Error 2"), + ]; + + Promise.any(promises) + .then((value) => { + console.log(value); // Output: "Success 1" + }) + .catch((error) => { + console.error(error); // Output: AggregateError: All promises were rejected + }); + ``` + +7. **AggregateError**: ES2021 introduced the `AggregateError` object, which is used to represent multiple errors in a single error object. The `AggregateError` object contains an array of errors as its `errors` property. + + For example: + + ```javascript title="AggregateError Example" + const error1 = new Error("Error 1"); + const error2 = new Error("Error 2"); + const aggregateError = new AggregateError([error1, error2]); + console.log(aggregateError.errors); // Output: [Error: Error 1, Error: Error 2] + ``` + +## Browser Support for ES2021 + +Most modern web browsers support ES2021 features, but some older browsers may not fully support all ES2021 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2021 code into ES5 code, which is compatible with older browsers. + +ES2021 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. However, it is always a good practice to check the compatibility of the features you are using with the target browsers to ensure a consistent user experience. + +For more information on browser support for ES2021 features, you can check the compatibility tables provided by [Can I use](https://caniuse.com/). + +## Conclusion + +In this tutorial, we learned about the ES2021 version of JavaScript (ECMAScript 2021) and the new features introduced in ES2021. We explored features such as `String.prototype.replaceAll()`, logical assignment operators, numeric separators, `WeakRef`, `FinalizationRegistry`, `Promise.any()`, and `AggregateError`. You can start using these features in your JavaScript code to take advantage of the latest enhancements in the language. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2022.md b/docs/javascript/js-versions/js-2022.md new file mode 100644 index 000000000..69b74f0fa --- /dev/null +++ b/docs/javascript/js-versions/js-2022.md @@ -0,0 +1,126 @@ +--- +id: es2022-version-of-javascript +title: JavaScript ES2022 Version (2022) +sidebar_label: ES2022 Version (2022) +sidebar_position: 8 +tags: [JavaScript, ES2022, ECMAScript 2022, JavaScript ES2022, JavaScript ES2022, JavaScript ES2022 Version, JavaScript ES2022 Version] +description: "In this tutorial, we will learn about the ES2022 version of JavaScript, also known as ECMAScript 2022. We will discuss the new features introduced in ES2022 and how to use them in your JavaScript code." +--- + +JavaScript ES2022 (ECMAScript 2022) is the thirteenth major release of the JavaScript language specification. It was finalized in June 2022. ES2022 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2022 and how to use them in your JavaScript code. + +## Features of ES2022 + +ES2022 introduced several new features and enhancements to JavaScript. Some of the key features of ES2022 are: + +1. **String.prototype.replaceAll()**: ES2022 introduced the `String.prototype.replaceAll()` method, which allows you to replace all occurrences of a substring within a string with another substring. The `replaceAll()` method replaces all occurrences of a specified substring with another substring and returns a new string. + + For example: + + ```javascript title="String.prototype.replaceAll() Example" + let str = "Hello, World!"; + let newStr = str.replaceAll("o", "0"); + console.log(newStr); // Output: Hell0, W0rld! + ``` + +2. **Logical Assignment Operators**: ES2022 introduced the logical assignment operators `||=` (logical OR assignment) and `&&=` (logical AND assignment). These operators allow you to assign a value to a variable only if the variable is `null`, `undefined`, `false`, `0`, `NaN`, or an empty string (`""`). + + For example: + + ```javascript title="Logical Assignment Operators Example" + let x = 10; + x ||= 20; // Equivalent to: x = x || 20; + console.log(x); // Output: 10 + + let y = 0; + y &&= 5; // Equivalent to: y = y && 5; + console.log(y); // Output: 0 + ``` + +3. **Numeric Separators**: ES2022 introduced numeric separators, which allow you to use underscores (`_`) as separators in numeric literals to make them more readable. Numeric separators are ignored by the JavaScript engine and are used only for formatting purposes. + + For example: + + ```javascript title="Numeric Separators Example" + let billion = 1_000_000_000; + console.log(billion); // Output: 1000000000 + + let pi = 3.14159_26535; + console.log(pi); // Output: 3.1415926535 + ``` + +4. **WeakRef**: ES2022 introduced the `WeakRef` object, which allows you to create weak references to objects. Weak references do not prevent the garbage collector from collecting the object they reference. The `WeakRef` object is useful for implementing caches or other data structures that need to hold references to objects without preventing them from being garbage collected. + + For example: + + ```javascript title="WeakRef Example" + let obj = { name: "Alice" }; + let weakRef = new WeakRef(obj); + console.log(weakRef.deref()); // Output: { name: 'Alice' } + ``` + +5. **Promise.any()**: ES2022 introduced the `Promise.any()` method, which takes an iterable of `Promise` objects and returns a single `Promise` that fulfills with the value of the first `Promise` in the iterable that fulfills. If all `Promise` objects in the iterable are rejected, the `Promise` returned by `Promise.any()` is rejected with an `AggregateError` containing the rejection reasons. + + For example: + + ```javascript title="Promise.any() Example" + let promise1 = new Promise((resolve, reject) => setTimeout(() => reject("Error 1"), 1000)); + let promise2 = new Promise((resolve, reject) => setTimeout(() => resolve("Success 2"), 500)); + let promise3 = new Promise((resolve, reject) => setTimeout(() => reject("Error 3"), 1500); + + Promise.any([promise1, promise2, promise3]) + .then((value) => console.log(value)) + .catch((error) => console.error(error)); + ``` + +6. **Final State**: ES2022 introduced the `final` keyword, which can be used to declare a variable as a constant that cannot be reassigned. The `final` keyword is similar to the `const` keyword but enforces immutability more strictly. + + For example: + + ```java title="Final State Example" + final int x = 10; + x = 20; // Error: Cannot assign a value to a final variable + ``` + +7. **Record and Tuple**: ES2022 introduced the `record` and `tuple` types, which are new built-in types in JavaScript. The `record` type is an object type with a fixed set of properties, while the `tuple` type is an array type with a fixed number of elements and element types. + + For example: + + ```javascript title="Record and Tuple Example" + let person: record { name: string, age: number } = { name: "Alice", age: 30 }; + let pair: tuple [string, number] = ["Alice", 30]; + ``` + +8. **Private Fields**: ES2022 introduced private fields, which allow you to define private instance fields in classes. Private fields are not accessible from outside the class and are intended for internal use within the class. + + For example: + + ```javascript title="Private Fields Example" + class Person { + #name; + + constructor(name) { + this.#name = name; + } + + getName() { + return this.#name; + } + } + + let person = new Person("Alice"); + console.log(person.#name); // Error: Private field '#name' is not accessible outside class 'Person' + console.log(person.getName()); // Output: 'Alice' + ``` + +## Browser Support for ES2022 + +Most modern web browsers support ES2022 features, but some older browsers may not fully support all ES2022 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2022 code into ES5 code, which is compatible with older browsers. + +In this tutorial, we learned about the new features introduced in the ES2022 version of JavaScript (ECMAScript 2022) and how to use them in your JavaScript code. ES2022 introduced several new features and enhancements to JavaScript, such as `String.prototype.replaceAll()`, logical assignment operators, numeric separators, `WeakRef`, `Promise.any()`, `final` keyword, `record` and `tuple` types, and private fields. These features can help you write more expressive and efficient JavaScript code. + +You can start using these features in your JavaScript code to take advantage of the latest enhancements in the language. For more information on browser support for ES2022 features, you can check the compatibility tables provided by [Can I use](https://caniuse.com/). + +## Conclusion + +ES2022 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we learned about the new features introduced in ES2022, such as `String.prototype.replaceAll()`, logical assignment operators, numeric separators, `WeakRef`, `Promise.any()`, `final` keyword, `record` and `tuple` types, and private fields. These features can help you write more expressive and efficient JavaScript code. You can start using these features in your JavaScript code to take advantage of the latest enhancements in the language. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-2023.md b/docs/javascript/js-versions/js-2023.md new file mode 100644 index 000000000..36a514f00 --- /dev/null +++ b/docs/javascript/js-versions/js-2023.md @@ -0,0 +1,10 @@ +--- +id: es2023-version-of-javascript +title: JavaScript ES2023 Version (2023) +sidebar_label: ES2023 Version (2023) +sidebar_position: 9 +tags: [JavaScript, ES2023, ECMAScript 2023, JavaScript ES2023, JavaScript ES2023, JavaScript ES2023 Version, JavaScript ES2023 Version] +description: "In this tutorial, we will learn about the ES2023 version of JavaScript, also known as ECMAScript 2023. We will discuss the new features introduced in ES2023 and how to use them in your JavaScript code." +--- + +JavaScript ES2023 (ECMAScript 2023) is the twelfth major release of the JavaScript language specification. It is expected to be finalized in June 2023. ES2023 is expected to introduce several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2023 and how to use them in your JavaScript code. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-es5.md b/docs/javascript/js-versions/js-es5.md new file mode 100644 index 000000000..d1184398e --- /dev/null +++ b/docs/javascript/js-versions/js-es5.md @@ -0,0 +1,233 @@ +--- +id: es5-version-of-javascript +title: ES5 Version of JavaScript +sidebar_label: ES5 Version (2009) +sidebar_position: 1 +tags: [JavaScript, ES5, ES5 Version of JavaScript, ES5 JavaScript, ES5 JavaScript Tutorial, ES5 JavaScript Example, ES5 JavaScript Features, ES5 JavaScript Improvements, ES5 JavaScript Development, ES5 JavaScript Changes, ES5 JavaScript New Features, ES5 JavaScript Tutorial for Beginners, ES5 JavaScript Tutorial for Developers, ES5 JavaScript Tutorial Example, ES5 JavaScript Tutorial Features, ES5 JavaScript Tutorial Improvements, ES5 JavaScript Tutorial Changes, ES5 JavaScript Tutorial New Features, ES5 JavaScript Tutorial Development, ES5 JavaScript Tutorial Beginners, ES5 JavaScript Tutorial Developers, ES5 JavaScript Tutorial Example, ES5 JavaScript Tutorial Features, ES5 JavaScript Tutorial Improvements, ES5 JavaScript Tutorial Changes, ES5 JavaScript Tutorial New Features, ES5 JavaScript Tutorial Development] +description: "In this tutorial, we will learn about the ES5 version of JavaScript, which was released in 2009. We will explore the new features and improvements introduced in ES5 and how they have impacted JavaScript development." +--- + +JavaScript ES5 (ECMAScript 5) is the fifth edition of the ECMAScript standard, which was released in 2009. It introduced several new features and improvements to the language, making it more powerful and flexible for developers. In this tutorial, we will learn about the ES5 version of JavaScript and how it has impacted JavaScript development. + +## Features of ES5 + +### Strict Mode + +One of the key features introduced in ES5 is strict mode. Strict mode is a special mode that allows you to opt into a restricted variant of JavaScript that enforces stricter parsing and error handling. It helps you write more secure and optimized code by catching common coding mistakes and preventing certain actions that are considered bad practice. + +To enable strict mode in your code, you can add the following directive at the beginning of your script: + +```javascript title="Strict Mode in ES5" +"use strict"; + +function myFunction() { + console.log("This is a strict mode function"); +} + +myFunction(); +``` + +By using strict mode, you can avoid common pitfalls in JavaScript and write cleaner, more reliable code. + +### `JSON` Object + +ES5 introduced the `JSON` object, which provides methods for parsing and serializing JSON data. The `JSON` object includes two main methods: + +- `JSON.parse()`: Parses a JSON string and returns a JavaScript object. +- `JSON.stringify()`: Converts a JavaScript object into a JSON string. + - This method is useful for serializing data before sending it to a server or storing it in a database. + - It can also be used to pretty-print JSON data for debugging purposes. + - The `JSON.stringify()` method can take an optional `replacer` function or an array of properties to include or exclude from the serialization process. + - It can also take an optional `space` parameter to specify the indentation level for the output JSON string. + - The `JSON.stringify()` method can handle circular references by throwing an error or replacing the circular reference with a placeholder value. +- The `JSON` object also includes the `JSON.parse()` method, which can parse a JSON string and return a JavaScript object. +- The `JSON.parse()` method can take an optional `reviver` function to transform the parsed data before returning it. +- The `JSON.parse()` method can handle invalid JSON strings by throwing a `SyntaxError` or returning `null`. +- The `JSON.parse()` method can also handle duplicate keys by throwing a `SyntaxError` or using the last key-value pair encountered. + +Here is an example of using the `JSON` object to parse and stringify JSON data: + +```javascript title="JSON Object in ES5" +// Parsing JSON data +const jsonString = '{"name": "John", "age": 30}'; +const data = JSON.parse(jsonString); + +console.log(data.name); // John +console.log(data.age); // 30 + +// Stringifying JavaScript object +const person = { name: "Alice", age: 25 }; +const jsonData = JSON.stringify(person); + +console.log(jsonData); // {"name":"Alice","age":25} +``` + +### `Array` Methods + +ES5 introduced several new methods for the `Array` object, making it easier to work with arrays in JavaScript. Some of the key methods introduced in ES5 include: + +- `Array.prototype.forEach()`: Executes a provided function once for each array element. +- `Array.prototype.map()`: Creates a new array with the results of calling a provided function on every element in the array. +- `Array.prototype.filter()`: Creates a new array with all elements that pass a test implemented by the provided function. +- `Array.prototype.reduce()`: Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. +- `Array.prototype.some()`: Tests whether at least one element in the array passes the test implemented by the provided function. +- `Array.prototype.every()`: Tests whether all elements in the array pass the test implemented by the provided function. +- `Array.prototype.indexOf()`: Returns the first index at which a given element can be found in the array. +- `Array.prototype.lastIndexOf()`: Returns the last index at which a given element can be found in the array. +- `Array.prototype.reduceRight()`: Applies a function against an accumulator and each element in the array (from right to left) to reduce it to a single value. +- `Array.prototype.forEach()`: Executes a provided function once for each array element. +- `Array.prototype.map()`: Creates a new array with the results of calling a provided function on every element in the array. + +Here is an example of using the `Array` methods introduced in ES5: + +```javascript title="Array Methods in ES5" +const numbers = [1, 2, 3, 4, 5]; + +// Using forEach + +numbers.forEach((number) => { + console.log(number); +}); + +// Using map + +const doubledNumbers = numbers.map((number) => number * 2); +console.log(doubledNumbers); // [2, 4, 6, 8, 10] + +// Using filter + +const evenNumbers = numbers.filter((number) => number % 2 === 0); +console.log(evenNumbers); // [2, 4] + +// Using reduce + +const sum = numbers.reduce((accumulator, number) => accumulator + number, 0); +console.log(sum); // 15 +``` + +### `Function.prototype.bind()` + +ES5 introduced the `Function.prototype.bind()` method, which allows you to create a new function with a specified `this` value and initial arguments. This method is useful for creating functions with a fixed context, which can be helpful when working with event handlers or callbacks. + +Here is an example of using the `Function.prototype.bind()` method: + +```javascript title="Function.prototype.bind() in ES5" +const person = { + name: "Alice", + greet: function() { + console.log(`Hello, my name is ${this.name}`); + }, +}; + +const greetFunction = person.greet; +greetFunction(); // Hello, my name is undefined + +const boundGreetFunction = person.greet.bind(person); +boundGreetFunction(); // Hello, my name is Alice +``` + +### Getters and Setters + +ES5 introduced support for getters and setters in JavaScript objects. Getters are used to get the value of a property, while setters are used to set the value of a property. Getters and setters allow you to define computed properties and control access to object properties. + +Here is an example of using getters and setters in ES5: + +```javascript title="Getters and Setters in ES5" +const person = { + firstName: "John", + lastName: "Doe", + get fullName() { + return `${this.firstName} ${this.lastName}`; + }, + set fullName(value) { + const parts = value.split(" "); + this.firstName = parts[0]; + this.lastName = parts[1]; + }, +}; + +console.log(person.fullName); // John Doe + +person.fullName = "Alice Smith"; +console.log(person.firstName); // Alice +console.log(person.lastName); // Smith +``` + +### `Object.keys()` + +ES5 introduced the `Object.keys()` method, which returns an array of a given object's own enumerable property names. This method is useful for iterating over the properties of an object and accessing their values. + +Here is an example of using the `Object.keys()` method in ES5: + +```javascript title="Object.keys() in ES5" +const person = { + name: "John", + age: 30, +}; + +const keys = Object.keys(person); +console.log(keys); // ["name", "age"] + +keys.forEach((key) => { + console.log(`${key}: ${person[key]}`); +}); +``` + +### `Array.isArray()` + +ES5 introduced the `Array.isArray()` method, which checks whether a given value is an array. This method is useful for determining the type of a value and handling it accordingly. + +Here is an example of using the `Array.isArray()` method in ES5: + +```javascript title="Array.isArray() in ES5" +const numbers = [1, 2, 3, 4, 5]; + +console.log(Array.isArray(numbers)); // true + +const person = { + name: "Alice", + age: 25, +}; + +console.log(Array.isArray(person)); // false +``` + +## Browser Support for ES5 + +ES5 is supported by all modern web browsers, including Chrome, Firefox, Safari, Edge, and Opera. It is also supported by Internet Explorer 9 and later versions. Since ES5 was released in 2009, it is widely adopted and compatible with most web development environments. + +By using ES5 features in your JavaScript code, you can ensure better compatibility with a wide range of browsers and devices. ES5 provides a solid foundation for building web applications and enables you to write more efficient and maintainable code. + +### Compatibility Table for ES5 + +Here is a compatibility table showing the support for ES5 features in modern web browsers: + +| Feature | Chrome | Firefox | Safari | Edge | Opera | IE | +|-----------------------|--------|---------|--------|------|-------|-------| +| Strict Mode | 5 | 4 | 5 | 12 | 12 | 9 | +| `JSON` Object | 3 | 3.5 | 4 | 8 | 10.5 | 8 | +| `Array` Methods | 5 | 4 | 5 | 12 | 12 | 9 | +| `Function.prototype.bind()` | 7 | 4 | 5 | 12 | 12 | 9 | +| Getters and Setters | 3 | 2 | 5 | 12 | 12 | 9 | +| `Object.keys()` | 5 | 4 | 5 | 12 | 12 | 9 | +| `Array.isArray()` | 5 | 4 | 5 | 12 | 12 | 9 | +| `Array.prototype.forEach()` | 1 | 1.5 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.map()` | 1 | 1.5 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.filter()` | 1 | 1.5 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.reduce()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.some()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.every()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.indexOf()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.lastIndexOf()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.reduceRight()` | 1 | 3 | 5 | 12 | 10.5 | 9 | + +:::info Note +The version numbers in the compatibility table represent the first stable release of the browser that supports the feature. For example, Chrome 5 indicates that the feature is supported in Chrome version 5 and later. + +> The version numbers in the compatibility table represent the first stable version that supports the feature. The compatibility data is based on [Can I use](https://caniuse.com/) and [MDN Web Docs](https://developer.mozilla.org/). + +::: + +## Conclusion + +In this tutorial, we learned about the ES5 version of JavaScript, which introduced several new features and improvements to the language. We explored the key features of ES5, including strict mode, the `JSON` object, new `Array` methods, `Function.prototype.bind()`, getters and setters, `Object.keys()`, and `Array.isArray()`. We also discussed the browser support for ES5 and how it has impacted JavaScript development. By understanding the features of ES5, you can write more efficient and maintainable JavaScript code for your web applications. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-es6.md b/docs/javascript/js-versions/js-es6.md new file mode 100644 index 000000000..39dea7d67 --- /dev/null +++ b/docs/javascript/js-versions/js-es6.md @@ -0,0 +1,83 @@ +--- +id: es6-version-of-javascript +title: ES6 Version in JavaScript +sidebar_label: ES6 Version (2015) +sidebar_position: 2 +tags: [JavaScript, ES6, ES2015, ES6 Version, ECMAScript 6, ECMAScript 2015, JavaScript ES6, JavaScript ES2015, JavaScript ES6 Version, JavaScript ES2015 Version] +description: "In this tutorial, we will learn about the ES6 version of JavaScript, also known as ECMAScript 6 or ECMAScript 2015. We will discuss the new features introduced in ES6 and how to use them in your JavaScript code." +--- + +JavaScript ES6 (ECMAScript 6) is the sixth major release of the JavaScript language specification. It was finalized in June 2015. ES6 introduced many new features and syntax enhancements to JavaScript, making it more powerful and expressive. In this tutorial, we will learn about the new features introduced in ES6 and how to use them in your JavaScript code. + +## Features of ES6 + +ES6 introduced several new features and enhancements to JavaScript. Some of the key features of ES6 are: + +1. **`let` and `const` Declarations**: ES6 introduced two new ways to declare variables in JavaScript: `let` and `const`. The `let` keyword is used to declare block-scoped variables, while the `const` keyword is used to declare variables whose values cannot be reassigned. +2. **Arrow Functions**: Arrow functions are a new way to define functions in JavaScript. They provide a more concise syntax for writing function expressions. +3. **Template Literals**: Template literals are a new way to define strings in JavaScript. They allow you to embed expressions and variables inside a string using `${}`. +4. **Destructuring Assignment**: Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a single statement. +5. **Spread and Rest Operators**: ES6 introduced the spread (`...`) and rest (`...`) operators. The spread operator allows you to expand an array or object into individual elements, while the rest operator allows you to collect multiple elements into an array or object. +6. **Classes**: ES6 introduced a new way to define classes in JavaScript using the `class` keyword. Classes provide a more familiar and concise syntax for defining object-oriented programming concepts. +7. **Modules**: ES6 introduced a new module system for JavaScript using the `import` and `export` keywords. Modules allow you to split your code into multiple files and import/export functionality between them. +8. **Promises**: Promises are a new way to work with asynchronous code in JavaScript. They provide a cleaner and more readable syntax for handling asynchronous operations. +9. **Generators**: Generators are a new type of function in JavaScript that can be paused and resumed. They are useful for writing asynchronous code in a synchronous style. +10. **Default Parameters**: ES6 introduced default parameter values for functions. Default parameters allow you to specify default values for function parameters if no value is provided. +11. **Enhanced Object Literals**: ES6 introduced several enhancements to object literals, such as shorthand property and method definitions, computed property names, and method definition shorthand. +12. **Map and Set Data Structures**: ES6 introduced two new data structures: `Map` and `Set`. `Map` is a collection of key-value pairs, while `Set` is a collection of unique values. +13. **Symbols**: Symbols are a new primitive data type in JavaScript introduced in ES6. They are unique and immutable values that can be used as object keys. +14. **Iterators and Iterables**: ES6 introduced the concept of iterators and iterables. Iterators are objects that define a sequence of values, while iterables are objects that can be iterated over using the `for...of` loop. +15. **Typed Arrays**: ES6 introduced a new way to work with binary data in JavaScript using typed arrays. Typed arrays allow you to work with raw binary data in a more efficient way. +16. **New String Methods**: ES6 introduced several new methods for working with strings, such as `startsWith()`, `endsWith()`, `includes()`, and `repeat()`. +17. **New Array Methods**: ES6 introduced several new methods for working with arrays, such as `find()`, `findIndex()`, `some()`, and `every()`. +18. **New Number Methods**: ES6 introduced several new methods for working with numbers, such as `isFinite()`, `isNaN()`, and `isInteger()`. +19. **New Math Methods**: ES6 introduced several new methods for working with mathematical operations, such as `Math.sign()`, `Math.trunc()`, and `Math.cbrt()`. +20. **New Object Methods**: ES6 introduced several new methods for working with objects, such as `Object.assign()`, `Object.keys()`, `Object.values()`, and `Object.entries()`. +21. **New Reflect API**: ES6 introduced a new set of reflection methods for working with objects, such as `Reflect.get()`, `Reflect.set()`, and `Reflect.construct()`. +22. **New Proxy API**: ES6 introduced a new set of proxy methods for creating and handling proxies, which are objects that intercept and customize the behavior of fundamental operations on other objects. +23. **Internationalization and Localization**: ES6 introduced new features for working with internationalization and localization, such as the `Intl` object and the `Intl.Collator`, `Intl.DateTimeFormat`, and `Intl.NumberFormat` classes. +24. **Tail Call Optimization**: ES6 introduced tail call optimization, which allows JavaScript engines to optimize recursive functions that are tail calls, making them more memory-efficient. +25. **Other Features**: ES6 introduced many other features and enhancements, such as binary and octal literals, new syntax for promises, and new syntax for regular expressions. + +## Browser Support for ES6 + +Most modern web browsers support ES6 features, but some older browsers may not fully support all ES6 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES6 code into ES5 code, which is compatible with older browsers. + +## Using ES6 Features + +To use ES6 features in your JavaScript code, you can write your code using ES6 + +```javascript title="ES6 Code Example" +// ES6 code +const greet = (name) => { + return `Hello, ${name}!`; +}; + +console.log(greet("Alice")); +``` + +You can also use a transpiler like Babel to convert your ES6 code into ES5 code. To do this, you can install Babel using + +```bash npm2yarn +npm install --save-dev @babel/core @babel/cli @babel/preset-env +``` + +Then, you can create a `.babelrc` file in your project directory with the following configuration + +```json title=".babelrc" +{ + "presets": ["@babel/preset-env"] +} +``` + +Finally, you can transpile your ES6 code into ES5 code using + +```bash title="Transpile ES6 to ES5 using Babel" +npx babel src --out-dir dist +``` + +By using Babel, you can write modern ES6 code and ensure that it works across all browsers. + +## Conclusion + +ES6 introduced many new features and enhancements to JavaScript, making it more powerful and expressive. In this tutorial, we learned about the key features of ES6 and how to use them in your JavaScript code. By using ES6 features, you can write cleaner, more readable, and more maintainable JavaScript code. \ No newline at end of file diff --git a/docs/javascript/js-versions/js-history.md b/docs/javascript/js-versions/js-history.md new file mode 100644 index 000000000..11e58dbf8 --- /dev/null +++ b/docs/javascript/js-versions/js-history.md @@ -0,0 +1,96 @@ +--- +id: javascript-history +title: JavaScript Versions History +sidebar_label: JS History +sidebar_position: 10 +tags: [JavaScript, JavaScript Versions, ECMAScript, JavaScript History, JavaScript Versions History] +description: "In this tutorial, we will explore the history of JavaScript versions, starting from the initial release in 1995 to the latest version. We will discuss the key features introduced in each version and the evolution of the JavaScript language over the years." +--- + +JavaScript is a versatile and powerful programming language that has evolved significantly since its inception in 1995. Over the years, JavaScript has undergone several major revisions, introducing new features and enhancements to the language. In this tutorial, we will explore the history of JavaScript versions, starting from the initial release in 1995 to the latest version. We will discuss the key features introduced in each version and the evolution of the JavaScript language over the years. + +## JavaScript Versions + +### 1. JavaScript 1.0 (1995) + +JavaScript was first introduced in 1995 by Brendan Eich at Netscape Communications. The initial version of JavaScript, known as JavaScript 1.0, was released in the same year. JavaScript 1.0 included the core features of the language, such as variables, functions, loops, and conditional statements. + +### 2. JavaScript 1.1 (1996) + +JavaScript 1.1 was released in 1996 and introduced several new features, including support for regular expressions, better error handling, and improved performance. This version also added support for the `let` statement and the `const` statement for declaring variables. + +### 3. JavaScript 1.2 (1997) + +JavaScript 1.2 was released in 1997 and introduced several new features, such as support for `do-while` loops, the `switch` statement, and the `for-in` loop. This version also added support for the `eval()` function for evaluating JavaScript code dynamically. + +### 4. JavaScript 1.3 (1998) + +JavaScript 1.3 was released in 1998 and introduced several new features, including support for regular expressions, better error handling, and improved performance. This version also added support for the `let` statement and the `const` statement for declaring variables. + +### 5. JavaScript 1.4 (1999) + +JavaScript 1.4 was released in 1999 and introduced several new features, such as support for `do-while` loops, the `switch` statement, and the `for-in` loop. This version also added support for the `eval()` function for evaluating JavaScript code dynamically. + +### 6. JavaScript 1.5 (2000) + +JavaScript 1.5 was released in 2000 and introduced several new features, including support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 7. JavaScript 1.6 (2005) + +JavaScript 1.6 was released in 2005 and introduced several new features, such as support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 8. JavaScript 1.7 (2006) + +JavaScript 1.7 was released in 2006 and introduced several new features, such as support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 9. JavaScript 1.8 (2008) + +JavaScript 1.8 was released in 2008 and introduced several new features, such as support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 10. ECMAScript 5 (2009) + +ECMAScript 5 was released in 2009 and introduced several new features, such as strict mode, JSON support, and array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 11. ECMAScript 5.1 (2011) + +ECMAScript 5.1 was released in 2011 and introduced several new features, such as strict mode, JSON support, and array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 12. ECMAScript 6 (ES2015) + +ECMAScript 6, also known as ES2015, was released in 2015 and introduced several new features, such as arrow functions, classes, modules, template literals, and destructuring assignments. This version also added support for the `let` statement and the `const` statement for declaring variables. + +### 13. ECMAScript 7 (ES2016) + +ECMAScript 7, also known as ES2016, was released in 2016 and introduced several new features, such as the `includes()` method for arrays, the `**` operator for exponentiation, and the `async` and `await` keywords for handling asynchronous operations. + +### 14. ECMAScript 8 (ES2017) + +ECMAScript 8, also known as ES2017, was released in 2017 and introduced several new features, such as the `Object.values()` method, the `Object.entries()` method, and the `String.prototype.padStart()` and `String.prototype.padEnd()` methods for padding strings. + +### 15. ECMAScript 9 (ES2018) + +ECMAScript 9, also known as ES2018, was released in 2018 and introduced several new features, such as asynchronous iteration, the `Promise.prototype.finally()` method, and rest/spread properties for object literals and destructuring. + +### 16. ECMAScript 10 (ES2019) + +ECMAScript 10, also known as ES2019, was released in 2019 and introduced several new features, such as `Array.prototype.flat()` and `Array.prototype.flatMap()` methods, the `Object.fromEntries()` method, and the `String.prototype.trimStart()` and `String.prototype.trimEnd()` methods. + +### 17. ECMAScript 11 (ES2020) + +ECMAScript 11, also known as ES2020, was released in 2020 and introduced several new features, such as the `BigInt` data type for working with arbitrary precision integers, the `Promise.allSettled()` method, and the `String.prototype.matchAll()` method for working with regular expressions. + +### 18. ECMAScript 12 (ES2021) + +ECMAScript 12, also known as ES2021, was released in 2021 and introduced several new features, such as the `String.prototype.replaceAll()` method for replacing all occurrences of a substring, the `Logical Assignment Operators` for combining logical operations with assignment, and the `Numeric Separators` for improving the readability of numeric literals. + +### 19. ECMAScript 13 (ES2022) + +ECMAScript 13, also known as ES2022, was released in 2022 and introduced several new features, such as the `Array.prototype.groupBy()` method for grouping array elements based on a key, the `String.prototype.sliceSet()` method for replacing a slice of a string with another string, and the `Object.hasOwn()` method for checking if an object has a property. + +### 20. ECMAScript 14 (ES2023) + +ECMAScript 14, also known as ES2023, is the upcoming version of JavaScript that is expected to be released in 2023. It is expected to introduce several new features and enhancements to the language, building upon the foundation laid by previous versions. + +## Conclusion + +In this tutorial, we explored the history of JavaScript versions, starting from the initial release in 1995 to the latest version. We discussed the key features introduced in each version and the evolution of the JavaScript language over the years. JavaScript has come a long way since its inception and continues to evolve to meet the changing needs of developers and the web platform. \ No newline at end of file diff --git a/docs/javascript/json-js.md b/docs/javascript/json-js.md new file mode 100644 index 000000000..0fdc16cf0 --- /dev/null +++ b/docs/javascript/json-js.md @@ -0,0 +1,346 @@ +--- +id: json-in-javascript +title: JSON in JavaScript +sidebar_label: JSON +sidebar_position: 38 +tags: + [ + JavaScript, + JSON, + json-in-javascript, + json, + javascript-json, + javascript-json-tutorial, + json-tutorial, + json-in-javascript-tutorial, + json-in-javascript-example, + json-in-javascript-syntax, + json-in-javascript-usage, + json-in-javascript-usage-example, + json-in-javascript-usage-syntax, + json-in-javascript-usage-guide, + json-in-javascript-guide, + json-in-javascript-example, + json-in-javascript-example-guide, + json-in-javascript-example-tutorial, + json-in-javascript-tutorial-guide, + json-in-javascript-tutorial-example, + json-in-javascript-tutorial-syntax, + json-in-javascript-tutorial-usage, + json-in-javascript-tutorial-example-guide, + json-in-javascript-tutorial-usage-example, + json-in-javascript-tutorial-syntax-example, + json-in-javascript-tutorial-syntax-guide, + json-in-javascript-tutorial-syntax-usage, + json-in-javascript-tutorial-syntax-example-guide, + json-in-javascript-tutorial-syntax-guide-example, + json-in-javascript-tutorial-usage-example-guide, + json-in-javascript-tutorial-usage-guide-example, + json-in-javascript-tutorial-example-usage, + json-in-javascript-tutorial-example-syntax, + json-in-javascript-tutorial-example-guide-syntax, + json-in-javascript-tutorial-example-syntax-guide, + json-in-javascript-tutorial-example-usage, + json-in-javascript-tutorial-example-usage-guide, + json-in-javascript-tutorial-guide-example-syntax, + json-in-javascript-tutorial-guide-example-usage, + json-in-javascript-tutorial-guide-example-usage-syntax, + json-in-javascript-tutorial-guide-syntax-example, + json-in-javascript-tutorial-guide-syntax-usage, + json-in-javascript-tutorial-guide-syntax-usage-example, + json-in-javascript-tutorial-guide-usage-example, + ] +description: "In this tutorial, we will learn about JSON in JavaScript. JSON stands for JavaScript Object Notation. It is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate." +--- + +JSON stands for JavaScript Object Notation. It is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. + +**JSON is built on two structures:** + +1. A collection of key/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. +2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. + +These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures. + +**In JSON, they take on these forms:** + +1. An object is an unordered set of name/value pairs. An object begins with `{` (left brace) and ends with `}` (right brace). Each name is followed by `:` (colon) and the name/value pairs are separated by `,` (comma). +2. An array is an ordered collection of values. An array begins with `[` (left bracket) and ends with `]` (right bracket). Values are separated by `,` (comma). +3. A value can be a string in double quotes, a number, `true`, `false`, `null`, an object, or an array. These structures can be nested. +4. JSON is often used to exchange data between a server and a web application. + +In this tutorial, we will learn how to work with JSON in JavaScript. We will learn how to parse JSON data, stringify JSON data, and how to work with JSON objects and arrays in JavaScript. We will also learn how to convert JSON data to JavaScript objects and arrays and vice versa. We will also learn how to work with JSON data in JavaScript using the JSON object. We will also learn how to handle errors when working with JSON data in JavaScript. We will also learn how to work with JSON data in JavaScript using the fetch API. We will also learn how to work with JSON data in JavaScript using the XMLHttpRequest object. We will also learn how to work with JSON data in JavaScript using the jQuery library. We will also learn how to work with JSON data in JavaScript using the Axios library. + +## JSON Syntax + +JSON syntax is derived from JavaScript object notation syntax: + +1. Data is in name/value pairs. + + - Data is separated by commas. + - Curly braces hold objects. + - Square brackets hold arrays. + +
+ + ```js title="data.json" + { + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + } + ``` + +2. Data is in key/value pairs. + + - Keys must be strings. + - Values must be valid JSON data types. + - Each key/value pair is separated by a comma. + - The key is separated from the value by a colon. + +
+ + ```js title="data.json" + { + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + } + ``` + +3. JSON values can be: + + - A string. + - A number. + - An object (JSON object). + - An array. + - A boolean. + - `null`. + +## JSON Data Types + +JSON supports the following data types: + +1. **String**: A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslashes (`\`) to escape characters. + + ```js title="data.json" + { + "name": "Ajay Dhangar" + } + ``` + +2. **Number**: A number is a signed decimal number that may contain a fractional part and may use exponential `E` notation. + + ```js title="data.json" + { + "age": 23 + } + ``` + +3. **Object**: An object is an unordered collection of key/value pairs. + + ```js title="data.json" + { + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + } + ``` + +4. **Array**: An array is an ordered collection of values. + + ```js title="data.json" + { + "courses": ["Math", "Science", "English"] + } + ``` + +5. **Boolean**: A boolean is either `true` or `false`. + + ```js title="data.json" + { + "isStudent": true + } + ``` + +6. **Null**: A null value represents a `null` value. + + ```js title="data.json" + { + "address": null + } + ``` + +## JSON in JavaScript + +In JavaScript, you can work with JSON data using the following methods: + +1. **`JSON.parse()`**: The `JSON.parse()` method parses a JSON string and returns a JavaScript object. + + ```js title="JSON.parse() Example" + const jsonString = `{ + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + }`; + + const jsonObject = JSON.parse(jsonString); + + console.log(jsonObject); + ``` + +2. **`JSON.stringify()`**: The `JSON.stringify()` method converts a JavaScript object or value to a JSON string. + + ```js title="JSON.stringify() Example" + const jsonObject = { + name: "Ajay Dhangar", + age: 23, + isStudent: true, + courses: ["Math", "Science", "English"], + address: { + street: "Mandsaur, MP", + city: "Mandsaur", + state: "MP", + zip: "458002" + } + }; + + const jsonString = JSON.stringify(jsonObject); + + console.log(jsonString); // + + ``` + +3. **`JSON` Object**: The `JSON` object provides methods for working with JSON data. + + - `JSON.parse()`: Parses a JSON string and returns a JavaScript object. + - `JSON.stringify()`: Converts a JavaScript object or value to a JSON string. + +
+ + ```js title="JSON Object Example" + const jsonString = `{ + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + }`; + + const jsonObject = JSON.parse(jsonString); + + console.log(jsonObject); + + const jsonString = JSON.stringify(jsonObject); + + console.log(jsonString); + ``` + +4. **Fetch API**: The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. + + ```js title="Fetch API Example" + fetch('https://jsonplaceholder.typicode.com/posts') + .then(response => response.json()) + .then(data => console.log(data)) + .catch(error => console.error(error)); + ``` + +5. **XMLHttpRequest Object**: The `XMLHttpRequest` object is used to interact with servers. + + ```js title="XMLHttpRequest Object Example" + const xhr = new XMLHttpRequest(); + + xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true); + + xhr.onload = function () { + if (xhr.status >= 200 && xhr.status < 300) { + console.log(JSON.parse(xhr.responseText)); + } else { + console.error('Request failed with status:', xhr.status); + } + }; + + xhr.send(); + ``` + +6. **jQuery Library**: The jQuery library provides methods for working with JSON data. + + ```js title="jQuery Library Example" + $.getJSON('https://jsonplaceholder.typicode.com/posts', function(data) { + console.log(data); + }); + ``` + +7. **Axios Library**: The Axios library provides methods for working with JSON data. + + ```js title="Axios Library Example" + axios.get('https://jsonplaceholder.typicode.com/posts') + .then(response => console.log(response.data)) + .catch(error => console.error(error)); + ``` + +## JSON Error Handling + +When working with JSON data in JavaScript, you should handle errors to prevent your application from crashing. You can handle errors using the `try...catch` statement. + +```js title="Error Handling Example" +try { + const jsonString = `{ + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + }`; + + const jsonObject = JSON.parse(jsonString); + + console.log(jsonObject); +} catch (error) { + console.error(error); +} +``` + +In the above example, we are using the `try...catch` statement to handle errors when parsing JSON data. If an error occurs while parsing JSON data, the error will be caught and logged to the console. + +:::info Note +You should always handle errors when working with JSON data in JavaScript to prevent your application from crashing. +::: + +## Conclusion + +In this tutorial, we learned about JSON in JavaScript. We learned how to parse JSON data, stringify JSON data, and how to work with JSON objects and arrays in JavaScript. We also learned how to convert JSON data to JavaScript objects and arrays and vice versa. We also learned how to work with JSON data in JavaScript using the JSON object. We also learned how to handle errors when working with JSON data in JavaScript. We also learned how to work with JSON data in JavaScript using the fetch API. We also learned how to work with JSON data in JavaScript using the XMLHttpRequest object. We also learned how to work with JSON data in JavaScript using the jQuery library. We also learned how to work with JSON data in JavaScript using the Axios library. JSON is a powerful data interchange format that is widely used in web development. It is easy to read and write and easy to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages. JSON is built on two structures: A collection of key/value pairs and an ordered list of values. JSON is often used to exchange data between a server and a web application. It is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a universal data structure that is supported by virtually all modern programming languages. \ No newline at end of file diff --git a/docs/javascript/let-js.md b/docs/javascript/let-js.md new file mode 100644 index 000000000..ab919bad6 --- /dev/null +++ b/docs/javascript/let-js.md @@ -0,0 +1,110 @@ +--- +id: let-in-javascript +title: Let Keyword in JavaScript +sidebar_label: Let Keyword +sidebar_position: 8 +tags: [JavaScript, let, ES6, Variables, Block Scope, Hoisting, Redeclaration] +description: What is the let keyword in JavaScript and how to use it. +--- + +In JavaScript, the `let` keyword is used to declare a block-scoped variable. It was introduced in ECMAScript 6 (ES6) and is the preferred way to declare variables in modern JavaScript. + +> ***ES6 (ECMAScript 2015) is a major update to JavaScript that adds new syntax and features to the language. It was officially released in June 2015.*** + +## Syntax + +The syntax to declare a variable using the `let` keyword is: + +```js title="Syntax" +let variableName = value; +``` + +Here, `variableName` is the name of the variable and `value` is the value assigned to the variable. + +## Example + +Let's see an example to understand how to use the `let` keyword in JavaScript: + +```js title="Example" +let name = "John"; +console.log(name); // Output: John +``` + +In the above example, we have declared a variable `name` using the `let` keyword and assigned it a value `"John"`. We then printed the value of the variable using `console.log()`. + +## Block Scope + +The `let` keyword is block-scoped, which means that the variable declared using `let` is only available within the block in which it is defined. + +```js title="Block Scope" +{ + let x = 10; + console.log(x); // Output: 10 +} + +console.log(x); // Uncaught ReferenceError: x is not defined +``` + +In the above example, the variable `x` is only available within the block in which it is defined. If we try to access it outside the block, it will result in a `ReferenceError`. + +## Redeclaration + +The `let` keyword does not allow redeclaration of the same variable within the same block scope. + +```js title="Redeclaration" +let x = 10; +let x = 20; // Uncaught SyntaxError: Identifier 'x' has already been declared +``` + +In the above example, we are trying to redeclare the variable `x` within the same block scope, which results in a `SyntaxError`. + +## Hoisting + +Variables declared using the `let` keyword are not hoisted to the top of their block. This means that you cannot access the variable before it is declared. + +```js title="Hoisting" +console.log(x); // Uncaught ReferenceError: x is not defined +let x = 10; +``` + +In the above example, we are trying to access the variable `x` before it is declared, which results in a `ReferenceError`. + +## Comparison with var + +The `let` keyword differs from the `var` keyword in terms of block scope, redeclaration, and hoisting. + +### Block Scope + +Variables declared using the `var` keyword are function-scoped or globally-scoped, whereas variables declared using the `let` keyword are block-scoped. + +```js title="Block Scope" +// var +function varExample() { + if (true) { + var x = 10; + } + console.log(x); // Output: 10 +} + +varExample(); + +// let +function letExample() { + if (true) { + let x = 10; + } + console.log(x); // Uncaught ReferenceError: x is not defined +} + +letExample(); +``` + +In the above example, the variable `x` declared using the `var` keyword is available outside the block in which it is defined, whereas the variable `x` declared using the `let` keyword is not available outside the block. + +:::info +A block is a set of statements enclosed in curly braces `{}`. +::: + +## Conclusion + +In this article, we learned about the `let` keyword in JavaScript and how to use it to declare block-scoped variables. We also saw how the `let` keyword differs from the `var` keyword in terms of block scope, redeclaration, and hoisting. \ No newline at end of file diff --git a/docs/javascript/maps.md b/docs/javascript/maps.md new file mode 100644 index 000000000..2342b2018 --- /dev/null +++ b/docs/javascript/maps.md @@ -0,0 +1,863 @@ +--- +id: map-in-javascript +title: Maps in JavaScript +sidebar_label: Maps +sidebar_position: 27 +tags: + [ + JavaScript, + Map, + Data Structure, + Collection, + Key, + Value, + Pairs, + Iteration, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about maps in JavaScript. We will learn how to use maps to store key-value pairs in JavaScript." +--- + +In JavaScript, a `Map` is a built-in object that allows you to store key-value pairs. It is often used when you want to store a collection of key-value pairs and access them by their keys. + +## Creating a Map + +You can create a new `Map` by using the `new` keyword followed by the `Map` constructor. You can pass an iterable + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +console.log(map); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +- The `Map` constructor creates a new `Map` object. +- You can pass an iterable (such as an array of key-value pairs) to the `Map` constructor to initialize the map with the key-value pairs from the iterable. +- The `Map` object stores key-value pairs, so any duplicate keys will be overwritten. +- The order of elements in a `Map` is guaranteed to be the same as the order of insertion. +- The `Map` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. +- The `Map` object has a `size` property that returns the number of key-value pairs in the map. +- The `Map` object has methods to add, delete, and check for the presence of key-value pairs. +- The `Map` object does not have methods to access key-value pairs by index, as it does not maintain the order of elements. +- The `Map` object can store any type of key or value, including objects, functions, and other maps. +- The `Map` object can store key-value pairs with the same key, as it uses the `===` operator to compare keys. +- The `Map` object can store key-value pairs with `NaN` as the key, as it uses the `===` operator to compare keys. + +## Adding Key-Value Pairs to a Map + +You can add key-value pairs to a `Map` by using the `set` method. + +```js title="app.js" +const map = new Map(); +map.set("name", "John"); +map.set("age", 23); +map.set("person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}); +console.log(map); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +In this example, the `set` method is used to add key-value pairs to the map. The first argument to the `set` method is the key, and the second argument is the value. + +- The `set` method is used to add a new key-value pair to the map. +- If the key is already present in the map, its value will be updated with the new value. +- The `set` method returns the `Map` object, so you can chain multiple `set` calls together. +- The `set` method can store any type of key or value, including objects, functions, and other maps. +- The `set` method can store key-value pairs with the same key, as it uses the `===` operator to compare keys. +- The `set` method can store key-value pairs with `NaN` / `undefined` as the key, as it uses the `===` operator to compare keys. + +## Deleting Key-Value Pairs from a Map + +You can delete key-value pairs from a `Map` by using the `delete` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +map.delete("age"); + +console.log(map); // Map { 'name' => 'John', 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +In this example, the `delete` method is used to remove the key-value pair with the key `"age"` from the map. The `delete` method returns `true` if the key-value pair is removed, and `false` otherwise. + +- The `delete` method is used to remove a key-value pair from the map. +- If the key is present in the map, the key-value pair will be removed, and the method will return `true`. +- If the key is not present in the map, the method will return `false`. +- The `delete` method does not throw an error if the key is not present in the map. +- The `delete` method does not return the removed key-value pair. +- The `delete` method is chainable, so you can remove multiple key-value pairs from the map in a single statement. +- The `delete` method can be used to remove key-value pairs with `NaN` / `undefined` as the key, as it uses the `===` operator to compare keys. +- The `delete` method can be used to remove key-value pairs with the same key, as it uses the `===` operator to compare keys. + +## Checking for the Presence of a Key in a Map + +You can check if a key is present in a `Map` by using the `has` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +console.log(map.has("age")); // true +``` + +In this example, the `has` method is used to check if the key `"age"` is present in the map. If the key is present, the method will return `true`; otherwise, it will return `false`. + +- The `has` method is used to check if a key is present in the map. +- If the key is present in the map, the method will return `true`. +- If the key is not present in the map, the method will return `false`. +- The `has` method does not throw an error if the key is not present in the map. +- The `has` method does not return the key itself. +- The `has` method is often used to check if a key is present in the map before adding or deleting it. +- The `has` method can be used to check for the presence of `NaN` / `undefined` as the key, as it uses the `===` operator to compare keys. +- The `has` method can be used to check for the presence of the same key, as it uses the `===` operator to compare keys. +- The `has` method can be used to check for the presence of a key with a value of `undefined`. + +## Iterating Over a Map + +You can iterate over the key-value pairs of a `Map` by using a `for...of` loop. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const [key, value] of map) { + console.log(key + ": " + value); +} +``` + +The `for...of` loop is used to iterate over the key-value pairs of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `[key, value]`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Iterating Over the Keys of a Map + +You can iterate over the keys of a `Map` by using the `keys` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key of map.keys()) { + console.log(key); +} +``` + +The `keys` method is used to iterate over the keys of the map. In each iteration, the value of the current key is assigned to the loop variable `key`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key of the current key-value pair is printed to the console. + +## Iterating Over the Values of a Map + +You can iterate over the values of a `Map` by using the `values` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const value of map.values()) { + console.log(value); +} +``` + +The `values` method is used to iterate over the values of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `value`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +John +23 +[object Object] +``` + +In each iteration, the value of the current key-value pair is printed to the console. + +## Converting a Map to an Array + +You can convert a `Map` to an array by using the `Array.from` method or the spread operator (`...`). + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const array = Array.from(map); + +console.log(array); // [ [ 'name', 'John' ], [ 'age', 23 ], [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] ] +``` + +- The `Array.from` method is used to create a new array from an iterable (such as a `Map`). +- The `Array.from` method returns a new array that contains the key-value pairs of the map. +- The spread operator (`...`) can also be used to create a new array from an iterable. +- The spread operator (`...`) returns a new array that contains the key-value pairs of the map. +- The `Array.from` method and the spread operator (`...`) can be used to convert a `Map` to an array of key-value pairs. +- The `Array.from` method and the spread operator (`...`) can be used to convert a `Map` to an array of keys or values. + +## Using the Map Constructor + +You can use the `Map` constructor to create an empty `Map` and then add key-value pairs to it. + +```js title="app.js" +const map = new Map(); +map.set("name", "John"); +map.set("age", 23); +map.set("person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}); + +console.log(map); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +The `Map` constructor creates a new empty `Map` object. You can then use the `set` method to add key-value pairs to the map. The `Map` object stores key-value pairs, so any duplicate keys will be overwritten. + +## Using the Spread Operator + +You can use the spread operator (`...`) to create a new `Map` from an existing `Map`. + +```js title="app.js" +const map1 = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const map2 = new Map([...map1]); + +console.log(map2); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +The spread operator (`...`) is used to create a new `Map` from an existing `Map`. The new `Map` contains the key-value pairs of the existing `Map`. + +## Using the `forEach` Method + +You can use the `forEach` method to iterate over the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +map.forEach((value, key) => { + console.log(key + ": " + value); +}); +``` + +The `forEach` method is used to iterate over the key-value pairs of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `value`, and the key is assigned to the loop variable `key`. The loop body is executed for each key-value pair. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Using the `clear` Method + +You can use the `clear` method to remove all key-value pairs from a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +map.clear(); + +console.log(map); // Map {} +``` + +The `clear` method is used to remove all key-value pairs from the map. After calling the `clear` method, the map will be empty. + +The `clear` method does not return any value. + +The `clear` method can be used to remove all key-value pairs from the map in a single statement. + +## Using the `size` Property + +You can use the `size` property to get the number of key-value pairs in a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +console.log(map.size); // 3 +``` + +The `size` property returns the number of key-value pairs in the map. It can be used to get the size of the map in a single statement. + +The `size` property is read-only, so you cannot change its value. + +The `size` property can be used to get the number of key-value pairs in the map. + +## Using the `entries` Method + +You can use the `entries` method to get an iterator that contains the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map.entries(); + +console.log(iterator.next().value); // [ 'name', 'John' ] +console.log(iterator.next().value); // [ 'age', 23 ] +console.log(iterator.next().value); // [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] +``` + +The `entries` method returns an iterator that contains the key-value pairs of the map. You can use the `next` method of the iterator to get the next key-value pair. + +The `entries` method can be used to get an iterator that contains the key-value pairs of the map. + +The `entries` method can be used to iterate over the key-value pairs of the map. + +## Using the `keys` Method + +You can use the `keys` method to get an iterator that contains the keys of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map.keys(); + +console.log(iterator.next().value); // name +console.log(iterator.next().value); // age +console.log(iterator.next().value); // person +``` + +The `keys` method returns an iterator that contains the keys of the map. You can use the `next` method of the iterator to get the next key. + +The `keys` method can be used to get an iterator that contains the keys of the map. + +The `keys` method can be used to iterate over the keys of the map. + +## Using the `values` Method + +You can use the `values` method to get an iterator that contains the values of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map.values(); + +console.log(iterator.next().value); // John +console.log(iterator.next().value); // 23 +console.log(iterator.next().value); // { name: 'John', age: 23, greet: [Function: greet] } +``` + +The `values` method returns an iterator that contains the values of the map. You can use the `next` method of the iterator to get the next value. + +The `values` method can be used to get an iterator that contains the values of the map. + +The `values` method can be used to iterate over the values of the map. + +## Using the `Symbol.iterator` Property + +You can use the `Symbol.iterator` property to get an iterator that contains the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map[Symbol.iterator](); + +console.log(iterator.next().value); // [ 'name', 'John' ] +console.log(iterator.next().value); // [ 'age', 23 ] +console.log(iterator.next().value); // [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] +``` + +The `Symbol.iterator` property returns an iterator that contains the key-value pairs of the map. You can use the `next` method of the iterator to get the next key-value pair. + +The `Symbol.iterator` property can be used to get an iterator that contains the key-value pairs of the map. + +The `Symbol.iterator` property can be used to iterate over the key-value pairs of the map. + +## Using the `for...of` Loop + +You can use a `for...of` loop to iterate over the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const [key, value] of map) { + console.log(key + ": " + value); +} +``` + +The `for...of` loop is used to iterate over the key-value pairs of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `[key, value]`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Using the `for...of` Loop with the `entries` Method + +You can use a `for...of` loop to iterate over the key-value pairs of a `Map` by using the `entries` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const [key, value] of map.entries()) { + console.log(key + ": " + value); +} +``` + +The `for...of` loop is used to iterate over the key-value pairs of the map by using the `entries` method. In each iteration, the value of the current key-value pair is assigned to the loop variable `[key, value]`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Using the `for...of` Loop with the `keys` Method + +You can use a `for...of` loop to iterate over the keys of a `Map` by using the `keys` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key of map.keys()) { + console.log(key); +} +``` + +The `for...of` loop is used to iterate over the keys of the map by using the `keys` method. In each iteration, the value of the current key is assigned to the loop variable `key`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key of the current key-value pair is printed to the console. + +## Using the `for...of` Loop with the `values` Method + +You can use a `for...of` loop to iterate over the values of a `Map` by using the `values` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const value of map.values()) { + console.log(value); +} +``` + +The `for...of` loop is used to iterate over the values of the map by using the `values` method. In each iteration, the value of the current key-value pair is assigned to the loop variable `value`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +John +23 +[object Object] +``` + +In each iteration, the value of the current key-value pair is printed to the console. + +## Using the `for...in` Loop + +You can use a `for...in` loop to iterate over the keys of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key in map) { + console.log(key); +} +``` + +The `for...in` loop is used to iterate over the keys of the map. In each iteration, the value of the current key is assigned to the loop variable `key`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key of the current key-value pair is printed to the console. + +## Using the `hasOwnProperty` Method + +To check if the key is a direct property of the map and not inherited from its prototype chain, you can use the `hasOwnProperty` method. Here's an example: + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key in map) { + if (map.hasOwnProperty(key)) { + console.log(key); + } +} +``` + +In this example, the `hasOwnProperty` method is used to check if the key is a direct property of the map. If it is, the key is printed to the console. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key is checked if it is a direct property of the map. If it is, the key is printed to the console. + +## Using the `Array.from` Method + +You can use the `Array.from` method to convert a `Map` to an array of key-value pairs. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const array = Array.from(map); + +console.log(array); // [ [ 'name', 'John' ], [ 'age', 23 ], [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] ] +``` + +The `Array.from` method is used to create a new array from the map. The new array contains the key-value pairs of the map. + +The `Array.from` method can be used to convert a `Map` to an array of key-value pairs. + +The `Array.from` method can be used to convert a `Map` to an array of keys or values. + +:::info 📝 Note + +## Why Use Maps? + +Maps are often used when you want to store a collection of key-value pairs and access them by their keys. They are more flexible than objects, as they can store any type of key or value, including objects, functions, and other maps. They can also store key-value pairs with the same key, as they use the `===` operator to compare keys. + +## Benefits of Using Maps + +- Maps are iterable, so you can use them in a `for...of` loop to iterate over their elements. +- Maps have a `size` property that returns the number of key-value pairs in the map. +- Maps have methods to add, delete, and check for the presence of key-value pairs. +- Maps do not have methods to access key-value pairs by index, as they do not maintain the order of elements. +- Maps can store any type of key or value, including objects, functions, and other maps. +- Maps can store key-value pairs with the same key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `NaN` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `undefined` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `null` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `0` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `false` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with an empty string as the key, as they use the `===` operator to compare keys. + +## When to Use Maps + +- Use maps when you want to store a collection of key-value pairs and access them by their keys. +- Use maps when you want to store key-value pairs with the same key, as maps can store duplicate keys. +- Use maps when you want to store key-value pairs with `NaN` as the key, as maps can store `NaN` as the key. +- Use maps when you want to store key-value pairs with `undefined` as the key, as maps can store `undefined` as the key. +- Use maps when you want to store key-value pairs with `null` as the key, as maps can store `null` as the key. +- Use maps when you want to store key-value pairs with `0` as the key, as maps can store `0` as the key. +- Use maps when you want to store key-value pairs with `false` as the key, as maps can store `false` as the key. + +## When Not to Use Maps + +- Do not use maps when you want to access key-value pairs by index, as maps do not maintain the order of elements. +- Do not use maps when you want to store key-value pairs with the same key, as maps will overwrite the existing key-value pair. +- Do not use maps when you want to store key-value pairs with `NaN` as the key, as maps will treat `NaN` as the same key. +- Do not use maps when you want to store key-value pairs with `undefined` as the key, as maps will treat `undefined` as the same key. +- Do not use maps when you want to store key-value pairs with `null` as the key, as maps will treat `null` as the same key. +- Do not use maps when you want to store key-value pairs with `0` as the key, as maps will treat `0` as the same key. +- Do not use maps when you want to store key-value pairs with `false` as the key, as maps will treat `false` as the same key. + +::: + +## Summary + +In this tutorial, we learned about maps in JavaScript. We learned how to use maps to store key-value pairs in JavaScript. We also learned how to add, delete, and check for the presence of key-value pairs in a map. Finally, we learned how to iterate over the key-value pairs, keys, and values of a map. \ No newline at end of file diff --git a/docs/javascript/math.md b/docs/javascript/math.md new file mode 100644 index 000000000..2ac8cc615 --- /dev/null +++ b/docs/javascript/math.md @@ -0,0 +1,261 @@ +--- +id: math-in-javascript +title: Math in JavaScript +sidebar_label: Math +sidebar_position: 17 +tags: [JavaScript, Math, Object, Properties, Methods] +description: "In this tutorial, we will learn about the Math object in JavaScript. We will learn about the properties and methods of the Math object." +--- + +In JavaScript, the `Math` object is a built-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. + +## Properties + +The `Math` object has the following properties: + +- `Math.E`: Returns Euler's number, the base of natural logarithms, approximately 2.718. + + for example: + + ```js title="app.js" + console.log(Math.E); // 2.718281828459045 + ``` + +- `Math.PI`: Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159. + for example: + + ```js title="app.js" + console.log(Math.PI); // 3.141592653589793 + ``` + +- `Math.LN2`: Returns the natural logarithm of 2, approximately 0.693. + for example: + + ```js title="app.js" + console.log(Math.LN2); // 0.6931471805599453 + ``` + +- `Math.LN10`: Returns the natural logarithm of 10, approximately 2.303. + for example: + + ```js title="app.js" + console.log(Math.LN10); // 2.302585092994046 + ``` + +- `Math.LOG2E`: Returns the base 2 logarithm of E, approximately 1.442. + + for example: + + ```js title="app.js" + console.log(Math.LOG2E); // 1.4426950408889634 + ``` + +- `Math.LOG10E`: Returns the base 10 logarithm of E, approximately 0.434. + + for example: + + ```js title="app.js" + console.log(Math.LOG10E); // 0.4342944819032518 + ``` + +- `Math.SQRT1_2`: Returns the square root of 1/2, approximately 0.707. + + for example: + + ```js title="app.js" + console.log(Math.SQRT1_2); // 0.7071067811865476 + ``` + +- `Math.SQRT2`: Returns the square root of 2, approximately 1.414. + + for example: + + ```js title="app.js" + console.log(Math.SQRT2); // 1.4142135623730951 + ``` + +## Methods + +The `Math` object has the following methods: + +- `Math.abs(x)`: Returns the absolute value of a number. + + for example: + + ```js title="app.js" + console.log(Math.abs(-5)); // 5 + console.log(Math.abs(5)); // 5 + ``` + +- `Math.ceil(x)`: Returns the smallest integer greater than or equal to a number. + + for example: + + ```js title="app.js" + console.log(Math.ceil(5.1)); // 6 + console.log(Math.ceil(5.9)); // 6 + ``` + +- `Math.floor(x)`: Returns the largest integer less than or equal to a number. + + for example: + + ```js title="app.js" + console.log(Math.floor(5.1)); // 5 + console.log(Math.floor(5.9)); // 5 + ``` + +- `Math.round(x)`: Returns the value of a number rounded to the nearest integer. + + for example: + + ```js title="app.js" + console.log(Math.round(5.1)); // 5 + console.log(Math.round(5.9)); // 6 + ``` + +- `Math.max(x, y, z, ..., n)`: Returns the largest of zero or more numbers. + + for example: + + ```js title="app.js" + console.log(Math.max(5, 10, 15, 20)); // 20 + ``` + +- `Math.min(x, y, z, ..., n)`: Returns the smallest of zero or more numbers. + + for example: + + ```js title="app.js" + console.log(Math.min(5, 10, 15, 20)); // 5 + ``` + +- `Math.pow(x, y)`: Returns the value of x to the power of y. + + for example: + + ```js title="app.js" + console.log(Math.pow(2, 3)); // 8 + ``` + +- `Math.sqrt(x)`: Returns the square root of a number. + + for example: + + ```js title="app.js" + console.log(Math.sqrt(16)); // 4 + ``` + +- `Math.random()`: Returns a random number between 0 (inclusive), and 1 (exclusive). + + for example: + + ```js title="app.js" + console.log(Math.random()); // 0.123456789 + ``` + +- `Math.sin(x)`: Returns the sine of a number. + + for example: + + ```js title="app.js" + console.log(Math.sin(90)); // 0.8939966636005579 + ``` + +- `Math.cos(x)`: Returns the cosine of a number. + + for example: + + ```js title="app.js" + console.log(Math.cos(0)); // 1 + ``` + +- `Math.tan(x)`: Returns the tangent of a number. + + for example: + + ```js title="app.js" + console.log(Math.tan(45)); // 1.6197751905438615 + ``` + +- `Math.log(x)`: Returns the natural logarithm (base E) of a number. + + for example: + + ```js title="app.js" + console.log(Math.log(2)); // 0.6931471805599453 + ``` + +- `Math.exp(x)`: Returns the value of E^x. + + for example: + + ```js title="app.js" + console.log(Math.exp(2)); // 7.3890560989306495 + ``` + +- `Math.atan(x)`: Returns the arctangent of a number. + + for example: + + ```js title="app.js" + console.log(Math.atan(1)); // 0.7853981633974483 + ``` + +- `Math.acos(x)`: Returns the arccosine of a number. + + for example: + + ```js title="app.js" + console.log(Math.acos(0)); // 1.5707963267948966 + ``` + +- `Math.asin(x)`: Returns the arcsine of a number. + + for example: + + ```js title="app.js" + console.log(Math.asin(1)); // 1.5707963267948966 + ``` + +- `Math.atan2(y, x)`: Returns the arctangent of the quotient of its arguments. + + for example: + + ```js title="app.js" + console.log(Math.atan2(1, 1)); // 0.7853981633974483 + ``` + +- `Math.cosh(x)`: Returns the hyperbolic cosine of a number. + + for example: + + ```js title="app.js" + console.log(Math.cosh(0)); // 1 + ``` + +- `Math.sinh(x)`: Returns the hyperbolic sine of a number. + + for example: + + ```js title="app.js" + console.log(Math.sinh(0)); // 0 + ``` + +- `Math.tanh(x)`: Returns the hyperbolic tangent of a number. + + for example: + + ```js title="app.js" + console.log(Math.tanh(0)); // 0 + ``` + +:::tip 📝 Note + +The `Math` object is not a constructor. All properties and methods of the `Math` object can be called by using the `Math` object as a namespace. + +::: + +## Conclusion + +In this tutorial, we learned about the `Math` object in JavaScript. We learned about the properties and methods of the `Math` object. We also saw examples of how to use the `Math` object to perform mathematical tasks on numbers. \ No newline at end of file diff --git a/docs/javascript/mistakes-js.md b/docs/javascript/mistakes-js.md new file mode 100644 index 000000000..23ff5672a --- /dev/null +++ b/docs/javascript/mistakes-js.md @@ -0,0 +1,207 @@ +--- +id: mistakes-in-js +title: Mistakes in JavaScript +sidebar_label: Mistakes +sidebar_position: 42 +tags: [ JavaScript, Mistakes, Common Mistakes in JavaScript, JavaScript Mistakes, JavaScript Mistakes Tutorial, JavaScript Mistakes Example, JavaScript Mistakes to Avoid, JavaScript Common Mistakes, JavaScript Common Mistakes Tutorial, JavaScript Common Mistakes Example ] +description: "In this tutorial, we will learn about the common mistakes in JavaScript that developers make and how to avoid them. We will learn about the common pitfalls, bugs, and errors in JavaScript code and how to fix them." +--- + +JavaScript is a powerful and flexible language, but it is also easy to make mistakes while writing code. In this tutorial, we will learn about the common mistakes in JavaScript that developers make and how to avoid them. By understanding these mistakes and pitfalls, you can write better and more reliable JavaScript code. + +## Common Mistakes in JavaScript + +### Misunderstanding Variable Scope + +One common mistake in JavaScript is misunderstanding variable scope. JavaScript has function-level scope, which means that variables declared inside a function are only accessible within that function. If you declare a variable without the `var`, `let`, or `const` keyword, it becomes a global variable and is accessible throughout the entire script. This can lead to unintended side effects and bugs in your code. + + + + + ```javascript + function myFunction() { + let localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + + + ```javascript + function myFunction() { + localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + + +### Using `==` Instead of `===` + +Another common mistake in JavaScript is using the `==` operator instead of the `===` operator. The `==` operator performs type coercion, which means that it converts the operands to the same type before comparing them. This can lead to unexpected results and bugs in your code. The `===` operator, on the other hand, performs strict equality comparison, which means that it compares the operands without type coercion. + + + + + ```javascript + let x = 10; + let y = "10"; + + if (x === 10) { + console.log("x is equal to 10"); + } + + if (x === y) { + console.log("x is equal to y"); + } + ``` + + + + + ```javascript + let x = 10; + let y = "10"; + + if (x == 10) { + console.log("x is equal to 10"); + } + + if (x == y) { + console.log("x is equal to y"); + } + ``` + + + + +### Ignoring Asynchronous Code + +JavaScript is a single-threaded language, which means that it can only execute one piece of code at a time. Asynchronous code allows you to perform time-consuming tasks without blocking the main thread. One common mistake in JavaScript is ignoring asynchronous code and performing time-consuming tasks synchronously. This can lead to slow performance and unresponsive user interfaces. + + + + + ```javascript + function fetchData() { + fetch("https://api.github.com/users") + .then(response => response.json()) + .then(data => console.log(data)) + .catch(error => console.error(error)); + } + + fetchData(); // Fetch and log data asynchronously + ``` + + + + + ```javascript + function fetchData() { + let response = fetch("https://api.github.com/users"); + let data = response.json(); + console.log(data); + } + + fetchData(); // Fetch and log data synchronously + ``` + + + + +### Not Handling Errors + +Another common mistake in JavaScript is not handling errors properly. Errors can occur at any time in your code, and if they are not handled correctly, they can crash your application. It is important to use try-catch blocks or promise.catch() to catch and handle errors in your code. + + + + + ```javascript + async function fetchData() { + try { + let response = await fetch("https://api.github.com/users"); + let data = await response.json(); + console.log(data); + } catch (error) { + console.error("Error fetching data:", error); + } + } + + fetchData(); // Fetch and log data with error handling + + ``` + + + + + ```javascript + async function fetchData() { + let response = await fetch("https://api.github.com/users"); + let data = await response.json(); + console.log(data); + } + + fetchData(); // Fetch and log data without error handling + ``` + + + + +### Not Using Strict Mode + +Strict mode is a feature in JavaScript that helps you write cleaner and more secure code. It catches common coding mistakes and prevents certain actions that are considered bad practice. One common mistake in JavaScript is not using strict mode in your code. + + + + + ```javascript + "use strict"; + + // Code that follows strict mode + ``` + + + + + ```javascript + // Code that does not follow strict mode + ``` + + + + +### Not Using `let` and `const` + +Another common mistake in JavaScript is not using the `let` and `const` keywords to declare variables. The `let` keyword is used to declare block-scoped variables, while the `const` keyword is used to declare constants. Using `let` and `const` helps prevent unintended side effects and bugs in your code. + + + + + ```javascript + let x = 10; + const y = 20; + ``` + + + + + ```javascript + var x = 10; + y = 20; + + console.log(x); // 10 + console.log(y); // 20 + ``` + + + + +## Conclusion + +In this tutorial, we learned about the common mistakes in JavaScript that developers make and how to avoid them. By understanding these mistakes and pitfalls, you can write better and more reliable JavaScript code. We covered common mistakes such as misunderstanding variable scope, using `==` instead of `===`, ignoring asynchronous code, not handling errors, not using strict mode, and not using `let` and `const`. By avoiding these mistakes, you can write cleaner, more secure, and more efficient JavaScript code. \ No newline at end of file diff --git a/docs/javascript/modules-js.md b/docs/javascript/modules-js.md new file mode 100644 index 000000000..b751b22ad --- /dev/null +++ b/docs/javascript/modules-js.md @@ -0,0 +1,405 @@ +--- +id: modules-in-js +title: Modules in JavaScript +sidebar_label: Modules +sidebar_position: 37 +tags: + [ + JavaScript, + Modules, + ES6, + ES2015, + ES6 Features, + ES2015 Features, + ES6 Tutorials, + ES2015 Tutorials, + ES6 Tutorial, + ES2015 Tutorial, + ES6 Modules, + ES2015 Modules, + Modules in JavaScript, + Modules in ES6, + Modules in ES2015, + JavaScript Modules, + ES6 Modules Tutorial, + ES2015 Modules Tutorial, + Modules Tutorial, + Modules in JavaScript Tutorial, + Modules in ES6 Tutorial, + Modules in ES2015 Tutorial, + JavaScript Modules Tutorial, + ES6 Modules Example, + ES2015 Modules Example, + Modules Example, + Modules in JavaScript Example, + Modules in ES6 Example, + Modules in ES2015 Example, + JavaScript Modules Example, + ES6 Modules Syntax, + ES2015 Modules Syntax, + Modules Syntax, + Modules in JavaScript Syntax, + Modules in ES6 Syntax, + Modules in ES2015 Syntax, + JavaScript Modules Syntax, + ES6 Modules Syntax Example, + ES2015 Modules Syntax Example, + Modules Syntax Example, + Modules in JavaScript Syntax Example, + Modules in ES6 Syntax Example, + Modules in ES2015 Syntax Example, + JavaScript Modules Syntax Example, + ES6 Modules Syntax Tutorial, + ES2015 Modules Syntax Tutorial, + Modules Syntax Tutorial, + Modules in JavaScript Syntax Tutorial, + Modules in ES6 Syntax Tutorial, + Modules in ES2015 Syntax Tutorial, + JavaScript Modules Syntax Tutorial, + ES6 Modules Syntax Example Tutorial, + ES2015 Modules Syntax Example Tutorial, + Modules Syntax Example Tutorial, + Modules in JavaScript Syntax Example Tutorial, + Modules in ES6 Syntax Example Tutorial, + Modules in ES2015 Syntax Example Tutorial, + JavaScript Modules Syntax Example Tutorial, + ] +description: "In this tutorial, you will learn about modules in JavaScript, a new feature introduced in ES6 (ES2015) that allows you to organize your code into reusable pieces." +--- + +In JavaScript, modules are a new feature introduced in ES6 (ES2015) that allows you to organize your code into reusable pieces. Modules are a way to split your code into separate files and import/export the parts you need. + +In this tutorial, you will learn about modules in JavaScript with the help of examples. + +## Modules in JavaScript + +The syntax for importing and exporting modules in JavaScript is as follows: + + + + + ```js + // Exporting a variable + export const PI = 3.14159; + ``` + + + + + ```js + // Exporting a function + export function add(a, b) { + return a + b; + } + ``` + + + + + ```js + // Exporting a class + export class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + + greet() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } + } + ``` + + + + +```js +// Importing a variable +import { PI } from "./module1.js"; + +// Importing a function +import { add } from "./module2.js"; + +// Importing a class +import { Person } from "./module3.js"; + +console.log(PI); // Output: 3.14159 + +console.log(add(5, 3)); // Output: 8 + +const john = new Person("John", 30); + +console.log(john.greet()); // Output: Hello, my name is John and I am 30 years old. +``` + + + + + +In the example above, we have three modules: `module1.js`, `module2.js`, and `module3.js`, each exporting a variable, a function, and a class, respectively. The `app.js` file imports these modules and uses the exported values. + +Here's a breakdown of the example: + +1. `module1.js` exports a variable `PI` with the value `3.14159`. +2. `module2.js` exports a function `add` that takes two parameters and returns their sum. +3. `module3.js` exports a class `Person` with a constructor that initializes the `name` and `age` properties and a `greet` method that returns a greeting message. +4. `app.js` imports the exported values from the modules and uses them in the code. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +8 +Hello, my name is John and I am 30 years old. +``` + +This is how you can use modules in JavaScript to organize your code into reusable pieces. + +## Default Exports + +In addition to named exports, you can also use default exports in JavaScript modules. A default export is a single value that is exported from a module and can be imported without using curly braces `{}`. + +Here's an example of using default exports in JavaScript modules: + + + + +```js +// Default export +const PI = 3.14159; + +export default PI; +``` + + + + + +```js +// Default export +export default function add(a, b) { + return a + b; +} +``` + + + + + +```js +// Importing a default export +import PI from "./module1.js"; + +// Importing a default export +import add from "./module2.js"; + +console.log(PI); // Output: 3.14159 + +console.log(add(5, 3)); // Output: 8 +``` + + + + + +In this example, we have two modules: `module1.js` and `module2.js`, each exporting a single value using default exports. The `app.js` file imports these default exports without using curly braces `{}`. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +8 +``` + +This is how you can use default exports in JavaScript modules. + +## Multiple Exports and Imports in a Single Statement + +You can also export and import multiple values in a single statement using the `export` and `import` keywords. + +Here's an example of exporting and importing multiple values in a single statement: + + + + + +```js +// Exporting multiple values +export const PI = 3.14159; +export const E = 2.71828; +``` + + + + + +```js +// Exporting multiple values +export function add(a, b) { + return a + b; +} + +export function subtract(a, b) { + return a - b; +} +``` + + + + + +```js +// Importing multiple values +import { PI, E } from "./module1.js"; + +// Importing multiple values +import { add, subtract } from "./module2.js"; + +console.log(PI); // Output: 3.14159 +console.log(E); // Output: 2.71828 + +console.log(add(5, 3)); // Output: 8 + +console.log(subtract(5, 3)); // Output: 2 +``` + + + + + + +In this example, we have two modules: `module1.js` and `module2.js`, each exporting multiple values using the `export` keyword. The `app.js` file imports these multiple values in a single statement using the `import` keyword. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +2.71828 +8 +2 +``` + +This is how you can export and import multiple values in a single statement in JavaScript modules. + +:::info 📝 Note + +You can also use the `export * from 'module'` syntax to re-export all named exports from another module. This can be useful when you want to aggregate exports from multiple modules into a single module. + +For example: + + + + + +```js +// Exporting a variable +export const PI = 3.14159; +``` + + + + + +```js +// Exporting a variable +export const E = 2.71828; +``` + + + + + +```js +// Re-exporting named exports +export * from "./module1.js"; +export * from "./module2.js"; +``` + + + + + +```js +// Importing re-exported values +import { PI, E } from "./module.js"; + +console.log(PI); // Output: 3.14159 +console.log(E); // Output: 2.71828 +``` + + + + +In this example, we have two modules `module1.js` and `module2.js`, each exporting a variable. The `module.js` file re-exports the named exports from `module1.js` and `module2.js`. The `app.js` file imports the re-exported values from `module.js`. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +2.71828 +``` + +This is how you can re-export named exports from other modules in JavaScript. + +::: + +:::important + +When using modules in JavaScript, you need to be aware of the module system you are using. Common module systems include CommonJS, AMD, and ES6 modules. ES6 modules are the standard module system in modern JavaScript applications. + +If you are using a module in html file, you can use the `type="module"` attribute in the ` + + + + + +``` + +In this example, the `type="module"` attribute in the ` + + + ``` + + ```javascript title="script.js" + const container = document.getElementById("container"); + const fragment = document.createDocumentFragment(); + + for (let i = 0; i < 1000; i++) { + const div = document.createElement("div"); + div.textContent = `Element ${i}`; + fragment.appendChild(div); + } + + container.appendChild(fragment); + ``` + + + + ```html title="index.html" + + + + + + + Document + + +
+ + + + ``` + + ```javascript title="script.js" + const container = document.getElementById("container"); + + for (let i = 0; i < 1000; i++) { + const div = document.createElement("div"); + div.textContent = `Element ${i}`; + container.appendChild(div); + } + ``` +
+ + +### Avoid Memory Leaks + +Memory leaks can occur in JavaScript when objects are no longer needed but are still referenced, preventing them from being garbage collected. This can lead to increased memory usage and degraded performance over time. To avoid memory leaks, you should be mindful of object references and ensure that objects are properly cleaned up when they are no longer needed. + + + + + ```javascript + function createHeavyObject() { + const obj = { + /* heavy data */ + data: Array.from({ length: 1000000 }, () => Math.random()) + }; + return obj; + } + + let obj = createHeavyObject(); + + console.log(obj.data.length); // Use obj... + + obj = null; // Clean up obj + ``` + + + + ```javascript + function createHeavyObject() { + const obj = { + /* heavy data */ + data: Array.from({ length: 1000000 }, () => Math.random()) + }; + return obj; + } + + let obj = createHeavyObject(); + + console.log(obj.data.length); // Use obj... + ``` + + + +### Optimize Loops + +Loops are a common source of performance issues in JavaScript. Inefficient loops can slow down your code, especially when dealing with large datasets. To optimize loops, you should minimize the number of iterations, avoid unnecessary work inside the loop, and use appropriate loop constructs for the task at hand. + + + + + ```javascript + const data = [1, 2, 3, 4, 5]; + + for (let i = 0; i < data.length; i++) { + console.log(data[i]); + } + ``` + + + + ```javascript + const data = [1, 2, 3, 4, 5]; + + data.forEach(item => { + console.log(item); + }); + ``` + + + +### Use Event Delegation + +Event delegation is a technique in JavaScript that allows you to attach a single event listener to a parent element, rather than multiple event listeners to individual child elements. This can improve performance by reducing the number of event listeners and simplifying event handling. + + + + + ```html title="index.html" + + + + + + + Document + + +
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
+ + + + ``` + + ```javascript title="script.js" + const list = document.getElementById("list"); + + list.addEventListener("click", function(event) { + if (event.target.tagName === "LI") { + console.log(event.target.textContent); + } + }); + ``` +
+ + + ```html title="index.html" + + + + + + + Document + + +
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
+ + + + ``` + + ```javascript title="script.js" + const items = document.querySelectorAll("li"); + + items.forEach(item => { + item.addEventListener("click", function() { + console.log(item.textContent); + }); + }); + ``` +
+
+ +### Use Efficient Data Structures + +Choosing the right data structure can have a significant impact on the performance of your JavaScript code. For example, using an object for key-value pairs can be more efficient than an array for lookups, especially for large datasets. By selecting the appropriate data structure for your needs, you can optimize the performance of your code. + + + + + ```javascript + const data = { + key1: "value1", + key2: "value2", + key3: "value3" + }; + + console.log(data.key1); + ``` + + + + ```javascript + const data = ["value1", "value2", "value3"]; + + console.log(data[0]); + ``` + + + +### Avoid Global Variables + +Global variables can lead to performance issues in JavaScript, as they are accessible from anywhere in your code and can be modified by any part of your application. This can make it difficult to track changes and optimize performance. To avoid global variables, you should encapsulate your code in modules and use local variables whenever possible. + + + + + ```javascript + function myFunction() { + const localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + + ```javascript + function myFunction() { + localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + +### Use `===` Instead of `==` + +Another common mistake in JavaScript is using the `==` operator instead of the `===` operator. The `==` operator performs type coercion, which means that it converts the operands to the same type before comparing them. This can lead to unexpected results and bugs in your code. The `===` operator, on the other hand, performs strict equality comparison, which means that it compares the operands without type coercion. + + + + + ```javascript + let x = 10; + let y = "10"; + + if (x === 10) { + console.log("x is equal to 10"); + } + + if (x === y) { + console.log("x is equal to y"); + } + ``` + + + + ```javascript + let x = 10; + let y = "10"; + + if (x == 10) { + console.log("x is equal to 10"); + } + + if (x == y) { + console.log("x is equal to y"); + } + ``` + + + +By following these performance optimization techniques and best practices, you can improve the performance of your JavaScript code and make it run faster. Remember to profile your code and identify bottlenecks before applying optimizations to ensure that you are addressing the most critical issues. + +:::info 🚀 Performance Tip +Always measure the performance of your code before and after applying optimizations to ensure that you are achieving the desired improvements. +::: + +## Conclusion + +In this tutorial, we learned about performance optimization in JavaScript. We discussed various techniques and best practices to improve the performance of your JavaScript code, including minimizing DOM manipulation, avoiding memory leaks, optimizing loops, using event delegation, choosing efficient data structures, avoiding global variables, and using `===` instead of `==`. By following these techniques, you can optimize the performance of your JavaScript code and make it run faster. \ No newline at end of file diff --git a/docs/javascript/precedence.md b/docs/javascript/precedence.md new file mode 100644 index 000000000..9e5b9ef47 --- /dev/null +++ b/docs/javascript/precedence.md @@ -0,0 +1,76 @@ +--- +id: precedence-and-associativity-of-operators-in-javascript +title: Precedence and Associativity of Operators in JavaScript +sidebar_label: Precedence and Associativity of Operators +sidebar_position: 30 +tags: [JavaScript, Operators, Precedence, Associativity] +description: "In this tutorial, we will learn about the precedence and associativity of operators in JavaScript. The precedence of operators determines the order in which operators are evaluated in an expression. The associativity of operators determines the order in which operators of the same precedence are evaluated in an expression. We will see some examples to understand the precedence and associativity of operators in JavaScript." +--- + +In JavaScript, the precedence of operators determines the order in which operators are evaluated in an expression. The precedence of operators is used to determine the grouping of terms in an expression. This affects the order of evaluation of an expression. + +JavaScript follows the same precedence rules as in mathematics. The following table lists the precedence and associativity of JavaScript operators. + +| No. | Operator | Description | Associativity | +| :---: | :------- | :---------- | :------------- | +| 1 | `.` | Member Access | Left-to-right | +| 2 | `[]` | Member Access | Left-to-right | +| 3 | `()` | Function Call | Left-to-right | +| 4 | `++` `--` | Postfix Increment, Postfix Decrement | Left-to-right | +| 5 | `++` `--` | Prefix Increment, Prefix Decrement | Right-to-left | +| 6 | `!` `~` `+` `-` `typeof` `void` `delete` | Unary Operators | Right-to-left | +| 7 | `**` | Exponentiation | Right-to-left | +| 8 | `*` `/` `%` | Multiplication, Division, Remainder | Left-to-right | +| 9 | `+` `-` | Addition, Subtraction | Left-to-right | +| 10 | `<<` `>>` `>>>` | Bitwise Shifts | Left-to-right | +| 11 | `<` `<=` `>` `>=` `in` `instanceof` | Relational Operators | Left-to-right | +| 12 | `==` `!=` `===` `!==` | Equality Operators | Left-to-right | +| 13 | `&` | Bitwise AND | Left-to-right | +| 14 | `^` | Bitwise XOR | Left-to-right | +| 15 | `|` | Bitwise OR | Left-to-right | +| 16 | `&&` | Logical AND | Left-to-right | +| 17 | `||` | Logical OR | Left-to-right | +| 18 | `? :` | Conditional | Right-to-left | +| 19 | `=` `+=` `-=` `*=` `/=` `%=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` | Assignment | Right-to-left | +| 20 | `,` | Comma | Left-to-right | + +The precedence of operators determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first. For example, the multiplication operator `*` has a higher precedence than the addition operator `+`. So, the expression `2 + 3 * 4` is evaluated as `2 + (3 * 4)`. + +The associativity of operators determines the order in which operators of the same precedence are evaluated in an expression. For example, the addition operator `+` is left-to-right associative. So, the expression `2 + 3 + 4` is evaluated as `(2 + 3) + 4`. + +Let's see some examples to understand the precedence and associativity of operators in JavaScript. + +## Example: Precedence and Associativity of Operators + +```js title="app.js" +// Precedence and Associativity of Operators + +// Multiplication has higher precedence than addition + +let result1 = 2 + 3 * 4; // 2 + (3 * 4) = 2 + 12 = 14 + +console.log(result1); // Output: 14 + +// Addition is left-to-right associative + +let result2 = 2 + 3 + 4; // (2 + 3) + 4 = 5 + 4 = 9 + +console.log(result2); // Output: 9 +``` + +In this example, we have used the precedence and associativity of operators to evaluate the expressions `2 + 3 * 4` and `2 + 3 + 4`. + +When you run the above code, you will get the following output. + +```bash title="Output" +14 +9 +``` + +In the first expression `2 + 3 * 4`, the multiplication operator `*` has a higher precedence than the addition operator `+`. So, the expression is evaluated as `2 + (3 * 4)`, which results in `14`. + +In the second expression `2 + 3 + 4`, the addition operator `+` is left-to-right associative. So, the expression is evaluated as `(2 + 3) + 4`, which results in `9`. + +That's all for the precedence and associativity of operators in JavaScript. You can use the precedence and associativity of operators to evaluate complex expressions in JavaScript. + +I hope this tutorial helps you to understand the precedence and associativity of operators in JavaScript. \ No newline at end of file diff --git a/docs/javascript/random.md b/docs/javascript/random.md new file mode 100644 index 000000000..1026d919b --- /dev/null +++ b/docs/javascript/random.md @@ -0,0 +1,76 @@ +--- +id: random-in-javascript +title: Random in JavaScript +sidebar_label: Random +sidebar_position: 18 +tags: [JavaScript, Math, Object, Methods, Random, Number, Integer, Range, Floating-point, Generate, Math.random()] +description: "In this tutorial, we will learn about the Math.random() method in JavaScript. We will learn how to generate random numbers in JavaScript." +--- + +In JavaScript, the `Math.random()` method is used to generate a random floating-point number between 0 (inclusive) and 1 (exclusive). + +## Syntax + +The syntax of the `Math.random()` method is as follows: + +```js title="app.js" +Math.random() +``` + +## Example + +The following example demonstrates how to use the `Math.random()` method to generate a random number between 0 and 1: + +```js title="app.js" +console.log(Math.random()); // 0.12345678901234567 +``` + +In the above example, the `Math.random()` method returns a random floating-point number between 0 (inclusive) and 1 (exclusive). + +## Generate Random Number within a Range + +To generate a random number within a specific range, you can use the following formula: + +```js title="app.js" +Math.floor(Math.random() * (max - min + 1)) + min +``` + +Where `min` is the minimum value and `max` is the maximum value. + +The following example demonstrates how to generate a random number between 1 and 10: + +```js title="app.js" +console.log(Math.floor(Math.random() * (10 - 1 + 1)) + 1); // 5 +``` + +In the above example, the `Math.floor(Math.random() * (10 - 1 + 1)) + 1` expression generates a random number between 1 and 10. + +## Generate Random Integer + +To generate a random integer within a specific range, you can use the following formula: + +```js title="app.js" +Math.floor(Math.random() * (max - min + 1)) + min +``` + +Where `min` is the minimum value and `max` is the maximum value. + +The following example demonstrates how to generate a random integer between 1 and 10: + +```js title="app.js" +console.log(Math.floor(Math.random() * (10 - 1 + 1)) + 1); // 5 +``` + +In the above example, the `Math.floor(Math.random() * (10 - 1 + 1)) + 1` expression generates a random integer between 1 and 10. + +## A property of Math.random() method + +The `Math.random()` method returns a random floating-point number between 0 (inclusive) and 1 (exclusive). + +:::info 📝 Note +The `Math.random()` method returns a random number between 0 (inclusive) and 1 (exclusive). +::: + +## Conclusion + +In this tutorial, you learned how to use the `Math.random()` method to generate random numbers in JavaScript. You also learned how to generate random numbers within a specific range and how to generate random integers. \ No newline at end of file diff --git a/docs/javascript/reg-exp.md b/docs/javascript/reg-exp.md new file mode 100644 index 000000000..3042cee97 --- /dev/null +++ b/docs/javascript/reg-exp.md @@ -0,0 +1,395 @@ +--- +id: reg-exp-in-javascript +title: Regular Expressions in JavaScript +sidebar_label: Regular Expressions +sidebar_position: 29 +tags: [JavaScript, Regular Expressions, RegExp, Pattern, Match, Replace, Search, Split, Test, RegExp Object, RegExp Methods, RegExp Properties, RegExp in JavaScript, Regular Expressions in JavaScript, RegExp Object in JavaScript, RegExp Methods in JavaScript, RegExp Properties in JavaScript] +description: "In this tutorial, we will learn about regular expressions in JavaScript. We will learn how to create and use regular expressions to match, search, replace, and split strings in JavaScript." +--- + +In JavaScript, a regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and search-and-replace functions on strings. They are a powerful tool for working with strings and text data in JavaScript. + +## Creating a Regular Expression + +In JavaScript, you can create a regular expression using the `RegExp` object or by using a regular expression literal. + +### Using the `RegExp` Object + +You can create a regular expression using the `RegExp` object as follows: + +```js title="app.js" +const pattern = new RegExp("hello"); + +console.log(pattern); // /hello/ +``` + +In this example, we have created a regular expression that matches the string `"hello"`. +The `RegExp` object takes two arguments: the pattern and the flags. + +### Using Regular Expression Literal + +You can also create a regular expression using a regular expression literal as follows: + +```js title="app.js" +const pattern = /hello/; +``` + +In this example, we have created a regular expression using a regular expression literal. + +## Regular Expression Patterns + +A regular expression pattern is a sequence of characters that define a search pattern. It can include literal characters, metacharacters, and quantifiers. + +### Literal Characters + +Literal characters are characters that match themselves. For example, the regular expression `/hello/` matches the string `"hello"`. + +### Metacharacters + +Metacharacters are special characters that have a special meaning in regular expressions. Some common metacharacters are: + +- `.`: Matches any single character except the newline character. +- `^`: Matches the beginning of a string. +- `$`: Matches the end of a string. +- `*`: Matches zero or more occurrences of the preceding character. +- `+`: Matches one or more occurrences of the preceding character. +- `?`: Matches zero or one occurrence of the preceding character. +- `[]`: Matches any one of the characters inside the square brackets. +- `()`: Groups multiple tokens together. +- `|`: Matches either the expression before or after the `|`. +- `\`: Escapes a metacharacter or a special character. +- `{}`: Matches a specific number of occurrences of the preceding character. +- `^`: Inside square brackets, it negates the character set. +- `\b`: Matches a word boundary. +- `\B`: Matches a non-word boundary. +- `\d`: Matches a digit character. +- `\D`: Matches a non-digit character. +- `\s`: Matches a whitespace character. +- `\S`: Matches a non-whitespace character. +- `\w`: Matches a word character. +- `\W`: Matches a non-word character. +- `\n`: Matches a newline character. +- `\r`: Matches a carriage return character. +- `\t`: Matches a tab character. +- `\v`: Matches a vertical tab character. +- `\f`: Matches a form feed character. +- `\0`: Matches a null character. + +**Example for all metacharacters with their description or usage.** + +```js title="app.js" +const pattern1 = /./; // Matches any single character except the newline character +const pattern2 = /^hello/; // Matches the beginning of a string +const pattern3 = /world$/; // Matches the end of a string +const pattern4 = /a*/; // Matches zero or more occurrences of the preceding character +const pattern5 = /b+/; // Matches one or more occurrences of the preceding character +const pattern6 = /c?/; // Matches zero or one occurrence of the preceding character +const pattern7 = /[abc]/; // Matches any one of the characters inside the square brackets +const pattern8 = /(abc)/; // Groups multiple tokens together +const pattern9 = /a|b/; // Matches either the expression before or after the | +const pattern10 = /\./; // Escapes a metacharacter or a special character +const pattern11 = /d{3}/; // Matches exactly 3 occurrences of the preceding character +const pattern12 = /[^abc]/; // Negates the character set +const pattern13 = /\bword\b/; // Matches a word boundary +const pattern14 = /\d/; // Matches a digit character +const pattern15 = /\D/; // Matches a non-digit character +const pattern16 = /\s/; // Matches a whitespace character +const pattern17 = /\S/; // Matches a non-whitespace character +const pattern18 = /\w/; // Matches a word character +const pattern19 = /\W/; // Matches a non-word character +const pattern20 = /\n/; // Matches a newline character +const pattern21 = /\r/; // Matches a carriage return character +const pattern22 = /\t/; // Matches a tab character +const pattern23 = /\v/; // Matches a vertical tab character +const pattern24 = /\f/; // Matches a form feed character +const pattern25 = /\0/; // Matches a null character + +console.log(pattern1); +``` + +## Regular Expression Flags + +Regular expressions can have flags that modify the behavior of the pattern-matching. Some common flags are: + +- `i`: Case-insensitive matching. +- `g`: Global matching (find all matches). +- `m`: Multiline matching. +- `s`: Allows `.` to match newline characters. +- `u`: Enables full Unicode support. +- `y`: Sticky matching (matches from the last index). +- `d`: Enables ECMAScript 2018 mode. +- `x`: Ignores whitespace and allows comments in the pattern. +- `A`: Enables the `astral` mode. +- `D`: Enables the `dotAll` mode. +- `U`: Enables the `ungreedy` mode. +- `J`: Enables the `freeSpacing` mode. +- `X`: Enables the `extra` mode. +- `T`: Enables the `unicode` mode. +- `S`: Enables the `namedGroups` mode. +- `R`: Enables the `rightContext` mode. +- `L`: Enables the `lookbehind` mode. +- `P`: Enables the `hasIndices` mode. +- `O`: Enables the `optimize` mode. +- `C`: Enables the `constrained` mode. +- `B`: Enables the `backreferences` mode. +- `F`: Enables the `freeSpacing` mode. +- `N`: Enables the `newline` mode. +- `K`: Enables the `keepOrder` mode. +- `I`: Enables the `ignorePatternWhitespace` mode. +- `M`: Enables the `multiline` mode. +- `Y`: Enables the `sticky` mode. +- `G`: Enables the `global` mode. + +**Example for all flags with their description or usage.** + +```js title="app.js" +const pattern1 = /hello/i; // Case-insensitive matching +const pattern2 = /hello/g; // Global matching (find all matches) +const pattern3 = /hello/m; // Multiline matching +const pattern4 = /hello/s; // Allows . to match newline characters +const pattern5 = /hello/u; // Enables full Unicode support +const pattern6 = /hello/y; // Sticky matching (matches from the last index) +const pattern7 = /hello/d; // Enables ECMAScript 2018 mode +const pattern8 = /hello/x; // Ignores whitespace and allows comments in the pattern +const pattern9 = /hello/A; // Enables the astral mode +const pattern10 = /hello/D; // Enables the dotAll mode +const pattern11 = /hello/U; // Enables the ungreedy mode +const pattern12 = /hello/J; // Enables the freeSpacing mode +const pattern13 = /hello/X; // Enables the extra mode +const pattern14 = /hello/T; // Enables the unicode mode +const pattern15 = /hello/S; // Enables the namedGroups mode +const pattern16 = /hello/R; // Enables the rightContext mode + +console.log(pattern1); +``` + +## Regular Expression Methods + +In JavaScript, regular expressions are used with string methods to perform pattern-matching and search-and-replace functions on strings. Some common string methods that use regular expressions are: + +- `match()`: Returns an array of matches. +- `search()`: Returns the index of the first match. +- `replace()`: Replaces the matched substring with a new substring. +- `split()`: Splits the string into an array of substrings. +- `test()`: Tests for a match in a string. +- `exec()`: Returns the next match. +- `compile()`: Compiles a regular expression. +- `toString()`: Returns the string representation of a regular expression. +- `valueOf()`: Returns the primitive value of a regular expression. +- `toSource()`: Returns the source code of a regular expression. +- `toJSON()`: Returns the JSON representation of a regular expression. +- `toLocaleString()`: Returns the localized string representation of a regular expression. +- `hasInstance()`: Tests if a regular expression is an instance of another object. +- `isConcatSpreadable()`: Tests if a regular expression is spreadable. +- `iterator()`: Returns an iterator for a regular expression. +- `matchAll()`: Returns an iterator of matches. +- `species()`: Returns the constructor of a regular expression. +- `unscopables()`: Returns an object of properties to exclude from a regular expression. +- `flags()`: Returns the flags of a regular expression. +- `dotAll()`: Returns the dotAll flag of a regular expression. +- `sticky()`: Returns the sticky flag of a regular expression. +- `unicode()`: Returns the unicode flag of a regular expression. +- `hasIndices()`: Returns the hasIndices flag of a regular expression. +- `ignoreCase()`: Returns the ignoreCase flag of a regular expression. + +### Using the `match()` Method + +The `match()` method is used to match a string against a regular expression. It returns an array of matches if the pattern is found, or `null` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.match(pattern); + +console.log(result); // [ 'lo', index: 3, input: 'Hello, World!', groups: undefined ] +``` + +In this example, we have used the `match()` method to match the string `"Hello, World!"` against the regular expression `/lo/`. The `match()` method returns an array of matches `['lo']`. + +### Using the `search()` Method + +The `search()` method is used to search for a pattern in a string. It returns the index of the first match if the pattern is found, or `-1` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.search(pattern); + +console.log(result); // 3 +``` + +In this example, we have used the `search()` method to search for the pattern `/lo/` in the string `"Hello, World!"`. The `search()` method returns the index `3` where the pattern is found. + +### Using the `replace()` Method + +The `replace()` method is used to replace a pattern in a string with a new substring. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.replace(pattern, "123"); + +console.log(result); // He123, World! +``` + +In this example, we have used the `replace()` method to replace the pattern `/lo/` in the string `"Hello, World!"` with the new substring `"123"`. + +### Using the `split()` Method + +The `split()` method is used to split a string into an array of substrings using a regular expression or a specified separator. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.split(pattern); + +console.log(result); // [ 'He', ', World!' ] +``` + +In this example, we have used the `split()` method to split the string `"Hello, World!"` into an array of substrings using the regular expression `/lo/`. + +### Using the `test()` Method + +The `test()` method is used to test for a match in a string. It returns `true` if the pattern is found, or `false` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = pattern.test(str); + +console.log(result); // true +``` + +In this example, we have used the `test()` method to test for the pattern `/lo/` in the string `"Hello, World!"`. The `test()` method returns `true` because the pattern is found. + +### Using the `exec()` Method + +The `exec()` method is used to return the next match in a string. It returns an array of matches if the pattern is found, or `null` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = pattern.exec(str); + +console.log(result); // [ 'lo', index: 3, input: 'Hello, World!', groups: undefined ] +``` + +In this example, we have used the `exec()` method to return the next match of the pattern `/lo/` in the string `"Hello, World!"`. The `exec()` method returns an array of matches `['lo']`. + +## Regular Expression Properties + +A regular expression object has several properties that provide information about the regular expression. + +- `source`: Returns the source text of the regular expression. +- `flags`: Returns the flags of the regular expression. +- `global`: Returns `true` if the `g` flag is set, otherwise `false`. +- `ignoreCase`: Returns `true` if the `i` flag is set, otherwise `false`. +- `multiline`: Returns `true` if the `m` flag is set, otherwise `false`. +- `dotAll`: Returns `true` if the `s` flag is set, otherwise `false`. +- `unicode`: Returns `true` if the `u` flag is set, otherwise `false`. +- `sticky`: Returns `true` if the `y` flag is set, otherwise `false`. +- `hasIndices`: Returns `true` if the `d` flag is set, otherwise `false`. + +**Example for all properties with their description or usage.** + +```js title="app.js" +const pattern = /hello/gi; + +console.log(pattern.source); // hello +console.log(pattern.flags); // gi +console.log(pattern.global); // true +console.log(pattern.ignoreCase); // true +console.log(pattern.multiline); // false +console.log(pattern.dotAll); // false +console.log(pattern.unicode); // false +console.log(pattern.sticky); // false +console.log(pattern.hasIndices); // false +``` + +In this example, we have created a regular expression `/hello/gi` and accessed its properties using the `source`, `flags`, `global`, `ignoreCase`, `multiline`, `dotAll`, `unicode`, `sticky`, and `hasIndices` properties. + +## Regular Expression Examples + +### Matching a Pattern + +You can use regular expressions to match a pattern in a string. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = pattern.test(str); + +console.log(result); // true +``` + +In this example, we have used a regular expression to match the pattern `/lo/` in the string `"Hello, World!"`. The `test()` method returns `true` because the pattern is found. + +### Searching for a Pattern + +You can use regular expressions to search for a pattern in a string. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.search(pattern); + +console.log(result); // 3 +``` + +In this example, we have used a regular expression to search for the pattern `/lo/` in the string `"Hello, World!"`. The `search()` method returns the index `3` where the pattern is found. + +### Replacing a Pattern + +You can use regular expressions to replace a pattern in a string with a new substring. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.replace(pattern, "123"); + +console.log(result); // He123, World! +``` + +In this example, we have used a regular expression to replace the pattern `/lo/` in the string `"Hello, World!"` with the new substring `"123"`. + +### Splitting a String + +You can use regular expressions to split a string into an array of substrings. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.split(pattern); + +console.log(result); // [ 'He', ', World!' ] +``` + +In this example, we have used a regular expression to split the string `"Hello, World!"` into an array of substrings using the pattern `/lo/`. + +### Matching Multiple Patterns + +You can use regular expressions to match multiple patterns in a string. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/g; +const result = str.match(pattern); + +console.log(result); // [ 'lo' ] +``` + +In this example, we have used a regular expression to match the pattern `/lo/g` in the string `"Hello, World!"`. The `match()` method returns an array of matches `['lo']`. + +:::tip 📝 Note +Regular expressions are a powerful tool for working with strings and text data in JavaScript. They are widely used in web development for tasks such as form validation, data extraction, and text processing. + +Regular expressions are a complex topic, and there are many advanced features and techniques that you can learn to become proficient in using regular expressions in JavaScript. + +In this tutorial, we have covered the basics of regular expressions in JavaScript and how to create and use regular expressions to match, search, replace, and split strings. We have also covered regular expression patterns, flags, methods, and properties. + +You can learn more about regular expressions by reading the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and practicing with regular expressions in your own projects. +::: + +## Conclusion + +In this tutorial, you learned about regular expressions in JavaScript and how to create and use regular expressions to match, search, replace, and split strings. You also learned about regular expression patterns, flags, methods, and properties. Regular expressions are a powerful tool for working with strings and text data in JavaScript, and they are widely used in web development for tasks such as form validation, data extraction, and text processing. Regular expressions are a complex topic, and there are many advanced features and techniques that you can learn to become proficient in using regular expressions in JavaScript. \ No newline at end of file diff --git a/docs/javascript/scope.md b/docs/javascript/scope.md new file mode 100644 index 000000000..a3b8f8d94 --- /dev/null +++ b/docs/javascript/scope.md @@ -0,0 +1,144 @@ +--- +id: scopes-in-javascript +title: Scopes in JavaScript +sidebar_label: Scopes +sidebar_position: 32 +tags: [JavaScript, Scopes, Global Scope, Local Scope, Function Scope, Block Scope, Lexical Scope, Closures, Hoisting, Temporal Dead Zone, Global Object, Strict Mode, Module Scope] +description: "In this tutorial, we will learn about scopes in JavaScript. A scope is a region of a program where a variable is defined and can be accessed. We will see the different types of scopes in JavaScript and how they work." +--- + +In JavaScript, a scope is a region of a program where a variable is defined and can be accessed. JavaScript has three types of scopes: + +1. **Global Scope**: The global scope is the outermost scope in JavaScript. Variables declared outside of any function or block have global scope. Global variables can be accessed from any part of the program. +2. **Local Scope (Function Scope)**: The local scope is the innermost scope in JavaScript. Variables declared inside a function have local scope. Local variables can only be accessed from within the function in which they are declared. Each function has its own local scope. When a function is called, a new local scope is created. When the function returns, the local scope is destroyed. Local Scope is also known as Function Scope. +3. **Block Scope**: The block scope is the scope of a block of code enclosed in curly braces `{}`. Variables declared inside a block have block scope. Block scope is introduced in ECMAScript 6 (ES6) using the `let` and `const` keywords. Block scope is not available in ECMAScript 5 (ES5) and earlier versions. + +## Global Scope + +The global scope is the outermost scope in JavaScript. Variables declared outside of any function or block have global scope. Global variables can be accessed from any part of the program. For example: + +```javascript title="app.js" +let name = "Ajay Dhangar"; // Global variable + +function greet() { + console.log("Hello, " + name); // Accessing global variable +} + +greet(); // Output: Hello, Ajay Dhangar +``` + +In the above example, the variable `name` is declared outside of any function, so it has global scope. The `greet` function can access the `name` variable. + +## Local Scope (Function Scope) + +The local scope is the innermost scope in JavaScript. Variables declared inside a function have local scope. Local variables can only be accessed from within the function in which they are declared. Each function has its own local scope. When a function is called, a new local scope is created. When the function returns, the local scope is destroyed. Local Scope is also known as Function Scope. For example: + +```javascript title="app.js" +function greet() { + let message = "Hello, World!"; // Local variable + console.log(message); // Accessing local variable +} + +greet(); // Output: Hello, World! +console.log(message); // ReferenceError: message is not defined +``` + +In the above example, the variable `message` is declared inside the `greet` function, so it has local scope. The `greet` function can access the `message` variable, but it cannot be accessed outside of the function. + +## Block Scope + +The block scope is the scope of a block of code enclosed in curly braces `{}`. Variables declared inside a block have block scope. Block scope is introduced in ECMAScript 6 (ES6) using the `let` and `const` keywords. Block scope is not available in ECMAScript 5 (ES5) and earlier versions. For example: + +```javascript title="app.js" +if (true) { + let x = 10; // Block-scoped variable + console.log(x); // Accessing block-scoped variable +} + +console.log(x); // ReferenceError: x is not defined +``` + +In the above example, the variable `x` is declared inside the block of code, so it has block scope. The `x` variable can only be accessed within the block in which it is declared. It cannot be accessed outside of the block. + +## Lexical Scope + +Lexical scope is a scope in which a variable is defined at the time of writing the code. JavaScript uses lexical scope to resolve variable names. When a variable is referenced, JavaScript looks up the variable in the scope in which it was defined. If the variable is not found in the current scope, JavaScript looks up the variable in the outer scope. This process continues until the variable is found or the global scope is reached. + +Here is an example of lexical scope: + +```javascript title="app.js" +let name = "Ajay Dhangar"; // Global variable + +function greet() { + let message = "Hello, " + name; // Accessing global variable + console.log(message); +} + +greet(); // Output: Hello, Ajay Dhangar +``` + +In the above example, the `greet` function can access the `name` variable, which is defined in the global scope. This is an example of lexical scope. + +:::info 📚 Learn More: + +**Closures:** In JavaScript, a closure is a function that has access to its own scope, the outer function's scope, and the global scope. Closures are used to create private variables and to encapsulate functionality. Lexical scope is an important concept in understanding closures. + +Example of a closure with lexical scope for better understanding: + +```javascript title="app.js" +function outer() { + let x = 10; // Outer function variable + function inner() { + console.log(x); // Accessing outer function variable + } + return inner; +} + +let innerFunction = outer(); +innerFunction(); // Output: 10 +``` + +In this example, the `inner` function has access to the `x` variable, which is defined in the `outer` function. This is an example of a closure with lexical scope. The `inner` function has access to the `x` variable even after the `outer` function has returned. + +In the above example, the lexical scope of the `inner` function includes the scope of the `outer` function, which is why the `inner` function can access the `x` variable. This is an example of a closure with lexical scope. + +**Block Scope in ES6:** In ECMAScript 6 (ES6), the `let` and `const` keywords are introduced to declare block-scoped variables. Block scope is not available in ECMAScript 5 (ES5) and earlier versions. + +**Hoisting:** In JavaScript, variable declarations are hoisted to the top of their scope. This means that you can access a variable before it is declared. However, the value of the variable is not hoisted. Only the declaration is hoisted. + +**Temporal Dead Zone (TDZ):** In ECMAScript 6 (ES6), the `let` and `const` variables are hoisted to the top of their scope, but they are not initialized. This period between the creation of the variable and its initialization is called the Temporal Dead Zone (TDZ). If you try to access a `let` or `const` variable before it is initialized, you will get a ReferenceError. + +**Global Object:** In JavaScript, the global object is the object that holds global variables and functions. In a web browser, the global object is the `window` object. In Node.js, the global object is the `global` object. + +**Strict Mode:** In JavaScript, strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode makes it easier to write secure JavaScript code by catching common mistakes and preventing unsafe features from running. Strict mode also changes the behavior of the `this` keyword and disallows the use of undeclared variables. + +**Module Scope:** In ECMAScript 6 (ES6), JavaScript introduces the concept of modules. A module is a file that contains JavaScript code. Each module has its own scope, and the variables and functions defined in a module are not accessible outside of the module unless they are explicitly exported. + +::: + + +## Scope Chain + +The scope chain is the order in which JavaScript resolves variable names. When a variable is referenced, JavaScript looks up the variable in the scope in which it was defined. If the variable is not found in the current scope, JavaScript looks up the variable in the outer scope. This process continues until the variable is found or the global scope is reached. The scope chain is determined by the lexical scope of the code. + +Here is an example of the scope chain: + +```javascript title="app.js" +let name = "Ajay Dhangar"; // Global variable + +function greet() { + let message = "Hello, " + name; // Accessing global variable + console.log(message); +} + +greet(); // Output: Hello, Ajay Dhangar +``` + +In the above example, the `greet` function can access the `name` variable, which is defined in the global scope. This is an example of the scope chain. + + + + +## Conclusion + +In this tutorial, we learned about scopes in JavaScript. A scope is a region of a program where a variable is defined and can be accessed. JavaScript has three types of scopes: global scope, local scope (function scope), and block scope. We also learned about lexical scope, which is used by JavaScript to resolve variable names. diff --git a/docs/javascript/sets.md b/docs/javascript/sets.md new file mode 100644 index 000000000..79df9be01 --- /dev/null +++ b/docs/javascript/sets.md @@ -0,0 +1,195 @@ +--- +id: set-in-javascript +title: Sets in JavaScript +sidebar_label: Sets +sidebar_position: 26 +tags: + [ + JavaScript, + Set, + Data Structure, + Collection, + Unique, + Values, + Iteration, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + Spread Operator, + Set Methods, + ] +description: "In this tutorial, we will learn about sets in JavaScript. We will learn how to use sets to store unique values in JavaScript." +--- + +In JavaScript, a `Set` is a built-in object that allows you to store unique values. It is often used when you want to store a collection of unique values without any duplicates. + +## Creating a Set + +You can create a new `Set` by using the `new` keyword followed by the `Set` constructor. You can pass an iterable + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +console.log(set); // Set { 1, 2, 3, 4, 5 } +``` + +- The `Set` constructor creates a new `Set` object. +- You can pass an iterable (such as an array) to the `Set` constructor to initialize the set with the values from the iterable. +- The `Set` object stores unique values, so any duplicate values will be removed. +- The order of elements in a `Set` is guaranteed to be the same as the order of insertion. +- The `Set` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. +- The `Set` object has a `size` property that returns the number of elements in the set. +- The `Set` object has methods to add, delete, and check for the presence of elements. +- The `Set` object does not have methods to access elements by index, as it does not maintain the order of elements. + +## Adding Elements to a Set + +You can add elements to a `Set` by using the `add` method. + +```js title="app.js" +const set = new Set(); +set.add(1); +set.add(2); +set.add(3); +console.log(set); // Set { 1, 2, 3 } +``` + +- The `add` method is used to add a new element to the set. +- If the element is already present in the set, it will not be added again. +- The `add` method returns the `Set` object, so you can chain multiple `add` calls together. +- The `add` method is chainable, so you can add multiple elements to the set in a single statement. + +## Deleting Elements from a Set + +You can delete elements from a `Set` by using the `delete` method. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +set.delete(3); +console.log(set); // Set { 1, 2, 4, 5 } +``` + +- The `delete` method is used to remove an element from the set. +- If the element is present in the set, it will be removed, and the method will return `true`. +- If the element is not present in the set, the method will return `false`. +- The `delete` method returns `true` if the element is removed, and `false` otherwise. +- The `delete` method is chainable, so you can remove multiple elements from the set in a single statement. +- The `delete` method does not throw an error if the element is not present in the set. +- The `delete` method does not return the removed element. + +## Checking for the Presence of an Element in a Set + +You can check if an element is present in a `Set` by using the `has` method. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +console.log(set.has(3)); // true +console.log(set.has(6)); // false +``` + +- The `has` method is used to check if an element is present in the set. +- If the element is present in the set, the method will return `true`. +- If the element is not present in the set, the method will return `false`. +- The `has` method is chainable, so you can check for the presence of multiple elements in a single statement. +- The `has` method does not throw an error if the element is not present in the set. +- The `has` method does not return the element itself. +- The `has` method is often used to check if a value is present in the set before adding or deleting it. + +## Iterating Over a Set + +You can iterate over the elements of a `Set` by using a `for...of` loop. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +for (const element of set) { + console.log(element); +} +``` + +The `for...of` loop is used to iterate over the elements of the set. In each iteration, the value of the current element is assigned to the loop variable `element`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +3 +4 +5 +``` + +In each iteration, the value of the current element is printed to the console. + +## Converting a Set to an Array + +You can convert a `Set` to an array by using the `Array.from` method or the spread operator (`...`). + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +const array = Array.from(set); +console.log(array); // [1, 2, 3, 4, 5] +``` + +- The `Array.from` method is used to create a new array from an iterable (such as a `Set`). +- The `Array.from` method returns a new array that contains the elements of the iterable. +- The spread operator (`...`) can also be used to create a new array from an iterable. +- The spread operator (`...`) returns a new array that contains the elements of the iterable. + +## Using the Set Constructor + +You can use the `Set` constructor to create an empty `Set` and then add elements to it. + +```js title="app.js" +const set = new Set(); +set.add(1); +set.add(2); +set.add(3); +console.log(set); // Set { 1, 2, 3 } +``` + +The `Set` constructor creates a new empty `Set` object. You can then use the `add` method to add elements to the set. The `Set` object stores unique values, so any duplicate values will be removed. + +## Using the Spread Operator + +You can use the spread operator (`...`) to create a new `Set` from an existing `Set`. + +```js title="app.js" +const set1 = new Set([1, 2, 3]); +const set2 = new Set([...set1, 4, 5]); +console.log(set2); // Set { 1, 2, 3, 4, 5 } +``` + +The spread operator (`...`) is used to create a new `Set` that contains the elements of an existing `Set`, as well as additional elements. The new `Set` will contain the unique values from the existing `Set` and the additional elements. + +## Using the Set Methods + +You can use the `Set` methods to add, delete, and check for the presence of elements in a `Set`. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +set.add(6); +set.delete(3); +console.log(set.has(3)); // false +``` + +The `add` method is used to add a new element to the set. The `delete` method is used to remove an element from the set. The `has` method is used to check if an element is present in the set. + +:::info 📝 Note + +The `Set` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. The `Set` object has a `size` property that returns the number of elements in the set. + +**1. Spread Operator:** The spread operator (`...`) can be used to create a new `Set` from an existing `Set`. The new `Set` will contain the unique values from the existing `Set and the additional elements. The spread operator can also be used to convert a `Set` to an array. + +**2. Set Methods:** The `Set` object has methods to add, delete, and check for the presence of elements. The `add` method is used to add a new element to the set. The `delete` method is used to remove an element from the set. The `has` method is used to check if an element is present in the set. + +**3. Iterating Over a Set:** The `Set` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. In each iteration, the value of the current element is assigned to the loop variable, and the loop body is executed. + +**4. Converting a Set to an Array:** You can convert a `Set` to an array by using the `Array.from` method or the spread operator (`...`). The `Array.from` method is used to create a new array from an iterable, such as a `Set`. The spread operator (`...`) can also be used to create a new array from an iterable. + +::: + +## Summary + +In this tutorial, we learned about sets in JavaScript. We learned how to use sets to store unique values in JavaScript. We learned about the `Set` object and its methods for adding, deleting, and checking for the presence of elements. We also learned how to iterate over the elements of a `Set` and convert a `Set` to an array. \ No newline at end of file diff --git a/docs/javascript/statement-js.md b/docs/javascript/statement-js.md new file mode 100644 index 000000000..d0d5dd688 --- /dev/null +++ b/docs/javascript/statement-js.md @@ -0,0 +1,176 @@ +--- +id: satatement-in-js +title: Statement in JavaScript +sidebar_label: Statement in JavaScript +sidebar_position: 4 +tags: [JavaScript, Statement in JavaScript, statement in js, statement in JavaScript, JavaScript statement] +description: Write statements in JavaScript to perform different actions. Learn about different types of statements in JavaScript such as declaration statement, assignment statement, conditional statement, loop statement, function statement, return statement, break statement, continue statement, try...catch statement, and throw statement. +--- + +In this tutorial, you will learn about the statement in JavaScript. A statement is a command that performs an action. JavaScript is a scripting language, and it is executed by the browser. JavaScript statements are executed by the browser in the order they are written. + +## Types of Statements in JavaScript + +There are different types of statements in JavaScript. Some of the most commonly used statements are: + +### 1. Declaration Statement + +A declaration statement is used to declare a variable in JavaScript. For example, + +```js title="declaration-statement.js" +var name; +let age; +const PI = 3.14; +``` + +In the above program, we have declared three variables `name`, `age`, and `PI` using the `var`, `let`, and `const` keyword respectively. + +### 2. Assignment Statement + +An assignment statement is used to assign a value to a variable in JavaScript. For example, + +```js title="assignment-statement.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; +``` + +In the above program, we have assigned the value `"Ajay"` to the `name` variable, `23` to the `age` variable, and `3.14` to the `PI` variable. + +### 3. Conditional Statement + +A conditional statement is used to perform different actions based on different conditions. For example, + +```js title="conditional-statement.js" +var age = 23; + +if (age >= 18) { + console.log("You are eligible to vote."); +} else { + console.log("You are not eligible to vote."); +} +``` + +In the above program, we have used the `if...else` statement to check if the `age` is greater than or equal to `18`. If the condition is `true`, then it will print `"You are eligible to vote."`, otherwise it will print `"You are not eligible to vote."`. + +### 4. Loop Statement + +A loop statement is used to execute a block of code multiple times. For example, + +```js title="loop-statement.js" +for (var i = 1; i <= 5; i++) { + console.log(i); +} +``` + +In the above program, we have used the `for` loop to print numbers from `1` to `5`. + +### 5. Function Statement + +A function statement is used to define a function in JavaScript. For example, + +```js title="function-statement.js" +function greet() { + console.log("Hello, World!"); +} + +greet(); // Output: Hello, World! +``` + +In the above program, we have defined a function `greet()` that prints `"Hello, World!"` to the console. + +### 6. Return Statement + +A return statement is used to return a value from a function in JavaScript. For example, + +```js title="return-statement.js" +function add(a, b) { + return a + b; +} + +var sum = add(5, 3); + +console.log(sum); // Output: 8 +``` + +In the above program, we have used the `return` statement to return the sum of `a` and `b` from the `add()` function. + +### 7. Break Statement + +A break statement is used to terminate a loop in JavaScript. For example, + +```js title="break-statement.js" +for (var i = 1; i <= 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +In the above program, we have used the `break` statement to terminate the loop when `i` is equal to `3`. + +### 8. Continue Statement + +A continue statement is used to skip the current iteration of a loop in JavaScript. For example, + +```js title="continue-statement.js" + +for (var i = 1; i <= 5; i++) { + if (i === 3) { + continue; + } + console.log(i); +} +``` + +In the above program, we have used the `continue` statement to skip the iteration when `i` is equal to `3`. + +### 9. Try...Catch Statement + +A try...catch statement is used to handle errors in JavaScript. For example, + +```js title="try-catch-statement.js" +try { + var result = 10 / 0; + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} +``` + +In the above program, we have used the `try...catch` statement to handle the division by zero error. + +### 10. Throw Statement + +A throw statement is used to throw an exception in JavaScript. For example, + +```js title="throw-statement.js" +function divide(a, b) { + if (b === 0) { + throw new Error("Division by zero"); + } + return a / b; +} + +try { + var result = divide(10, 0); + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); // Output: An error occurred: Division by zero +} +``` + +In the above program, we have used the `throw` statement to throw an exception when `b` is equal to `0`. + +:::info +In JavaScript, a statement is terminated by a semicolon `;`. However, it is optional in most cases. But it is a good practice to use a semicolon to terminate a statement. +::: + +## Conclusion + +In this tutorial, you have learned about the statement in JavaScript. A statement is a command that performs an action. JavaScript statements are executed by the browser in the order they are written. There are different types of statements in JavaScript such as declaration statement, assignment statement, conditional statement, loop statement, function statement, return statement, break statement, continue statement, try...catch statement, and throw statement. You can use these statements to perform different actions in JavaScript. + +I hope this tutorial will help you to understand the statement in JavaScript. + +If you have any questions or feedback, feel free to reach out to me in the comment section below. \ No newline at end of file diff --git a/docs/javascript/strict.md b/docs/javascript/strict.md new file mode 100644 index 000000000..cff98e429 --- /dev/null +++ b/docs/javascript/strict.md @@ -0,0 +1,203 @@ +--- +id: strict-mode-in-javascript +title: Strict Mode in JavaScript +sidebar_label: Strict Mode +sidebar_position: 33 +tags: [JavaScript, Strict Mode, JavaScript Strict Mode, Strict Mode in JavaScript, Use Strict, Strict Mode Tutorial, Strict Mode Guide, Strict Mode Overview, Strict Mode Basics, Strict Mode Getting Started, Strict Mode Tutorial JavaScript, Strict Mode Guide JavaScript, Strict Mode Overview JavaScript, Strict Mode Basics JavaScript, Strict Mode Getting Started JavaScript] +description: "In this tutorial, we will learn about strict mode in JavaScript. Strict mode is a feature that allows you to place a program or a function in a strict operating context. It helps catch common coding errors and makes the code more secure and optimized." +--- + +In JavaScript, strict mode is a feature that allows you to place a program or a function in a strict operating context. When strict mode is enabled, the JavaScript engine performs additional checks and enforces stricter rules on the code. This helps catch common coding errors and makes the code more secure and optimized. + +## Why Use Strict Mode? + +There are several reasons to use strict mode in JavaScript: + +1. **Catch Common Errors**: Strict mode helps catch common coding errors and unsafe actions that would otherwise go unnoticed. It throws errors for silent errors that would have been ignored in non-strict mode. +2. **Prevent Global Variables**: In strict mode, assigning a value to an undeclared variable throws an error. This helps prevent accidental creation of global variables. +3. **Optimize Code**: Strict mode enforces stricter rules on the code, which can help optimize the performance of the code and make it run faster. +4. **Improve Security**: Strict mode helps prevent certain actions that are considered unsafe or insecure in JavaScript. It makes the code more secure and less prone to vulnerabilities. +5. **Future Compatibility**: Strict mode is a standard feature of ECMAScript 5 (ES5) and later versions. Using strict mode ensures that the code is compatible with modern JavaScript environments and future versions of the language. +6. **Encourage Best Practices**: Strict mode encourages best practices and helps developers write cleaner, more maintainable code. It enforces stricter rules on variable declarations, function calls, and other aspects of the code. +7. **Enable New Features**: Some new features of JavaScript are only available in strict mode. Using strict mode allows you to take advantage of these features and write more modern and efficient code. +8. **Improve Debugging**: Strict mode helps identify and fix errors in the code more easily. It provides more informative error messages and warnings that can help developers debug the code effectively. +9. **Enhance Readability**: Strict mode makes the code more readable and self-explanatory by enforcing stricter rules on variable declarations, function calls, and other aspects of the code. +10. **Prevent Silent Failures**: Strict mode helps prevent silent failures in the code by throwing errors for common coding errors and unsafe actions. This makes the code more robust and reliable. +11. **Improve Performance**: Strict mode enforces stricter rules on the code, which can help optimize the performance of the code and make it run faster. It eliminates certain JavaScript features that are known to be slow or inefficient. +12. **Reduce Bugs**: Strict mode helps reduce the likelihood of bugs and errors in the code by enforcing stricter rules and catching common coding errors. This can save time and effort in debugging and fixing issues in the code. +13. **Enhance Code Quality**: Strict mode helps improve the quality of the code by enforcing stricter rules on variable declarations, function calls, and other aspects of the code. It encourages best practices and helps developers write cleaner, more maintainable code. + +## Enabling Strict Mode + +Strict mode can be enabled at different levels in JavaScript: + +1. **Global Strict Mode**: To enable strict mode for the entire script, you can add the `"use strict";` directive at the beginning of the script. This applies strict mode to the entire script and all functions defined within the script. + + ```javascript title="app.js" + "use strict"; + + function greet() { + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + } + + greet(); + ``` + +2. **Function Strict Mode**: To enable strict mode for a specific function, you can add the `"use strict";` directive at the beginning of the function. This applies strict mode only to the function in which it is defined. + + ```javascript title="app.js" + function greet() { + "use strict"; + + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + } + + greet(); + ``` + +3. **Module Strict Mode**: In ECMAScript 6 (ES6) and later versions, you can use strict mode in modules by default. Modules are automatically in strict mode, so you don't need to add the `"use strict";` directive explicitly. + + ```javascript title="app.js" + // app.js (module) + function greet() { + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + } + + greet(); + ``` + +When strict mode is enabled, the JavaScript engine performs additional checks and enforces stricter rules on the code. It throws errors for common coding errors and unsafe actions that would otherwise go unnoticed in non-strict mode. + +## Strict Mode Rules + +Strict mode enforces several rules on the code to catch common coding errors and make the code more secure and optimized. Some of the key rules enforced by strict mode include: + +1. **No Implicit Globals**: In strict mode, assigning a value to an undeclared variable throws an error. This helps prevent accidental creation of global variables. + + ```javascript title="app.js" + "use strict"; + + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + ``` + +2. **No Octal Literals**: In strict mode, octal literals (numbers with a leading zero) are not allowed. Octal literals are considered confusing and error-prone. + + ```javascript title="app.js" + "use strict"; + + let num = 010; // Error: Uncaught SyntaxError: Octal literals are not allowed in strict mode. + console.log(num); + ``` + +3. **No Duplicate Parameters**: In strict mode, defining a function with duplicate parameters throws an error. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + function greet(name, name) { // Error: Uncaught SyntaxError: Duplicate parameter name not allowed in this context + console.log("Hello, " + name); + } + + greet("Alice", "Bob"); + ``` + +4. **No `this` in Global Context**: In strict mode, the `this` keyword in the global context is `undefined`. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + console.log(this); // Output: undefined + ``` + +5. **No `eval` and `arguments`**: In strict mode, the use of `eval` and `arguments` as variable names is not allowed. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + let eval = 10; // Error: Uncaught SyntaxError: Unexpected eval or arguments in strict mode + let arguments = 20; // Error: Uncaught SyntaxError: Unexpected eval or arguments in strict mode + ``` + +6. **No `with` Statement**: In strict mode, the `with` statement is not allowed. The `with` statement is considered harmful and error-prone. + + ```javascript title="app.js" + "use strict"; + + let person = { name: "Alice" }; + with (person) { // Error: Uncaught SyntaxError: Strict mode code may not include a with statement + console.log(name); + } + ``` + +7. **No `delete` on Non-configurable Properties**: In strict mode, attempting to delete a non-configurable property throws an error. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + let obj = {}; + Object.defineProperty(obj, "name", { + value: "Alice", + configurable: false + }); + + delete obj.name; // Error: Uncaught TypeError: Cannot delete property 'name' of # + ``` + +8. **No `arguments.callee`**: In strict mode, the `arguments.callee` property is not allowed. This property is considered harmful and error-prone. + + ```javascript title="app.js" + "use strict"; + + function factorial(n) { + if (n <= 1) { + return 1; + } else { + return n * arguments.callee(n - 1); // Error: Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them + } + } + + console.log(factorial(5)); + ``` + +9. **No `this` in Functions**: In strict mode, the `this` keyword in functions is `undefined` if the function is called without an explicit context. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + function greet() { + console.log(this); // Output: undefined + } + + greet(); + ``` + +10. **No `new` on Non-constructor Functions**: In strict mode, calling a non-constructor function with the `new` keyword throws an error. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + function greet() { + console.log("Hello, World!"); + } + + let obj = new greet(); // Error: Uncaught TypeError: greet is not a constructor + ``` + +These are some of the key rules enforced by strict mode in JavaScript. By enabling strict mode, you can catch common coding errors and make the code more secure and optimized. + +:::info 📚 Learn More: + +- [Strict Mode (MDN Web Docs)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) +- [Strict Mode in JavaScript (W3Schools)](https://www.w3schools.com/js/js_strict.asp) +- [Understanding ECMAScript 6: The Definitive Guide for JavaScript Developers](https://www.amazon.com/Understanding-ECMAScript-Definitive-JavaScript-Developers/dp/1593277571) +- [JavaScript: The Good Parts](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) + +::: + +## Conclusion + +Strict mode is a feature in JavaScript that allows you to place a program or a function in a strict operating context. It helps catch common coding errors and makes the code more secure and optimized. By enabling strict mode, you can enforce stricter rules on the code, prevent common coding errors, and improve the quality and performance of the code. Strict mode is a standard feature of ECMAScript 5 (ES5) and later versions, and it is recommended to use strict mode in all JavaScript code to ensure compatibility with modern JavaScript environments and future versions of the language. \ No newline at end of file diff --git a/docs/javascript/strings.md b/docs/javascript/strings.md new file mode 100644 index 000000000..3d8f892db --- /dev/null +++ b/docs/javascript/strings.md @@ -0,0 +1,331 @@ +--- +id: all-about-strings +title: All Basic About Strings in JavaScript +sidebar_label: Strings in JavaScript +sidebar_position: 13 +tags: [JavaScript, Strings, String Methods, Template Literals, Escape Characters, String Length, toUpperCase, toLowerCase, charAt, indexOf, lastIndexOf, includes, startsWith, endsWith, slice, substring, substr, replace, split, trim, concat, repeat, padStart, padEnd, match, search, localeCompare, charCodeAt, fromCharCode, fromCodePoint, codePointAt, normalize] +description: "In the JavaScript programming language, strings are text that is displayed on the screen. They are used to store and manipulate text. In this section, you will learn how to create and manipulate strings in JavaScript. You will also learn about the different methods that can be used to manipulate strings. We are going to cover the following topics in this section:" +--- + +> Strings are used to store text. They are used to represent a sequence of characters. +> Strings are written with quotes. You can use single or double quotes. + +```js title="index.js" +let name = "Ajay"; +let message = 'Hello, Ajay!'; +``` + +## String Length + +The `length` property returns the length of a string (number of characters). + +```js title="index.js" +let name = "Ajay"; +console.log(name.length); // 4 +``` + +## Escape Characters + +In JavaScript, you can use the backslash `\` to escape quotes and other characters. + +```js title="index.js" +let message = 'It\'s a beautiful day!'; +console.log(message); // It's a beautiful day! +``` + +The backslash `\` is used to escape quotes and other characters in a string. + +| Code | Output | Description | +| :--: | :----: | :---------: | +| `\'` | ' | Single quote | +| `\"` | " | Double quote | +| `\\` | \ | Backslash | +| `\n` | | New line | +| `\r` | | Carriage return | +| `\t` | | Tab | +| `\b` | | Backspace | +| `\f` | | Form feed | +| `\v` | | Vertical tab | + +## String Methods + +JavaScript has a number of built-in methods for working with strings. + +### `toUpperCase()` + +The `toUpperCase()` method converts a string to uppercase letters. + +```js title="index.js" +let name = "Ajay"; +console.log(name.toUpperCase()); // AJAY +``` + +### `toLowerCase()` + +The `toLowerCase()` method converts a string to lowercase letters. + +```js title="index.js" +let name = "AJAY"; +console.log(name.toLowerCase()); // ajay +``` + +### `charAt()` + +The `charAt()` method returns the character at a specified index (position) in a string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.charAt(0)); // A +console.log(name.charAt(1)); // j +``` + +### `indexOf()` + +The `indexOf()` method returns the position of the first occurrence of a specified value in a string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.indexOf('Ajay')); // 7 +``` + +### `lastIndexOf()` + +The `lastIndexOf()` method returns the position of the last occurrence of a specified value in a string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.lastIndexOf('l')); // 3 +``` + +### `includes()` + +The `includes()` method returns `true` if a string contains a specified value, otherwise `false`. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.includes('Ajay')); // true +console.log(message.includes('Ajayy')); // false + +// Case sensitive +console.log(message.includes('ajay')); // false +``` + +### `startsWith()` + +The `startsWith()` method returns `true` if a string starts with a specified value, otherwise `false`. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.startsWith('Hello')); // true +console.log(message.startsWith('Ajay')); // false +``` + +### `endsWith()` + +The `endsWith()` method returns `true` if a string ends with a specified value, otherwise `false`. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.endsWith('Ajay!')); // true +console.log(message.endsWith('Hello')); // false +``` + +### `slice()` + +The `slice()` method extracts a part of a string and returns the extracted part in a new string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.slice(7)); // Ajay! +console.log(message.slice(7, 11)); // Ajay +``` + +### `substring()` + +The `substring()` method extracts the characters from a string, between two specified indices, and returns the new sub string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.substring(7)); // Ajay! +console.log(message.substring(7, 11)); // Ajay +``` + +### `substr()` + +The `substr()` method extracts the characters from a string, beginning at a specified start position, and through the specified number of character. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.substr(7)); // Ajay! +console.log(message.substr(7, 4)); // Ajay +``` + +### `replace()` + +The `replace()` method replaces a specified value with another value in a string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.replace('Ajay', 'John')); // Hello, John! +``` + +### `split()` + +The `split()` method splits a string into an array of substrings, and returns the new array. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.split(' ')); // [ 'Hello,', 'Ajay!' ] +``` + +### `trim()` + +The `trim()` method removes whitespace from both ends of a string. + +```js title="index.js" +let message = ' Hello, Ajay! '; +console.log(message.trim()); // Hello, Ajay! +``` + +### `concat()` + +The `concat()` method joins two or more strings. + +```js title="index.js" +let name = "Ajay"; +let message = 'Hello, '; +console.log(message.concat(name)); // Hello, Ajay +``` + +### `repeat()` + +The `repeat()` method returns a new string with a specified number of copies of the string it was called on. + +```js title="index.js" +let name = "Ajay"; +console.log(name.repeat(3)); // AjayAjayAjay +``` + +### `padStart()` + +The `padStart()` method pads the current string with another string until the resulting string reaches the given length. + +```js title="index.js" +let name = "Ajay"; +console.log(name.padStart(10, 'Hi ')); // Hi Hi Ajay +``` + +### `padEnd()` + +The `padEnd()` method pads the current string with another string until the resulting string reaches the given length. + +```js title="index.js" +let name = "Ajay"; +console.log(name.padEnd(10, ' Hi')); // Ajay Hi Hi +``` + +### `match()` + +The `match()` method searches a string for a match against a regular expression, and returns the matches, as an Array object. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.match('Ajay')); // [ 'Ajay', index: 7, input: 'Hello, Ajay!', groups: undefined ] +``` + +### `search()` + +The `search()` method searches a string for a specified value, and returns the position of the match. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.search('Ajay')); // 7 +``` + +### `localeCompare()` + +The `localeCompare()` method compares two strings in the current locale. + +```js title="index.js" +let name1 = "Ajay"; +let name2 = "John"; + +console.log(name1.localeCompare(name2)); // -1 +console.log(name2.localeCompare(name1)); // 1 +console.log(name1.localeCompare(name1)); // 0 +``` + +### `charCodeAt()` + +The `charCodeAt()` method returns the Unicode of the character at a specified index in a string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.charCodeAt(0)); // 65 +console.log(name.charCodeAt(1)); // 106 +``` + +### `fromCharCode()` + +The `fromCharCode()` method converts Unicode values to characters. + +```js title="index.js" +console.log(String.fromCharCode(65)); // A +console.log(String.fromCharCode(106)); // j +``` + +### `fromCodePoint()` + +The `fromCodePoint()` method returns a string created by using the specified sequence of code points. + +```js title="index.js" +console.log(String.fromCodePoint(65)); // A +console.log(String.fromCodePoint(106)); // j +``` + +### `codePointAt()` + +The `codePointAt()` method returns a non-negative integer that is the Unicode code point value. + +```js title="index.js" +let name = "Ajay"; +console.log(name.codePointAt(0)); // 65 +console.log(name.codePointAt(1)); // 106 +``` + +### `normalize()` + +The `normalize()` method returns the Unicode Normalization Form of a given string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.normalize()); // Ajay +``` + +### `includes()` + +The `includes()` method determines whether a string contains the characters of a specified string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.includes('A')); // true +console.log(name.includes('a')); // false +``` + +## Template Literals + +Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification. + +```js title="index.js" +let name = "Ajay"; +let message = `Hello, ${name}!`; +console.log(message); // Hello, Ajay! +``` + +:::info +Template literals are enclosed by the back-tick (<) (grave accent) character instead of double or single quotes. +::: + +## Conclusion + +In this tutorial, we learned about strings in JavaScript and various methods to work with strings. We also learned about template literals. \ No newline at end of file diff --git a/docs/javascript/style-guide-js.md b/docs/javascript/style-guide-js.md new file mode 100644 index 000000000..cbbe3ec04 --- /dev/null +++ b/docs/javascript/style-guide-js.md @@ -0,0 +1,243 @@ +--- +id: style-guide-in-js +title: Style Guide in JavaScript +sidebar_label: Style Guide +sidebar_position: 40 +tags: + [ + JavaScript, + Style Guide, + Style Guide in JavaScript, + JavaScript Style Guide, + JavaScript Style Guide Tutorial, + JavaScript Style Guide Example, + JavaScript Style Guide Best Practices, + JavaScript Style Guide Coding Standards, + JavaScript Style Guide Recommendations, + JavaScript Style Guide Conventions, + JavaScript Style Guide Rules, + JavaScript Style Guide Linting, + JavaScript Style Guide ESLint, + JavaScript Style Guide Prettier, + JavaScript Style Guide Airbnb, + JavaScript Style Guide Google, + JavaScript Style Guide Standard, + JavaScript Style Guide AirBnB, + JavaScript Style Guide Google, + JavaScript Style Guide Standard, + JavaScript Style Guide Airbnb ESLint, + JavaScript Style Guide Google ESLint, + JavaScript Style Guide Standard ESLint, + JavaScript Style Guide Airbnb Prettier, + JavaScript Style Guide Google Prettier, + JavaScript Style Guide Standard Prettier, + JavaScript Style Guide Airbnb Linting, + JavaScript Style Guide Google Linting, + JavaScript Style Guide Standard Linting, + JavaScript Style Guide Airbnb Prettier Linting, + JavaScript Style Guide Google Prettier Linting, + JavaScript Style Guide Standard Prettier Linting, + ] +description: "In this tutorial, we will learn about the style guide in JavaScript. We will learn about the best practices, coding standards, recommendations, conventions, rules, linting, ESLint, Prettier, Airbnb, Google, Standard, AirBnB, Google, Standard, Airbnb ESLint, Google ESLint, Standard ESLint, Airbnb Prettier, Google Prettier, Standard Prettier, Airbnb Linting, Google Linting, Standard Linting, Airbnb Prettier Linting, Google Prettier Linting, Standard Prettier Linting." +--- + +Style Guide in JavaScript is a set of best practices, coding standards, recommendations, conventions, and rules that developers should follow while writing JavaScript code. It helps in maintaining the code quality, readability, and consistency across the codebase. It also helps in avoiding common pitfalls and bugs in the code. + +There are various tools available for enforcing the style guide in JavaScript such as ESLint, Prettier, Airbnb, Google, Standard, etc. These tools help in automatically checking the code against the style guide and providing suggestions or warnings to fix the issues. + +In this tutorial, we will learn about the style guide in JavaScript and how to enforce it using ESLint and Prettier. + +## Style Guide Rules + +The style guide in JavaScript consists of various rules that developers should follow while writing code. These rules cover various aspects of coding such as naming conventions, indentation, spacing, comments, etc. Some common rules in the style guide are: + +### Naming Conventions + +- Use camelCase for variable names. + + ```javascript title="Good" + let myVariable = 10; + ``` + +- Use PascalCase for class names. + + ```javascript title="Good" + class MyClass { + // class definition + } + ``` + +- Use UPPERCASE for constants. + + ```javascript title="Good" + const MY_CONSTANT = 100; + ``` + +### Indentation + +- Use 2 or 4 spaces for indentation. + + ```javascript title="Good" + function myFunction() { + if (condition) { + // code block + } + } + ``` + + ```javascript title="Good" + function myFunction() { + if (condition) { + // code block + } + + return result; + } + ``` + +### Spacing + +- Use spaces around operators. + + ```javascript title="Good" + let sum = a + b; + ``` + +- Use spaces after commas. + + ```javascript title="Good" + let arr = [1, 2, 3]; + ``` + +### Comments + +- Use comments to explain complex code or logic. + + ```javascript title="Good" + // Calculate the sum of two numbers + function sum(a, b) { + return a + b; + } + ``` + +- Avoid unnecessary comments. + + ```javascript title="Bad" + // Function to add two numbers + function sum(a, b) { + return a + b; // return sum + } + ``` + +These are just a few examples of the rules in the style guide. There are many more rules that cover different aspects of coding. + +## Linting + +Linting is the process of analyzing the code for potential errors, bugs, stylistic issues, and enforcing the style guide rules. ESLint is a popular linting tool for JavaScript that helps in identifying and fixing problems in the code. It can be configured to enforce the style guide rules and provide warnings or errors when the code violates these rules. + +To use ESLint in your project, you need to install it as a development dependency using npm or yarn. + +```bash npm2yarn +npm install eslint --save-dev +``` + +Once installed, you can create an ESLint configuration file `.eslintrc.js` in the root of your project to define the rules for your project. + +```javascript title=".eslintrc.js" +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + extends: ["eslint:recommended"], + rules: { + // add your custom rules here + }, +}; +``` + +You can also use popular ESLint configurations such as Airbnb, Google, Standard, etc., which provide a set of predefined rules that you can use in your project. + +```bash title="Install ESLint Config Airbnb" +npx install-peerdeps --dev eslint-config-airbnb +``` + +```javascript title=".eslintrc.js" +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + extends: ["airbnb"], + rules: { + // add your custom rules here + }, +}; +``` + +Once you have configured ESLint, you can run it on your project using the following command. + +```bash title="Run ESLint" +npx eslint . +``` + +ESLint will analyze your code and report any errors or warnings based on the rules defined in the configuration file. + +## Prettier + +Prettier is another popular tool for code formatting that helps in enforcing consistent code style across the codebase. It automatically formats the code according to the predefined rules such as indentation, spacing, line breaks, etc. + +To use Prettier in your project, you need to install it as a development dependency using npm or yarn. + +```bash npm2yarn +npm install prettier --save-dev +``` + +Once installed, you can create a Prettier configuration file `.prettierrc` in the root of your project to define the formatting rules. + +```json title=".prettierrc" +{ + "singleQuote": true, + "semi": false +} +``` + +You can also integrate Prettier with ESLint using the `eslint-plugin-prettier` and `eslint-config-prettier` plugins. This allows ESLint to check for formatting issues and fix them using Prettier. + +```bash npm2yarn +npm install eslint-plugin-prettier eslint-config-prettier --save-dev +``` + +```javascript title=".eslintrc.js" +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + extends: ["airbnb", "plugin:prettier/recommended"], + rules: { + // add your custom rules here + }, +}; +``` + +Once you have configured Prettier with ESLint, you can run ESLint with the `--fix` option to automatically fix the formatting issues in your code. + +```bash title="Run ESLint with Prettier" +npx eslint . --fix +``` + +This will format your code according to the Prettier rules and fix any formatting issues in the code. + +By following the style guide rules and using ESLint and Prettier, you can maintain code quality, readability, and consistency in your JavaScript projects. + +:::info +**Note:** You can also use other linting and formatting tools such as TSLint, JSHint, etc., based on your project requirements. +::: + +## Conclusion + +In this tutorial, we learned about the style guide in JavaScript and how to enforce it using ESLint and Prettier. We covered the common rules in the style guide, linting with ESLint, and code formatting with Prettier. By following the style guide rules and using these tools, you can maintain code quality, readability, and consistency in your JavaScript projects. \ No newline at end of file diff --git a/docs/javascript/switch.md b/docs/javascript/switch.md new file mode 100644 index 000000000..94eee7cb2 --- /dev/null +++ b/docs/javascript/switch.md @@ -0,0 +1,224 @@ +--- +id: switch-in-javascript +title: Switch Statement in JavaScript +sidebar_label: Switch Statement +sidebar_position: 20 +tags: [JavaScript, Conditional, Statement, Switch, Case, Break, Default, Decision, Making, Control, Flow, Conditional, Statements] +description: "In this tutorial, we will learn about the switch statement in JavaScript. We will learn how to use the switch statement to make decisions in JavaScript." +--- + +In JavaScript, the `switch` statement is used to execute a block of code based on the value of a variable. It is an alternative to the `if...else` statement when you need to compare the value of a variable to multiple values. + +## Syntax + +The syntax of the `switch` statement is as follows: + +```js title="app.js" +switch (expression) { + case value1: + // code to be executed if expression is equal to value1 + break; + case value2: + // code to be executed if expression is equal to value2 + break; + case value3: + // code to be executed if expression is equal to value3 + break; + default: + // code to be executed if expression is different from all values +} +``` + +- The `switch` statement starts with the `switch` keyword followed by an expression in parentheses. +- The `case` keyword is followed by a value and a colon. If the value of the expression matches the value of the `case`, the code inside the `case` block is executed. +- The `break` statement is used to exit the `switch` statement. If the `break` statement is omitted, the code will continue to execute the next `case` block. +- The `default` case is optional and is executed if the value of the expression does not match any of the `case` values. +- The `default` case does not require a `break` statement because it is always the last case in the `switch` statement. +- The `default` case can be placed anywhere in the `switch` statement. + +## Flow Chart of the `switch` Statement + +```mermaid +graph TD; + Start([Start]) --> Condition{Expression}; + Condition -->|Case 1| Action1; + Condition -->|Case 2| Action2; + Condition -->|Case 3| Action3; + Condition -->|Case 4| Action4; + Condition -->|Default| DefaultAction; + Action1 --> End; + Action2 --> End; + Action3 --> End; + Action4 --> End; + DefaultAction --> End; + End --> Stop([Stop]); + +``` + +## Example + +The following example demonstrates how to use the `switch` statement to check the day of the week: + +```js title="app.js" +let day = 3; +let dayName; + +switch (day) { + case 1: + dayName = "Sunday"; + break; + case 2: + dayName = "Monday"; + break; + case 3: + dayName = "Tuesday"; + break; + case 4: + dayName = "Wednesday"; + break; + case 5: + dayName = "Thursday"; + break; + case 6: + dayName = "Friday"; + break; + case 7: + dayName = "Saturday"; + break; + default: + dayName = "Invalid day"; +} + +console.log(dayName); // Tuesday +``` + +In the above example, the `switch` statement checks the value of the `day` variable and assigns the corresponding day name to the `dayName` variable. + +:::tip Flow Chart for the Example + +```mermaid +graph TD; + Start([Start]) --> Condition{day}; + Condition -->|1| Action1; + Condition -->|2| Action2; + Condition -->|3| Action3; + Condition -->|4| Action4; + Condition -->|5| Action5; + Condition -->|6| Action6; + Condition -->|7| Action7; + Condition -->|Default| DefaultAction; + Action1 --> End; + Action2 --> End; + Action3 --> End; + Action4 --> End; + Action5 --> End; + Action6 --> End; + Action7 --> End; + DefaultAction --> End; + End --> Stop([Stop]); + + subgraph DayNames + Action1(Sunday) + Action2(Monday) + Action3(Tuesday) + Action4(Wednesday) + Action5(Thursday) + Action6(Friday) + Action7(Saturday) + DefaultAction(Invalid day) + end +``` +::: + +## Multiple Cases + +You can use multiple `case` blocks to execute the same code for different values. For example: + +```js title="app.js" +let grade = "B+"; +let message; + +switch (grade) { + case "A+": + case "A": + case "A-": + message = "Excellent"; + break; + case "B+": + case "B": + case "B-": + message = "Good"; + break; + case "C+": + case "C": + case "C-": + message = "Fair"; + break; + case "D+": + case "D": + case "D-": + message = "Poor"; + break; + case "F": + message = "Fail"; + break; + default: + message = "Invalid grade"; +} + +console.log(message); // Good +``` + +In the above example, the `switch` statement checks the value of the `grade` variable and assigns a message based on the grade. + +:::info 📝 Note + +

Live Example

+ +```js live +function todayIs(){ + let day = new Date().getDay(); + let dayName; + + switch (day) { + case 0: + dayName = "Sunday"; + break; + case 1: + dayName = "Monday"; + break; + case 2: + dayName = "Tuesday"; + break; + case 3: + dayName = "Wednesday"; + break; + case 4: + dayName = "Thursday"; + break; + case 5: + dayName = "Friday"; + break; + case 6: + dayName = "Saturday"; + break; + default: + dayName = "Invalid day"; + } + + return ( +
+

Today is {dayName}

+
+ ) +} + +``` + +In the above example, the `switch` statement checks the value of the `day` variable and assigns the corresponding day name to the `dayName` variable. + +::: + +## Conclusion + +In this tutorial, you learned about the `switch` statement in JavaScript and how to use it to make decisions based on the value of a variable. You also learned how to use multiple `case` blocks to execute the same code for different values. \ No newline at end of file diff --git a/docs/javascript/syntax-js-.md b/docs/javascript/syntax-js-.md new file mode 100644 index 000000000..f1501e266 --- /dev/null +++ b/docs/javascript/syntax-js-.md @@ -0,0 +1,243 @@ +--- +id: syntax-of-js +title: Syntax of JavaScript +sidebar_label: Syntax of JavaScript +sidebar_position: 5 +tags: [JavaScript, Syntax of JavaScript, syntax of js, syntax of JavaScript, JavaScript syntax] +description: Write a JavaScript program using the syntax of JavaScript. Learn about the syntax of JavaScript, how to create a JavaScript file, how to create variables, how to use variables, how to create and use functions, JavaScript values, operators, literals, keywords, comments, statements, expressions, identifiers, naming conventions, case sensitivity, and the JavaScript character set. +--- + +In this tutorial, you will learn about the syntax of JavaScript. The syntax of JavaScript is the set of rules that define how a JavaScript program will be written and interpreted. The syntax of JavaScript is similar to the syntax of other programming languages like C, C++, and Java. + +## Hello, World! Program in JavaScript + +Let's start with a simple "Hello, World!" program in JavaScript. + +```js title="HelloWorld.js" +console.log("Hello, World!"); +``` + +In the above program, we have used the `console.log()` method to print "Hello, World!" to the console. + +## How to create a JavaScript file? + +You can create a JavaScript file with a `.js` extension. For example, `HelloWorld.js`. + +## How to create variables in JavaScript? + +You can create variables in JavaScript using the `var`, `let`, or `const` keyword. For example, + +```js title="variables.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; +``` + +In the above program, we have created three variables `name`, `age`, and `PI` using the `var`, `let`, and `const` keyword respectively. + +## How to use variables in JavaScript? + +You can use variables in JavaScript to store and manipulate data. For example, + +```js title="use-variables.js" +var name = "Ajay"; +console.log(name); // Output: Ajay + +let age = 23; + +age = age + 1; + +console.log(age); // Output: 24 +``` + +In the above program, we have used the `name` and `age` variables to store and manipulate data. + +## How to create and use functions in JavaScript? + +You can create and use functions in JavaScript to perform a specific task. Functions is created using the `function` keyword. For example, + +```js title="functions.js" +function greet() { + console.log("Hello, World!"); +} + +greet(); // Output: Hello, World! +``` + +In the above program, we have created a function `greet()` that prints "Hello, World!" to the console. + +## JavaScript Values + +JavaScript values are the data that is stored in variables. For example, `10`, `"Hello, World!"`, `true`, `false`, etc. + +for example, + +```js title="values.js" +var num = 10; +var name = "Ajay"; +var isStudent = true; +``` + +## JavaScript Operators + +JavaScript operators are used to perform operations on variables and values. For example, `+`, `-`, `*`, `/`, `==`, `!=`, `>`, `<`, etc. + +For example, + +```js title="operators.js" +var num1 = 10; +var num2 = 20; + +var sum = num1 + num2; +console.log(sum); // Output: 30 + +var isGreater = num1 > num2; +console.log(isGreater); // Output: false +``` + +## JavaScript Literals + +JavaScript literals are fixed values that are directly written in the code. For example, `10`, `"Hello, World!"`, `true`, `false`, etc. + +For example, + +```js title="literals.js" +console.log(10); // Output: 10 +console.log("Hello, World!"); // Output: Hello, World! +console.log(true); // Output: true +``` + +## JavaScript Keywords + +JavaScript keywords are the reserved words that have a special meaning in JavaScript. For example, `var`, `let`, `const`, `function`, `if`, `else`, `for`, `while`, etc. + +For example, + +```js title="keywords.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; + +if (age > 18) { + console.log("You are an adult!"); +} else { + console.log("You are a child!"); +} +``` + +## JavaScript Comments + +JavaScript comments are used to explain the code and make it more readable. There are two types of comments in JavaScript: single-line comments and multi-line comments. + +For example, + +```js title="comments.js" + +// This is a single-line comment + +/* +This is a multi-line comment +It can span multiple lines +*/ +``` + +## JavaScript Statements + +JavaScript statements are the instructions that are executed by the browser. For example, variable declaration, conditional statement, loop statement, function statement, etc. + +For example, + +```js title="statements.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; + +if (age > 18) { + console.log("You are an adult!"); +} else { + console.log("You are a child!"); +} +``` + +In the above program, we have declared variables `name`, `age`, and `PI` using the `var`, `let`, and `const` keyword respectively. We have also used the `if...else` statement to check if the `age` is greater than `18`. + +## JavaScript Expressions + +JavaScript expressions are the combination of values, variables, and operators that are evaluated to produce a value. For example, `10 + 20`, `name + " is " + age + " years old"`, etc. + +For example, + +```js title="expressions.js" +var num1 = 10; +var num2 = 20; + +var sum = num1 + num2; + +var name = "Ajay"; +let age = 23; + +var message = name + " is " + age + " years old."; +``` + +In the above program, `num1 + num2` and `name + " is " + age + " years old"` are expressions. + +## JavaScript Identifiers, Naming Conventions, and Case Sensitivity + +JavaScript identifiers are the names given to variables, functions, labels, and objects. JavaScript identifiers are case-sensitive and can contain letters, digits, underscores, and dollar signs. + +A JavaScript name must start with: + +- A letter (A-Z or a-z) +- A dollar sign ($) +- Or an underscore (_) +- After the first letter, a JavaScript name can also contain digits (0-9). +- JavaScript names are case-sensitive. + +For example, + +```js title="identifiers.js" +var name = "Ajay"; +let Age = 23; +const $currency = "USD"; +const _PI = 3.14; +const isStudent = true; +const surname123 = "Dhangar"; +``` + +In the above program, `name`, `Age`, `$currency`, `_PI`, `isStudent`, and `surname123` are identifiers. + +## JavaScript Character Set + +JavaScript uses the Unicode character set. JavaScript supports both ASCII and Unicode characters. + +for example, + +```js title="character-set.js" +var name = "Ajay"; +var ₹ = "Rupee"; +var こんにちは = "Hello"; +``` + +In the above program, `name`, `₹`, and `こんにちは` are identifiers. + +:::warning +- JavaScript identifiers should not start with a digit (0-9). + for example, + ```js title="invalid-identifiers.js" + var 123name = "Ajay"; // Invalid + ``` +- JavaScript identifiers should not contain special characters except `$` and `_`. + for example, + ```js title="invalid-identifiers.js" + var first-name = "Ajay"; // Invalid + ``` +- JavaScript identifiers should not be a JavaScript keyword. + for example, + ```js title="invalid-identifiers.js" + var var = "Ajay"; // Invalid + ``` +::: + +## Conclusion + +In this tutorial, you have learned about the syntax of JavaScript. The syntax of JavaScript is the set of rules that define how a JavaScript program will be written and interpreted. The syntax of JavaScript is similar to the syntax of other programming languages like C, C++, and Java. You have also learned about the "Hello, World!" program, how to create a JavaScript file, how to create variables, how to use variables, how to create and use functions, JavaScript values, operators, literals, keywords, comments, statements, expressions, identifiers, naming conventions, case sensitivity, and the JavaScript character set. \ No newline at end of file diff --git a/docs/javascript/this-keyword.md b/docs/javascript/this-keyword.md new file mode 100644 index 000000000..07ea7adad --- /dev/null +++ b/docs/javascript/this-keyword.md @@ -0,0 +1,760 @@ +--- +id: this-keyword-in-javascript +title: this Keyword in JavaScript +sidebar_label: this Keyword +sidebar_position: 34 +tags: [JavaScript, this, this keyword, this binding, this value, this context, this in functions, this in methods, this in constructors, this in arrow functions, this in event handlers, this in callbacks, this in nested functions, this in global scope, this in strict mode, this in modules, this in classes, this in prototypes, this in async functions, this in promises, this in generators, this in iterators, this in destructuring, this in spread operator, this in rest parameters, this in default parameters, this in computed properties, this in dynamic properties, this in getters, this in setters, this in static methods, this in private methods, this in public methods, this in protected methods, this in instance methods, this in static properties, this in private properties, this in public properties, this in protected properties, this in instance properties, this in static accessors, this in private accessors] +description: "In this tutorial, we will learn about the `this` keyword in JavaScript. The `this` keyword refers to the object on which a function is being invoked. The value of `this` depends on how a function is called. We will see how `this` works in different contexts such as functions, methods, constructors, arrow functions, event handlers, callbacks, nested functions, global scope, strict mode, modules, classes, prototypes, async functions, promises, generators, iterators, destructuring, spread operator, rest parameters, default parameters, computed properties, dynamic properties, getters, setters, static methods, private methods, public methods, protected methods, instance methods, static properties, private properties, public properties, protected properties, instance properties, static accessors, private accessors, etc." +--- + +In JavaScript, the `this` keyword refers to the object on which a function is being invoked. The value of `this` depends on how a function is called. The `this` keyword allows you to access the object's properties and methods from within the function. + +The `this` keyword is a special keyword in JavaScript that is used to refer to the object on which a function is being invoked. The value of `this` is determined by how a function is called, not where it is defined. The `this` keyword allows you to access the object's properties and methods from within the function. + +The `this` keyword can be used in different contexts such as functions, methods, constructors, arrow functions, event handlers, callbacks, nested functions, global scope, strict mode, modules, classes, prototypes, async functions, promises, generators, iterators, destructuring, spread operator, rest parameters, default parameters, computed properties, dynamic properties, getters, setters, static methods, private methods, public methods, protected methods, instance methods, static properties, private properties, public properties, protected properties, instance properties, static accessors, private accessors, etc. + +In this tutorial, we will learn how the `this` keyword works in different contexts in JavaScript. + +## `this` in Functions + +In JavaScript, the `this` keyword in a function refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +function greet() { + console.log(this); // Output: Window {...} (in browsers) +} + +greet(); +``` + +In the above example, the `this` keyword inside the `greet` function refers to the global object (`Window` in browsers) because the `greet` function is called in the global scope. + +## `this` in Methods + +In JavaScript, the `this` keyword in a method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet() { + console.log(this.name); // Output: Alice + } +}; + +person.greet(); +``` + +In the above example, the `this` keyword inside the `greet` method of the `person` object refers to the `person` object because the `greet` method is called on the `person` object. + +## `this` in Constructors + +In JavaScript, the `this` keyword in a constructor refers to the object being created by the constructor. + +For example: + +```javascript title="app.js" +function Person(name) { + this.name = name; + this.greet = function() { + console.log("Hello, " + this.name); + }; +} + +const person = new Person("Alice"); +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the `Person` constructor refers to the object being created by the constructor. The `this.name` property of the object is set to the `name` argument passed to the constructor. + +## `this` in Arrow Functions + +In JavaScript, the `this` keyword in an arrow function refers to the `this` value of the enclosing lexical context. Arrow functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet: function() { + const greetArrow = () => { + console.log(this.name); // Output: Alice + }; + + greetArrow(); + } +}; + +person.greet(); +``` + +In the above example, the `this` keyword inside the arrow function `greetArrow` refers to the `this` value of the `greet` method of the `person` object because the arrow function does not have its own `this` value. + +## `this` in Event Handlers + +In JavaScript, the `this` keyword in an event handler refers to the element that triggered the event. + +For example: + +```html title="index.html" + + + + + Event Handler + + + + + + + +``` + + + + + +In the above example, the `this` keyword inside the event handler function refers to the `button` element that triggered the `click` event. + +## `this` in Callbacks + +In JavaScript, the `this` keyword in a callback function refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +function greet(callback) { + callback(); +} + +function sayHello() { + console.log(this); // Output: Window {...} (in browsers) +} + +greet(sayHello); +``` + +In the above example, the `this` keyword inside the `sayHello` callback function refers to the global object (`Window` in browsers) because the `sayHello` function is called in the global scope. + +## `this` in Nested Functions + +In JavaScript, the `this` keyword in a nested function refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +function outer() { + function inner() { + console.log(this); // Output: Window {...} (in browsers) + } + + inner(); +} + +outer(); +``` + +In the above example, the `this` keyword inside the `inner` nested function refers to the global object (`Window` in browsers) because the `inner` function is called in the global scope. + +## `this` in Global Scope + +In JavaScript, the `this` keyword in the global scope refers to the global object (`window` in browsers, `global` in Node.js). + +For example: + +```javascript title="app.js" +console.log(this); // Output: Window {...} (in browsers) +``` + +In the above example, the `this` keyword in the global scope refers to the global object (`Window` in browsers). + +## `this` in Strict Mode + +In JavaScript, the `this` keyword in the global scope refers to `undefined` in strict mode. + +For example: + +```javascript title="app.js" +"use strict"; + +console.log(this); // Output: undefined +``` + +In the above example, the `this` keyword in the global scope refers to `undefined` because the code is running in strict mode. + +## `this` in Modules + +In JavaScript, the `this` keyword in a module refers to `undefined` in strict mode. + +For example: + +```javascript title="app.js" +console.log(this); // Output: undefined +``` + +```html title="index.html" + + + + + + Module + + + + + +``` + +In the above example, the `this` keyword in the module `app.js` refers to `undefined` because the code is running in strict mode. + +## `this` in Classes + +In JavaScript, the `this` keyword in a class method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the `greet` method of the `Person` class refers to the `person` object because the `greet` method is called on the `person` object. + +## `this` in Prototypes + +In JavaScript, the `this` keyword in a prototype method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +function Person(name) { + this.name = name; +} + +Person.prototype.greet = function() { + console.log("Hello, " + this.name); +}; + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the `greet` prototype method of the `Person` constructor refers to the `person` object because the `greet` method is called on the `person` object. + +## `this` in Async Functions + +In JavaScript, the `this` keyword in an async function refers to the `this` value of the enclosing lexical context. Async functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet: async function() { + console.log(this.name); // Output: Alice + } +}; + +person.greet(); +``` + +In the above example, the `this` keyword inside the async function `greet` refers to the `this` value of the `person` object because async functions do not have their own `this` value. + +## `this` in Promises + +In JavaScript, the `this` keyword in a promise callback refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet: function() { + return new Promise((resolve, reject) => { + resolve(this.name); + }); + } +}; + +person.greet().then(name => { + console.log(name); // Output: Alice +}); +``` + +In the above example, the `this` keyword inside the promise callback refers to the global object (`Window` in browsers) because the promise callback is called in the global scope. + +## `this` in Generators + +In JavaScript, the `this` keyword in a generator function refers to the `this` value of the enclosing lexical context. Generator functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + *greet() { + console.log(this.name); // Output: Alice + } +}; + +const generator = person.greet(); + +generator.next(); +``` + +In the above example, the `this` keyword inside the generator function `greet` refers to the `this` value of the `person` object because generator functions do not have their own `this` value. + +## `this` in Iterators + +In JavaScript, the `this` keyword in an iterator function refers to the `this` value of the enclosing lexical context. Iterator functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + [Symbol.iterator]: function*() { + yield this.name; + } +}; + +for (const name of person) { + console.log(name); // Output: Alice +} +``` + +In the above example, the `this` keyword inside the iterator function refers to the `this` value of the `person` object because iterator functions do not have their own `this` value. + +## `this` in Destructuring + +In JavaScript, the `this` keyword in a destructuring assignment refers to the global object (`window` in browsers, `global` in Node.js) when the assignment is done in the global scope. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice" +}; + +const { name } = person; + +console.log(this); // Output: Window {...} (in browsers) +``` + +In the above example, the `this` keyword inside the destructuring assignment refers to the global object (`Window` in browsers) because the assignment is done in the global scope. + +## `this` in Spread Operator + +In JavaScript, the `this` keyword in a spread operator refers to the global object (`window` in browsers, `global` in Node.js) when the operator is used in the global scope. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice" +}; + +const personCopy = { ...person }; + +console.log(this); // Output: Window {...} (in browsers) +``` + +In the above example, the `this` keyword inside the spread operator refers to the global object (`Window` in browsers) because the operator is used in the global scope. + +## `this` in Rest Parameters + +In JavaScript, the `this` keyword in a rest parameter refers to the global object (`window` in browsers, `global` in Node.js) when the parameter is used in the global scope. + +For example: + +```javascript title="app.js" +function greet(...args) { + console.log(this); // Output: Window {...} (in browsers) +} + +greet("Alice", "Bob"); +``` + +In the above example, the `this` keyword inside the rest parameter refers to the global object (`Window` in browsers) because the parameter is used in the global scope. + +## `this` in Default Parameters + +In JavaScript, the `this` keyword in a default parameter refers to the global object (`window` in browsers, `global` in Node.js) when the parameter is used in the global scope. + +For example: + +```javascript title="app.js" +function greet(name = "Alice") { + console.log(this); // Output: Window {...} (in browsers) +} + +greet(); +``` + +In the above example, the `this` keyword inside the default parameter refers to the global object (`Window` in browsers) because the parameter is used in the global scope. + +## `this` in Computed Properties + +In JavaScript, the `this` keyword in a computed property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + ["greet"]() { + console.log("Hello, " + this.name); + } +}; + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the computed property `greet` refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Dynamic Properties + +In JavaScript, the `this` keyword in a dynamic property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet() { + console.log("Hello, " + this.name); + } +}; + +person["greet"](); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the dynamic property `greet` refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Getters + +In JavaScript, the `this` keyword in a getter refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + get greeting() { + return "Hello, " + this.name; + } +}; + +console.log(person.greeting); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the getter `greeting` refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Setters + +In JavaScript, the `this` keyword in a setter refers to the object on which the property is being set. + +For example: + +```javascript title="app.js" +const person = { + _name: "", + set name(value) { + this._name = value; + }, + get name() { + return this._name; + } +}; + +person.name = "Alice"; + +console.log(person.name); // Output: Alice +``` + +In the above example, the `this` keyword inside the setter `name` refers to the `person` object because the property is set on the `person` object. + +## `this` in Static Methods + +In JavaScript, the `this` keyword in a static method refers to the class itself, not an instance of the class. + +For example: + +```javascript title="app.js" +class Person { + static greet() { + console.log("Hello, world"); + } +} + +Person.greet(); // Output: Hello, world +``` + +In the above example, the `this` keyword inside the static method `greet` refers to the `Person` class itself, not an instance of the class. + +## `this` in Private Methods + +In JavaScript, the `this` keyword in a private method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + #name; + + constructor(name) { + this.#name = name; + } + + #greet() { + console.log("Hello, " + this.#name); + } + + greet() { + this.#greet(); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the private method `#greet` of the `Person` class refers to the `person` object because the private method is called on the `person` object. + +## `this` in Public Methods + +In JavaScript, the `this` keyword in a public method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the public method `greet` of the `Person` class refers to the `person` object because the public method is called on the `person` object. + +## `this` in Protected Methods + +In JavaScript, the `this` keyword in a protected method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + #greet() { + console.log("Hello, " + this.name); + } + + greet() { + this.#greet(); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the protected method `#greet` of the `Person` class refers to the `person` object because the protected method is called on the `person` object. + +## `this` in Instance Methods + +In JavaScript, the `this` keyword in an instance method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the instance method `greet` of the `Person` class refers to the `person` object because the instance method is called on the `person` object. + +## `this` in Static Properties + +In JavaScript, the `this` keyword in a static property refers to the class itself, not an instance of the class. + +For example: + +```javascript title="app.js" +class Person { + static name = "Alice"; + + static greet() { + console.log("Hello, " + this.name); + } +} + +Person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the static property `name` of the `Person` class refers to the `Person` class itself, not an instance of the class. + +## `this` in Private Properties + +In JavaScript, the `this` keyword in a private property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" + +class Person { + #name; + + constructor(name) { + this.#name = name; + } + + greet() { + console.log("Hello, " + this.#name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the private property `#name` of the `Person` class refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Public Properties + +In JavaScript, the `this` keyword in a public property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" + +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the public property `name` of the `Person` class refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Protected Properties + +In JavaScript, the `this` keyword in a protected property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" + +class Person { + #name; + + constructor(name) { + this.#name = name; + } + + greet() { + console.log("Hello, " + this.#name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the protected property `#name` of the `Person` class refers to the `person` object because the property is accessed on the `person` object. + + +## `this` in Static Accessors + +In JavaScript, the `this` keyword in a static accessor refers to the class itself, not an instance of the class. + +For example: + +```javascript title="app.js" +class Person { + static #name = "Alice"; + + static get name() { + return this.#name; + } + + static set name(value) { + this.#name = value; + } +} + +console.log(Person.name); // Output: Alice + +Person.name = "Bob"; + +console.log(Person.name); // Output: Bob +``` + +In the above example, the `this` keyword inside the static accessor `name` of the `Person` class refers to the `Person` class itself, not an instance of the class. + +:::info 🤖🏋️‍♂️ + +The `this` keyword in JavaScript is a powerful feature that allows you to access the object's properties and methods from within a function. The value of `this` depends on how a function is called. By understanding how `this` works in different contexts, you can write more flexible and reusable code. + +::: + +## Conclusion + +In this tutorial, we have learned about the `this` keyword in JavaScript. The `this` keyword refers to the object on which a function is being invoked. The value of `this` depends on how a function is called. We have seen how `this` works in different contexts such as functions, methods, constructors, arrow functions, event handlers, callbacks, nested functions, global scope, strict mode, modules, classes, prototypes, async functions, promises, generators, iterators, destructuring, spread operator, rest parameters, default parameters, computed properties, dynamic properties, getters, setters, static methods, private methods, public methods, protected methods, instance methods, static properties, private properties, public properties, protected properties, static accessors, etc. \ No newline at end of file diff --git a/docs/javascript/type-of.md b/docs/javascript/type-of.md new file mode 100644 index 000000000..c54526b10 --- /dev/null +++ b/docs/javascript/type-of.md @@ -0,0 +1,130 @@ +--- +id: type-of-in-javascript +title: typeof Operator in JavaScript +sidebar_label: typeof +sidebar_position: 28 +tags: [JavaScript, typeof, Operator, Type, Value, Data, Typeof, Typeof Operator, Typeof Keyword, Typeof Operator in JavaScript, Typeof Keyword in JavaScript, Typeof Operator, Typeof Keyword, Typeof Operator in JS, Typeof Keyword in JS] +description: "In this tutorial, we will learn about the typeof operator in JavaScript. We will learn how to use the typeof operator to determine the type of a value in JavaScript." +--- + +In JavaScript, the `typeof` operator is used to determine the type of a value. It is often used when you want to check the type of a variable or a value before performing an operation on it. + +## Syntax + +The syntax of the `typeof` operator is as follows: + +```js title="app.js" +typeof value +``` + +- The `typeof` operator is followed by the `value` whose type you want to determine. +- The `value` can be a variable, a literal, or an expression. +- The `typeof` operator returns a string that represents the type of the `value`. +- The returned string can be one of the following values: + - `"undefined"`: If the `value` is `undefined`. + - `"boolean"`: If the `value` is a boolean. + - `"number"`: If the `value` is a number. + - `"string"`: If the `value` is a string. + - `"symbol"`: If the `value` is a symbol. + - `"function"`: If the `value` is a function. + - `"object"`: If the `value` is an object or `null`. + - `"bigint"`: If the `value` is a BigInt. + - `"object"`: If the `value` is an object or `null`. + +## Example + +The following example demonstrates how to use the `typeof` operator to determine the type of a value: + +```js title="app.js" +const name = "John"; +const age = 30; +const isMarried = false; +const fruits = ["apple", "banana", "cherry"]; +const person = { + name: "John", + age: 30, +}; + +console.log(typeof name); // string +console.log(typeof age); // number +console.log(typeof isMarried); // boolean +console.log(typeof fruits); // object +console.log(typeof person); // object +console.log(typeof undefinedVariable); // undefined +console.log(typeof nullVariable); // object +``` + +- In this example, we have used the `typeof` operator to determine the type of different values such as strings, numbers, booleans, arrays, objects, `undefined`, and `null`. +- The `typeof` operator returns the type of the value as a string. +- The `typeof` operator is often used to check the type of a value before performing an operation on it, such as type conversion or type-specific operations. +- The `typeof` operator is useful when you want to handle different types of values differently in your code. +- The `typeof` operator can be used to determine the type of a variable or a value at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a value before performing an operation on it, such as type conversion or type-specific operations. +- The `typeof` operator can be used to handle different types of values differently in your code. +- The `typeof` operator can be used to determine the type of a variable or a value at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a value before performing an operation on it, such as type conversion or type-specific operations. + +## Using the `typeof` Operator with Functions + +The `typeof` operator can be used to determine the type of a function. It returns `"function"` if the value is a function. + +```js title="app.js" +function greet() { + console.log("Hello, World!"); +} + +console.log(typeof greet); // function +``` + +- In this example, we have used the `typeof` operator to determine the type of the `greet` function. +- The `typeof` operator returns `"function"` because the `greet` value is a function. +- The `typeof` operator can be used to determine the type of a function, which can be useful when you want to handle functions differently in your code. +- The `typeof` operator can be used to determine the type of a function at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a function before performing an operation on it, such as calling the function or passing it as an argument to another function. +- The `typeof` operator can be used to handle functions differently in your code based on their type. + +## Using the `typeof` Operator with `null` + +The `typeof` operator returns `"object"` if the value is `null`. This is a historical bug in JavaScript, and it is not expected to change. + +```js title="app.js" +const person = null; + +console.log(typeof person); // object +``` + +In this example, we have used the `typeof` operator to determine the type of the `person` value, which is `null`. The `typeof` operator returns `"object"` because the `person` value is `null`. + +The `typeof` operator returns `"object"` if the value is `null`. This is a historical bug in JavaScript, and it is not expected to change. + +The `typeof` operator can be used to determine the type of a value at runtime, which can be useful in dynamic programming scenarios. + +The `typeof` operator can be used to determine the type of a value before performing an operation on it, such as type conversion or type-specific operations. + + +## Using the `typeof` Operator with Symbols + +The `typeof` operator returns `"symbol"` if the value is a symbol. + +```js title="app.js" +const symbol = Symbol("mySymbol"); + +console.log(typeof symbol); // symbol +``` + +- In this example, we have used the `typeof` operator to determine the type of the `symbol` value, which is a symbol. +- The `typeof` operator returns `"symbol"` because the `symbol` value is a symbol. +- The `typeof` operator can be used to determine the type of a symbol, which can be useful when you want to handle symbols differently in your code. +- The `typeof` operator can be used to determine the type of a symbol at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a symbol before performing an operation on it, such as type conversion or type-specific operations. +- The `typeof` operator can be used to handle symbols differently in your code based on their type. + +:::caution + +The `typeof` operator returns `"object"` if the value is `null`. This is a historical bug in JavaScript, and it is not expected to change. + +::: + +## Conclusion + +In this tutorial, you learned about the `typeof` operator in JavaScript and how to use it to determine the type of a value. You also learned about the different types of values that the `typeof` operator can return, such as `"undefined"`, `"boolean"`, `"number"`, `"string"`, `"symbol"`, `"function"`, `"object"`, and `"bigint"`. You also learned about the historical bug in JavaScript where the `typeof` operator returns `"object"` for `null` values. The `typeof` operator is useful when you want to handle different types of values differently in your code, and it can be used to determine the type of a variable or a value at runtime, which can be useful in dynamic programming scenarios. \ No newline at end of file diff --git a/docs/javascript/variables-js.md b/docs/javascript/variables-js.md new file mode 100644 index 000000000..0895c0393 --- /dev/null +++ b/docs/javascript/variables-js.md @@ -0,0 +1,303 @@ +--- +id: variables-in-javascript +title: Variables in JavaScript +sidebar_label: Variables in JavaScript +sidebar_position: 7 +tags: [JavaScript, Variables, variables in js, JavaScript variables, let, const, var, variable naming rules, variable best practices, variable declaration, variable initialization, variable scope, variable hoisting, variable re-declaration, variable re-assignment, variable mutable, variable naming conventions, variable naming best practices, variable naming rules, variable naming guidelines, variable naming standards, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable naming best practices in JavaScript, variable naming rules in JavaScript, variable naming guidelines in JavaScript, variable naming standards in JavaScript, variable naming conventions in JS, variable naming best practices in JS, variable naming rules in JS, variable naming guidelines in JS, variable naming standards in JS, variable naming conventions in JavaScript, variable] +description: What are variables in JavaScript? How to declare and initialize variables in JavaScript? Learn about variable naming rules and best practices. +--- + +In this tutorial, you will learn about variables in JavaScript. Variables are used to store data. They are like containers that hold data. You can think of them as a box that holds different items. You can put anything in the box and give it a name. Similarly, you can store different types of data in a variable and give it a name. + +## What are Variables? + +A variable is a named storage location that holds data. It has a name and a value. The value of a variable can change during the execution of a program. + +```mermaid +graph LR; + A[Variables] --> B(Containers for storing data); + B --> C(Data can be of different types, such as numbers, strings, booleans, etc.); + B --> D(Data can be assigned, retrieved, and modified); + B --> E(Variables have a name or identifier); + B --> F(Variables can have different scopes, such as global scope or local scope); +``` + +In JavaScript, you can declare a variable using the `var`, `let`, or `const` keyword. + +## Declaring Variables + +You can declare a variable using the `var`, `let`, or `const` keyword followed by the variable name. + +```mermaid +sequenceDiagram + participant User + participant Interpreter + participant Memory + + User->>Interpreter: Declare Variables + Interpreter->>User: Choose a name for the variable + Interpreter->>User: Determine the data type + Interpreter->>User: Use the appropriate keyword to declare the variable + Interpreter->>User: Optionally assign an initial value to the variable + Interpreter->>Memory: Allocate memory for the variable + Interpreter->>Interpreter: Store variable name and data type in symbol table + Interpreter->>User: Variable declaration completed + +``` + +For example, + +```js title="declaring-variables.js" +var name; +let age; +const PI = 3.14; +``` + +In this example, we have declared three variables: `name`, `age`, and `PI`. The `var` and `let` keywords are used to declare variables. The `const` keyword is used to declare constants. + +:::important +The `var` keyword is used to declare variables in JavaScript. However, it is recommended to use `let` and `const` instead of `var` to declare variables. We will learn more about `let` and `const` in the upcoming sections. +::: + +## Initializing Variables + +You can initialize a variable at the time of declaration. To initialize a variable, you can assign a value to it using the assignment operator (`=`). + +```mermaid +sequenceDiagram + participant User + participant Interpreter + participant Memory + + User->>Interpreter: Initialize Variables + Interpreter->>User: Provide initial values for variables + Interpreter->>Memory: Assign initial values to variables in memory + Interpreter->>User: Initialization completed +``` + +For example, + +```js title="initializing-variables.js" +var name = "John"; +let age = 25; +const PI = 3.14; +``` + +In this example, we have initialized three variables: `name`, `age`, and `PI`. The `name` variable is initialized with the value `"John"`, the `age` variable is initialized with the value `25`, and the `PI` constant is initialized with the value `3.14`. + +## Variable Naming Rules + +```mermaid +flowchart LR; + Start --> A[Variable Naming Rules]; + A --> B{Start with Letter, Underscore or Dollar Sign }; + B --> |Yes| C[Continue with Letters, Digits, Underscores, or Dollar Signs]; + C --> D{Not Start with Digit}; + D --> |Yes| E[Not Reserved Keywords]; + E --> F{Follow Naming Convention}; + F --> |Yes| G[Valid Variable Name]; + B --> |No| H[Invalid Variable Name]; + D --> |No| H; + E --> |No| H; + H --> I{Error or Warning}; + I --> J[Review and Correct]; +``` + +When naming variables in JavaScript, there are a few rules you need to follow: + +1. The variable name must start with a letter, underscore (`_`), or dollar sign (`$`). +2. The variable name can contain letters, digits, underscores (`_`), or dollar signs (`$`). +3. The variable name cannot contain spaces or special characters, except underscores (`_`) or dollar signs (`$`). +4. The variable name is case-sensitive. For example, `name`, `Name`, and `NAME` are three different variables. +5. The variable name should be descriptive and meaningful. +6. The variable name should not be a reserved keyword. +7. The variable name should follow camelCase or snake_case naming convention. +8. The variable name should not start with a capital letter. +9. The variable name should not be too long or too short. +10. The variable name should not be a JavaScript built-in object, method, or property. + +## Best Practices for Naming Variables + +```mermaid +flowchart LR; + Start --> A[Best Practices for Naming Variables]; + A --> B[Use descriptive names]; + A --> C[Use camelCase]; + A --> D[Avoid abbreviations]; + A --> E[Be consistent]; + A --> F[Avoid single-letter names]; + A --> G[Avoid reserved keywords]; + B --> H{Descriptive}; + H --> |Yes| I[Good]; + H --> |No| J[Improve]; + J --> K{Improve}; + K --> |Yes| I; + K --> |No| J; + I --> L{CamelCase}; + L --> |Yes| M[Good]; + L --> |No| N[Improve]; + N --> O{Improve}; + O --> |Yes| M; + O --> |No| N; + E --> P{Consistency}; + P --> |Yes| Q[Good]; + P --> |No| R[Improve]; + R --> S{Improve}; + S --> |Yes| Q; + S --> |No| R; + F --> T{Single-letter}; + T --> |Yes| U[Improve]; + T --> |No| V[Good]; + U --> W{Improve}; + W --> |Yes| V; + W --> |No| U; + G --> X{Reserved Keywords}; + X --> |Yes| Y[Avoided]; + X --> |No| Z[Good]; +``` + +When naming variables in JavaScript, you should follow these best practices: + +1. Use descriptive and meaningful variable names. + for example, `firstName`, `lastName`, `age`, `email`, `address`, etc. +2. Use camelCase or snake_case naming convention. + for example, `firstName`, `last_name`, `userAge`, `user_email`, etc. +3. Do not use reserved keywords as variable names. + for example, `var`, `let`, `const`, `function`, `if`, `else`, `while`, `for`, etc. +4. Do not use JavaScript built-in objects, methods, or properties as variable names. + for example, `Math`, `Date`, `String`, `Number`, `Object`, `Array`, `console`, `log`, `error`, etc. +5. Do not use a single character as a variable name. + for example, `a`, `b`, `c`, `x`, `y`, `z`, etc. +6. Do not use a too long or too short variable name. + for example, `thisIsAVeryLongVariableName`, `a`, `b`, etc. + +## Differents between var, let, and const in JavaScript + +In JavaScript, you can declare a variable using the `var`, `let`, or `const` keyword. Each keyword has different behavior and scope. + +| Keyword | Scope | Hoisting |TDZ | Re-declaration | Re-assignment | Mutable | +|:-------:|:-----:|:--------:|:--:|:--------------:|:-------------:|:-------:| +| var | Function | Yes | No | Yes | Yes | Yes | +| let | Block | No | Yes | No | Yes | Yes | +| const | Block | No | Yes | No | No | No | + +- **Scope**: The scope of a variable is the region of the program where the variable is accessible. The scope of a variable can be global or local. The `var` keyword has a function scope, while the `let` and `const` keywords have a block scope. + + for example, + + ```js title="scope.js" + var x = 10; + let y = 20; + const z = 30; + + function test() { + var a = 40; + let b = 50; + const c = 60; + console.log(a, b, c); // 40 50 60 + } + + console.log(x, y, z); // 10 20 30 + console.log(a, b, c); // ReferenceError: a is not defined + ``` + +- **Hoisting**: Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase. The `var` keyword is hoisted, while the `let` and `const` keywords are not hoisted. + + for example, + + ```js title="hoisting.js" + console.log(x); // undefined + var x = 10; + ``` + +- **Temporal Dead Zone (TDZ)**: The temporal dead zone is a behavior in JavaScript where you cannot access a variable before it is declared. The `let` and `const` keywords have a temporal dead zone, while the `var` keyword does not have a temporal dead zone. + + for example, + + ```js title="tdz.js" + console.log(x); // ReferenceError: Cannot access 'x' before initialization + let x = 10; + ``` + +- **Re-declaration**: The `var` keyword allows you to re-declare a variable in the same scope, while the `let` and `const` keywords do not allow you to re-declare a variable in the same scope. + + for example, + + ```js title="re-declaration.js" + var x = 10; + var x = 20; + console.log(x); // 20 + + let y = 30; + let y = 40; // SyntaxError: Identifier 'y' has already been declared + ``` + +- **Re-assignment**: The `var`, `let`, and `const` keywords allow you to re-assign a value to a variable. However, the `const` keyword does not allow you to re-assign a value to a variable. + + for example, + + ```js title="re-assignment.js" + var x = 10; + x = 20; + console.log(x); // 20 + + let y = 30; + y = 40; + console.log(y); // 40 + + const z = 50; + z = 60; // TypeError: Assignment to constant variable. + ``` + +- **Mutable**: The `var` and `let` keywords allow you to mutate the value of a variable, while the `const` keyword does not allow you to mutate the value of a variable. + + for example, + + ```js title="mutable.js" + var x = 10; + x = 20; + console.log(x); // 20 + + let y = 30; + y = 40; + console.log(y); // 40 + + const z = 50; + z = 60; // TypeError: Assignment to constant variable. + ``` + + ```mermaid + graph TD; + A[Variables] --> B{Scope}; + B --> |var| C[Function]; + B --> |let| D[Block]; + B --> |const| E[Block]; + A --> F{Hoisting}; + F --> |var| G[Yes]; + F --> |let| H[No]; + F --> |const| I[No]; + A --> J{Temporal Dead Zone}; + J --> |var| K[No]; + J --> |let| L[Yes]; + J --> |const| M[Yes]; + A --> N{Re-declaration}; + N --> |var| O[Yes]; + N --> |let| P[No]; + N --> |const| Q[No]; + A --> R{Re-assignment}; + R --> |var| S[Yes]; + R --> |let| T[Yes]; + R --> |const| U[No]; + A --> V{Mutable}; + V --> |var| W[Yes]; + V --> |let| X[Yes]; + V --> |const| Y[No]; + ``` + +:::important +It is recommended to use `let` and `const` instead of `var` to declare variables. Use `let` when you want to declare a variable that can be re-assigned, and use `const` when you want to declare a variable that cannot be re-assigned. +::: + +## Conclusion + +In this tutorial, you learned about variables in JavaScript. You learned what variables are, how to declare and initialize variables, and the rules and best practices for naming variables. In the next tutorial, you will learn about data types in JavaScript. \ No newline at end of file diff --git a/docs/javascript/where-to-js.md b/docs/javascript/where-to-js.md new file mode 100644 index 000000000..d5d4f2418 --- /dev/null +++ b/docs/javascript/where-to-js.md @@ -0,0 +1,100 @@ +--- +id: where-to-js +title: Where to Write JavaScript +sidebar_label: Where to JavaScript +sidebar_position: 2 +tags: [JavaScript, Introduction of js, Introduction of JavaScript, Where to javascript ] +description: Where to write JavaScript code? Learn about the different places where JavaScript code can be written such as inline JavaScript, internal JavaScript, and external JavaScript. +--- + +JavaScript code can be written in three places: + +### 1. Inline JavaScript + +JavaScript code can be written directly in an HTML file in the HTML element's attribute. For example, in the `onclick` attribute of a button element. + +```html + + + + Inline JavaScript + + + + + +``` + + + + + +### 2. Internal JavaScript + +JavaScript code can be written in the ` + + + + + +``` + + + + + +### 3. External JavaScript + +JavaScript code can be written in an external file with a `.js` extension. The external JavaScript file can be linked to the HTML file using the ` + + + + + +``` + +```js title="script.js" +function sayHello() { + alert('Hello World!'); +} +``` + + + + + +:::tip + +1. It is recommended to write JavaScript code in an external file to separate the structure of the HTML file from the behavior of the web page. This makes the code more organized and easier to maintain. + +2. It helps to keep the HTML file clean and easy to read. It also allows the JavaScript code to be reused in multiple HTML files. + +3. The external JavaScript file should be linked to the HTML file using the ` + + +``` + +On the server, replace `__SERVER_DATA__` with a JSON object containing real data before sending the response. The client-side code can then read `window.SERVER_DATA` to access and use this data. + +:::warning +Remember to sanitize the JSON before sending it to the client to prevent XSS attacks. Always prioritize security! +::: + +## Conclusion: + +Congratulations! You've learned how to handle title and meta tags in your Create React App for back-end integration. By customizing your title and meta tags, you can enhance your website's visibility in search engines and deliver a better experience to your users. Remember to use React Helmet for more advanced management of your head elements and be cautious when dealing with server-side data to ensure security. Happy coding and creating! \ No newline at end of file diff --git a/docs/react/building-your-app/_category_.json b/docs/react/building-your-app/_category_.json new file mode 100644 index 000000000..898c0f562 --- /dev/null +++ b/docs/react/building-your-app/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Building Your App", + "position": 6, + "link": { + "type": "generated-index", + "description": "5 minutes to learn the most important RoadMap for React Mastery." + } + } \ No newline at end of file diff --git a/docs/react/building-your-app/adding-a-router.md b/docs/react/building-your-app/adding-a-router.md new file mode 100644 index 000000000..56c7afee1 --- /dev/null +++ b/docs/react/building-your-app/adding-a-router.md @@ -0,0 +1,102 @@ +--- +id: adding-a-router +title: Adding a Router +sidebar_position: 8 +tags: [react, react router, routing, react app, single-page application, spa, create react app, navigation, links, components] +keywords: [react, react router, routing, react app, single-page application, spa, create react app, navigation, links, components] +description: Learn how to add routing capabilities to your React app using React Router, enabling dynamic, multi-page applications without full-page refreshes. +--- + +## Introduction: +Welcome, fellow Coders! Today, we embark on an exciting journey to enhance our React app by adding routing capabilities. Routing allows us to create dynamic, multi-page applications without the need for full-page refreshes. Buckle up, and let's dive into the world of React Router! + +### 1: What is React Router? +React Router is a popular library that enables navigation and routing within a React application. It provides a seamless way to create multiple pages while maintaining a single-page app feel. Think of it as a virtual GPS system for your app, guiding users to different views without reloading the entire page. + +### 2: Getting Started +Before we hit the road, let's set up our project! Make sure you have Node.js and npm installed. If not, visit Node.js' official website and follow their easy installation guide. + +Once you have everything set up, create your React app using Create React App (CRA). In your terminal, type: + +```bash +npx create-react-app my-awesome-app +cd my-awesome-app +``` + +Now, we're ready to install React Router. Execute the following command: + +```bash +npm install react-router-dom +``` + +### 3: Creating Our Routes +Imagine your app is a fantastic theme park, and each attraction represents a different page. Let's map out our routes accordingly: + +1. **Home:** The main entrance to our park, where visitors start their journey. +2. **About:** An information booth to learn more about our park's history. +3. **Contact:** A helpline where visitors can reach out for any queries. +4. **NotFound:** A secret portal to another dimension for lost URLs (404 page). + +### 4: Setting Up the Router +Now that we have our routes planned out, let's integrate React Router into our app. Open the `src/App.js` file, and let the routing magic begin: + +```jsx title="src/App.js" +import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; +import Home from './components/Home'; +import About from './components/About'; +import Contact from './components/Contact'; +import NotFound from './components/NotFound'; + +function App() { + return ( + + + + + + + + + ); +} +``` + +### 5: Creating Our Components +To keep our code organized, let's create separate components for each route we defined earlier. For instance, create `Home.js`, `About.js`, `Contact.js`, and `NotFound.js` in the `src/components` folder. Don't forget to sprinkle some code wizardry into each component to make them shine! + +### 6: Linking It All Together +Now that we have our routes and components set up, we need navigation links for our visitors to explore the park. Update your `src/components/Home.js` with the following code: + +```jsx title="src/components/Home.js" +import { Link } from 'react-router-dom'; + +function Home() { + return ( +
+

Welcome to Code Mastermind Theme Park!

+ +
+ ); +} +``` +### 7: Celebrate Your Success! +Congratulations, Code Mastermind! You've successfully added React Router to your app, making it dynamic and user-friendly. Now, users can roam freely through your theme park without ever getting lost. + +### Apply your Idea's + +[Contribution Now](https://github.com/Ajay-Dhangar/react-blog-app/tree/main/) + +## Conclusion: +Routing in React is like a thrilling roller coaster ride for developers. We've just scratched the surface of what React Router can do. So keep exploring, experimenting, and creating breathtaking experiences for your users. Until next time, happy coding, Code Masterminds! 🎢 diff --git a/docs/react/building-your-app/adding-bootstrap.md b/docs/react/building-your-app/adding-bootstrap.md new file mode 100644 index 000000000..f49c0ade7 --- /dev/null +++ b/docs/react/building-your-app/adding-bootstrap.md @@ -0,0 +1,195 @@ +--- +id: adding-bootstrap +title: Adding Bootstrap +sidebar_position: 4 +tags: [react, create react app, bootstrap, css, styling, components, responsive, layout, design, ui, user interface, integration] +keywords: [react, create react app, bootstrap, css, styling, components, responsive, layout, design, ui, user interface, integration, npm, install, package, library, framework, pre-designed, enchanting, styles, responsive, layouts, components, buttons, forms, grid, system, columns, rows, container, app, project, example, tutorial, guide, how-to, learn, step-by-step, beginner, basics, introduction, overview, explanation, example, code, source, snippet, tutorial, guide, learn, how-to, steps] +description: Learn how to integrate Bootstrap into your Create React App, unlocking the power of pre-designed components, responsive layouts, and enchanting styles. +--- + +import './style.css' + + +:::tip +Welcome, aspiring Coders! In this guide, we'll unlock the power of Bootstrap and elevate your Create React App to new heights of elegance and style. +::: + +## Embrace the Magic of Bootstrap + +Bootstrap, a legendary CSS framework, bestows upon you a treasure trove of pre-designed components, responsive layouts, and enchanting styles. To wield its power, we shall embark on a mystical journey to integrate it into your Create React App. + +### Unleash Bootstrap with npm + +First, you need to install Bootstrap as one of your app's dependencies using npm. Open your terminal and type this arcane incantation: + +```bash +npm install bootstrap +``` + +The magical npm spirits will work their wonders, and Bootstrap will be summoned to your project. + +### Empower Your App with Bootstrap's Styling + +Now that Bootstrap resides within your project, it's time to harness its styles. Open the `src/index.js` file, the very heart of your application, and invoke the Bootstrap magic by adding the following line at the top: + +```javascript +import 'bootstrap/dist/css/bootstrap.min.css'; +``` + +With this spell, Bootstrap's captivating styles will weave their way into your app, imbuing it with elegance. + +## Casting Spells with Bootstrap Components + +Prepare to be amazed by Bootstrap's wondrous components! From spellbinding buttons to mysterious modals, you can now summon them with ease. + +### Invoking Buttons + +Buttons are the building blocks of any magical user interface. To conjure a Bootstrap button, simply create an element with the `btn` class: + +```jsx title="MagicalButton,jsx" +import React from 'react'; + +function MagicalButton() { + return ( + + ); +} +``` + +**Live Preview:** + + +
+ +
+
+ +### Live Coding: + +apply (try your self) other like: `btn-primary`, `btn-secondary`, `btn-success`, `btn-danger`, `btn-warning`, etc. + +```jsx live +function MagicalButton() { + return ( + + ); +} +``` + +### Enchanting Forms + +Spice up your forms with Bootstrap's form components. Behold, an input with the `form-control` class: + +```jsx title="MagicalForm.jsx" +import React from 'react'; + +function MagicalForm() { + return ( + + ); +} +``` + +**Live Preview:** + + +
+ +
+
+ +### Creating Responsive Layouts + +Bootstrap's responsive grid system grants you the ability to craft captivating layouts for any screen size. Embrace the power of rows and columns: + +```jsx title="ResponsiveLayout.jsx" +import React from 'react'; + +function ResponsiveLayout() { + return ( +
+
+
+

This is the left column.

+
+
+

This is the right column.

+
+
+
+ ); +} +``` + +**Live Preview:** + + +
+
+
+

This is the left column.

+
+
+

This is the right column.

+
+
+
+
+ +## A Grand Finale - A Live Example + +And now, for the grand finale, a live example demonstrating the fusion of React and Bootstrap. Witness the creation of a stunning app showcasing Bootstrap's magic: + +```jsx title="MagicalApp.jsx" +import React from 'react'; +import 'bootstrap/dist/css/bootstrap.min.css'; + +function MagicalApp() { + return ( +
+

Welcome to the Magical World of React and Bootstrap!

+

Prepare to be enchanted by the wonders they create together.

+ +
+
+ logo +
+
+

Discover Your Powers

+

Embark on a journey of coding mastery as you learn the secrets of React and the magic of Bootstrap. Your powers shall know no bounds!

+ +
+
+
+ ); +} + +export default MagicalApp; +``` + +**Live Preview:** + + +
+

Welcome to the Magical World of React and Bootstrap!

+

Prepare to be enchanted by the wonders they create together.

+
+
+ logo +
+
+

Discover Your Powers

+

Embark on a journey of coding mastery as you learn the secrets of React and the magic of Bootstrap. Your powers shall know no bounds!

+ +
+
+
+
+ +By reciting this mystical incantation, you shall witness the wonders of React and Bootstrap merging in harmony, crafting an exquisite and responsive user interface. + +May this knowledge serve as your guide in the mesmerizing realms of React and Bootstrap. May you code with joy and spread magic across the web! + +### Celebrate Your Success! + +You have successfully integrated Bootstrap into your Create React App, unlocking the power of pre-designed components, responsive layouts, and enchanting styles. Your app now radiates elegance and charm, ready to captivate the world. \ No newline at end of file diff --git a/docs/react/building-your-app/adding-custom-environment-variables.md b/docs/react/building-your-app/adding-custom-environment-variables.md new file mode 100644 index 000000000..7eb96d2ec --- /dev/null +++ b/docs/react/building-your-app/adding-custom-environment-variables.md @@ -0,0 +1,132 @@ +--- +id: adding-custom-environment-variables +title: Adding Custom Environment Variables +sidebar_label: Environment Variables +sidebar_position: 9 +tags: [environment, variables, env, custom, create react app, react, react-scripts, node, node.js, npm, start, build, test, production, development, local, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret,] +keywords: [environment, variables, env, custom, create react app, react, react-scripts, node, node.js, npm, start, build, test, production, development, local, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret, sensitive, information, security, configuration, settings, dynamic, value, html, css, js, bundle, server, placeholders, dotenv, expand, server, client, runtime, embed, build-time, process, api, key, secret,] +description: Learn how to add custom environment variables to your Create React App, empowering your app to configure differently based on the environment in which it runs. +--- + +Welcome, aspiring Coders, to the enchanting world of React development! In this guide, we will explore the magical realm of custom environment variables and how they empower your React applications. + +:::note +This feature is available with `react-scripts@0.2.3` and higher. +::: + + +## Introduction to Environment Variables + +Environment variables are like magical keys that unlock hidden powers for your React app. They allow you to configure your app differently based on the environment in which it runs. With Create React App, you get two special environment variables by default: `NODE_ENV` and any variable starting with `REACT_APP_`. + +:::caution Warning +Never store sensitive information like private API keys in your React app! Environment variables are embedded into the build, making them accessible to anyone inspecting your app's files. +::: + +## Understanding Build-time Embedding + +During the build process, Create React App embeds the environment variables into the static HTML/CSS/JS bundle. As a result, your app cannot access or change these variables at runtime. If you need dynamic values at runtime, you'd have to load HTML into memory on the server and replace placeholders. Alternatively, rebuild your app on the server each time the variables change. + +## Creating Custom Environment Variables + +To create custom environment variables, you must name them starting with `REACT_APP_`. Any other variables, except for `NODE_ENV`, will be ignored to prevent accidental exposure of private keys. + +For instance, to define a variable `REACT_APP_API_KEY`, you can do it in two ways: + +### Method 1: Shell Environment Variables (Temporary) + +For a temporary solution during your current shell session: + +#### Windows (cmd.exe) + +```cmd +set "REACT_APP_API_KEY=your-api-key" && npm start +``` + +#### Windows (Powershell) + +```Powershell +($env:REACT_APP_API_KEY = "your-api-key") -and (npm start) +``` + +#### Linux, macOS (Bash) + +```sh +REACT_APP_API_KEY=your-api-key npm start +``` + +### Method 2: .env File (Permanent) + +For permanent environment variables, create a file called `.env` in the root of your project and define your variables like this: + +``` +REACT_APP_API_KEY=your-api-key +``` + +:::tip +Environment variables defined in `.env` should be kept secret and not committed to source control. +::: + +### Using Custom Environment Variables in Your App + +Once you've defined your custom variables, you can access them in your code via `process.env`. For example, let's display the API key and the current environment in a component: + +```jsx title="MyComponent.jsx" +import React from 'react'; + +const MyComponent = () => { + return ( +
+

Your API key: {process.env.REACT_APP_API_KEY}

+

You are running in {process.env.NODE_ENV} mode.

+
+ ); +}; + +export default MyComponent; +``` + +During the build process, `process.env.REACT_APP_API_KEY` will be replaced with the actual value you defined in the environment variable. The value of `process.env.NODE_ENV` will be set automatically based on the build type: `'development'`, `'test'`, or `'production'`. + +## Leveraging Environment Variables in the HTML + +Starting with `react-scripts@0.9.0`, you can also use environment variables in `public/index.html`. For example: + +```html +%REACT_APP_WEBSITE_NAME% +``` + +Remember the same naming convention applies: the variable must start with `REACT_APP_`. + +## More `.env` Files and Environment-specific Settings + +From `react-scripts@1.0.0`, Create React App allows you to use different `.env` files for various environments: + +- `.env`: Default file. +- `.env.local`: Local overrides for all environments except `test`. +- `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. +- `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides for environment-specific settings. + +When multiple `.env` files are present, they follow the priority order: + +- `npm start`: `.env.development.local`, `.env.local`, `.env.development`, `.env` +- `npm run build`: `.env.production.local`, `.env.local`, `.env.production`, `.env` +- `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) + +Environment-specific variables serve as defaults if not explicitly set on the machine. + +## Expanding Variables in `.env` + +With `react-scripts@1.1.0` and higher, you can use variables already defined on your machine within your `.env` file using [dotenv-expand](https://github.com/motdotla/dotenv-expand). For example: + +``` +REACT_APP_VERSION=$npm_package_version +# or +REACT_APP_VERSION=${npm_package_version} +``` + +## Conclusion + +You've now mastered the art of adding custom environment variables to your Create React App! These magical keys will help you configure your app in various environments while keeping sensitive information secure. Remember to handle secrets carefully and avoid committing them to source control. + +Happy coding, and may your React apps enchant users across the realms of the web! diff --git a/docs/react/building-your-app/adding-flow.md b/docs/react/building-your-app/adding-flow.md new file mode 100644 index 000000000..e5d45e9f6 --- /dev/null +++ b/docs/react/building-your-app/adding-flow.md @@ -0,0 +1,197 @@ +--- +id: adding-flow +title: Adding Flow +sidebar_position: 5 +tags: [flow, static, type, checker, create react app, react, javascript, type safety, bug prevention, type annotations, union types, optional types, type checking, type errors, live example, flow-bin, flowconfig, vscode, vim, lsp, absolute imports, type annotations, union types, optional types, type checking, type errors, live example, flow-bin, flowconfig, vscode, vim, lsp, absolute imports] +keywords: [flow, static, type, checker, create react app, react, javascript, type safety, bug prevention, type annotations, union types, optional types, type checking, type errors, live example, flow-bin, flowconfig, vscode, vim, lsp, absolute imports, type annotations, union types, optional types, type checking, type errors, live example, flow-bin, flowconfig, vscode, vim, lsp, absolute imports] +description: Learn how to add Flow, a static type checker, to your Create React App, empowering your code with type safety and bug prevention. +--- + +Flow, a formidable static type checker, stands ready to protect your code from lurking bugs. Fear not, for we shall guide you on this thrilling journey into the realm of static types in JavaScript. If you are new to this concept, fear not! Delve into this [enchanting introduction](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) to discover the power of static types. + +:::note +Recent versions of [Flow](https://flow.org/) seamlessly integrate with Create React App projects. +::: + +## Introduction: +Welcome, aspiring Code Masterminds, to the magical world of Create React App! In this guide, we will delve into the realm of type checking and unveil the powers of Flow to bring order and certainty to your React applications. Prepare to embark on an adventure of static typing and fearless coding! + +[Flow's documentation](https://flow.org/) + +### 1: Introducing Flow - The Guardian of Types + +Meet Flow, a stalwart guardian bestowed upon us by the ancient sorcerers at Facebook. Flow is a static type checker that adds an extra layer of protection to your JavaScript code, ensuring that it adheres to predefined types and preventing sneaky bugs from infiltrating your app. + + +### 2: Unleashing Flow in Your Create React App (Dance of Installation) + +Let us begin our quest by integrating Flow into your Create React App project. Fear not, for the path is straightforward. + +Prepare to summon Flow into your Create React App project by performing a few delicate steps: + +1. Utter the incantation `npm install --save flow-bin` (or `yarn add flow-bin`) to add Flow to your magical dependencies. +2. Inscribe the sacred command `"flow": "flow"` into the `scripts` section of your `package.json` to harness Flow's power. +3. Invoke the initiation ritual `npm run flow init` (or `yarn flow init`) to conjure a [`.flowconfig` file](https://flow.org/en/docs/config/) at your project's core. +4. Fortify your code with the mark of Flow - `// @flow`. Bestow this incantation upon any files you wish to bless with type checking, such as `src/App.js`. + +### 3: Unleashing the Magic + +Behold the power Flow bestows upon you! With a simple command, `npm run flow` (or `yarn flow`), Flow will roam through your files, inspecting for lurking bugs and ensuring harmony among types. + +Let us not forget the comforts of modern coding. Embrace extensions like [Flow Language Support](https://github.com/flowtype/flow-for-vscode) for Visual Studio Code or the wondrous Language Server Protocol standard (e.g. [vim LSP](https://github.com/prabirshrestha/vim-lsp/wiki/Servers-Flow)) to receive hints as you weave your code. + +### 4: The Elegance of Absolute Imports + +Should you seek the elegance of absolute imports while dancing with Flow, heed this secret. Enchant your `.flowconfig` with the following: + +```diff + [options] ++ module.name_mapper='^\([^\.].*\)$' -> '/src/\1' +``` + +Let the magic of this incantation make Flow aware of your desires. + +### 5: Casting Spells - Annotating Your Code with Types + +Now that Flow is up and running, it's time to adorn your code with type annotations. Brace yourself, for the power of type annotations will make your code more robust and comprehensible. + +```js +// @flow +function addNumbers(a: number, b: number): number { + return a + b; +} + +const result: number = addNumbers(4, 5); +``` + +Observe how the `number` type annotations indicate that `a` and `b` are expected to be numbers, and the function itself will return a number. Flow will diligently check if the types match during development, sparing you the anguish of runtime errors. + +### 6: Magical Unions and Optional Types + +Flow bestows upon us the gift of union types, allowing variables to possess multiple possible types. Behold this example: + +```javascript +// @flow +function getLength(value: string | Array): number { + return value.length; +} +``` + +In this spellbinding incantation, `value` can be either a string or an array. Flow gracefully accepts this union of types and validates the code accordingly. + +Moreover, Flow also offers the blessing of optional types. Take a look: + +```javascript +// @flow +type User = { + name: 'Ajay Dhangar', + age?: 22, +}; + +function getUserInfo(user: User): string { + if (user.age) { + return `Name: ${user.name}, Age: ${user.age}`; + } else { + return `Name: ${user.name}`; + } +} +``` + +Here, the `age` property of the `User` type is marked as optional with the `?` symbol. Flow acknowledges this optionality and allows for graceful handling within the `getUserInfo` function. + +### 7: Vanquishing Bugs - Leveraging Flow's Power + +Flow is not just about type annotations; it also possesses the power to unearth hidden bugs lurking within your code. With a simple command, `npx flow`, Flow will perform static analysis on your codebase, detecting potential type errors and revealing them to you. Let Flow guide you on your path to bug-free coding! + +### 8: The Spell of a Live Example + +In the grand tradition of Code Mastermind HQ, behold a live example to witness the power of Flow in action. Brace yourself as you explore this enchanting example, complete with code snippets and a detailed explanation: + +## Live Example For Better Understanding + +Absolutely! Here's a simple working live example of using Flow in a Create React App. This example demonstrates how to add type annotations to a component's props and state, and how Flow helps to catch type errors during development. + +1. Create a new React app using Create React App: + + ```bash title="terminal (bash)" + npx create-react-app flow-example-app + cd flow-example-app + ``` + +2. Install Flow: + + ```bash title="terminal (bash)" + npm install --save flow-bin + ``` + +3. Initialize Flow: + + ```bash title="terminal (bash)" + npx flow init + ``` + +4. Add `// @flow` to `App.js` to enable type checking: + + ```js title="App.js" + // App.js + // @flow + import React, { Component } from 'react'; + + type Props = { + name: 'Ajay', + }; + + type State = { + age: 23, + }; + + class App extends Component { + state = { + age: 25, + }; + + render() { + const { name } = this.props; + const { age } = this.state; + + return ( +
+

Hello, {name}!

+

You are {age} years old.

+
+ ); + } + } + + export default App; + ``` + +5. Run the app and check for type errors: + + ```bash + npm start + ``` + +6. You can now access the app at `http://localhost:3000`. The component `App` now expects a `name` prop of type `string`, and its state contains an `age` property of type `number`. + + +
+

Hello, name: Ajay!

+

You are 23 years old.

+
+
+ + If you attempt to use the component without providing the `name` prop or try to set the `age` to a non-numeric value, Flow will catch these type errors and display them in your terminal. + + With this live example, you can witness how Flow enhances your React app's robustness and detects potential type-related issues during development, saving you from future bugs and headaches. + + Remember to install Flow globally on your system if you haven't already, and make sure to use the `// @flow` pragma in files you wish to enable type checking for. + + May this example empower you to embrace the magic of Flow and wield the power of static typing in your React adventures! Happy coding! + +## Conclusion: +Congratulations, dear apprentice! You have mastered the art of integrating Flow into your Create React App and harnessing its magic to strengthen your codebase. With Flow as your companion, you can fearlessly journey through the lands of React, confident in the knowledge that your types are checked and your code is resilient. + +Remember, the path of a Code Mastermind is one of continuous learning and growth. Embrace the power of type checking and let Flow be your guiding light as you unlock new realms of coding excellence! + +May your code be elegant, your types be sound, and your journey be filled with joy. Happy coding, and may the magic of Flow be with you always! \ No newline at end of file diff --git a/docs/react/building-your-app/adding-relay.md b/docs/react/building-your-app/adding-relay.md new file mode 100644 index 000000000..ff284877e --- /dev/null +++ b/docs/react/building-your-app/adding-relay.md @@ -0,0 +1,211 @@ +--- +id: adding-relay +title: Adding Relay +sidebar_position: 7 +tags: [ react, relay, graphql, create react app, data fetching, data management, efficient, performance, batching, coalescing, over-fetching, server, client, network, environment, store, query, fragment, component, routing, react-router-dom, react-router, react-router-config, react-relay, graphql, relay-runtime, relay-environment-provider, relay-environment, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching, relay-server, relay-client, relay-network, relay-environment, relay-store, relay-query, relay-fragment, relay-component, relay-routing, relay-graphql, relay-optimization, relay-performance, relay-batching, relay-coalescing, relay-over-fetching] +description: Learn how to integrate Relay into your Create React App, enabling efficient data fetching and management from a GraphQL server in your React applications. +--- + +## Introduction to Relay + +Relay is a powerful GraphQL client framework developed by Facebook. It allows you to efficiently fetch and manage data from a GraphQL server in your React applications. Relay optimizes data fetching by batching and coalescing requests, reducing over-fetching and making your app more performant. + +## Prerequisites + +Before we begin, make sure you have the following installed: + +1. Node.js and npm (Node Package Manager) - You can download it from the official website: https://nodejs.org/ + +2. Create React App - You can create a new React application using Create React App with the following command in your terminal: + + ```bash + npx create-react-app my-relay-app + cd my-relay-app + ``` + +3. Basic knowledge of React and GraphQL will be helpful, but we'll try to explain everything in a beginner-friendly way. + +## Adding Relay to Your Create React App + +Let's integrate Relay into your Create React App project. + +### Step 1: Install Dependencies + +Open your terminal, navigate to your project directory, and install the necessary packages: + +```bash +npm install relay react-relay +``` + +### Step 2: Setup Relay Environment + +Relay requires a network layer to communicate with your GraphQL server. For this example, we'll use the GitHub GraphQL API. Open your `src` folder and create a new file named `relay-environment.js`: + +```javascript title="src/relay-environment.js" + +import { Environment, Network, RecordSource, Store } from 'relay-runtime'; + +async function fetchGraphQL(operation, variables) { + const response = await fetch('https://api.github.com/graphql', { + method: 'POST', + headers: { + Authorization: 'Bearer YOUR_GITHUB_ACCESS_TOKEN', // Replace with your GitHub access token + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: operation.text, + variables, + }), + }); + return await response.json(); +} + +const environment = new Environment({ + network: Network.create(fetchGraphQL), + store: new Store(new RecordSource()), +}); +export default environment; +``` + +Replace `YOUR_GITHUB_ACCESS_TOKEN` with a valid GitHub Personal Access Token. You can create one by following the steps in this guide: https://docs.github.com/en/authentication/creating-a-personal-access-token. + +### Step 3: Update index.js + +Now, let's make sure our app uses the Relay environment. Open `src/index.js` and update it as follows: + +```javascript title="src/index.js" + +import React from 'react'; +import ReactDOM from 'react-dom'; +import { RelayEnvironmentProvider } from 'react-relay'; +import environment from './relay-environment'; +import App from './App'; + +ReactDOM.render( + + + , + document.getElementById('root') +); +``` + +### Step 4: Writing Your First Relay Query + +In this example, we'll fetch a user's details from the GitHub API using Relay. Create a new file named `User.js` inside the `src` folder: + +```javascript title"src/User.js" + +import React from 'react'; +import { graphql, useFragment } from 'react-relay'; + +const userFragment = graphql` + fragment User_user on User { + name + login + avatarUrl + } +`; + +function User(props) { + const user = useFragment(userFragment, props.user); + return ( +
+ {user.name} +

{user.name}

+

{user.login}

+
+ ); +} + +export default User; +``` + +### Step 5: Create a Relay Query Component + +Now, let's create a component that uses the `User` component and fetches the data using Relay. Create a new file named `Profile.js` inside the `src` folder: + +```javascript title="src/Profile.js" + +import React from 'react'; +import { graphql, useLazyLoadQuery } from 'react-relay'; + +const profileQuery = graphql` + query ProfileQuery { + viewer { + ...User_user + } + } +`; + +function Profile() { + const data = useLazyLoadQuery(profileQuery, {}); + return ; +} + +export default Profile; +``` + +### Step 6: Add Routing (Optional) + +To view the user profile, we'll add routing to your app using `react-router-dom`. First, install the package: + +```bash +npm install react-router-dom +``` + +Then, update `src/App.js`: + +```javascript title="src/App.js" + +import React from 'react'; +import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; +import Profile from './Profile'; + +function App() { + return ( + +
+ + + + + + + +

Welcome to My Relay App

+
+
+
+
+ ); +} + +export default App; +``` + +### Step 7: Start Your App + +Now, you're all set! Save your changes and start your app: + +```bash +npm start +``` + +Visit `http://localhost:3000/profile` to see your Relay-powered user profile page! + +## Conclusion + +Congratulations! You've successfully integrated Relay into your Create React App and fetched data from the GitHub API. This is just the beginning of what Relay can do for your React applications. Continue exploring Relay's documentation and its powerful features to take your app to the next level. + +:::tip Info +Remember to replace the GitHub API with your own GraphQL API to experiment further with Relay. Happy coding! +::: \ No newline at end of file diff --git a/docs/react/building-your-app/adding-typescript.md b/docs/react/building-your-app/adding-typescript.md new file mode 100644 index 000000000..87a892e4d --- /dev/null +++ b/docs/react/building-your-app/adding-typescript.md @@ -0,0 +1,72 @@ +--- +id: adding-typescript +title: Adding TypeScript +sidebar_position: 6 +tags: [react, adding-typescript, typescript] +description: "Learn how to add TypeScript to your Create React App project. Enhance your code with type safety and unleash the power of TypeScript in your React applications." +--- + +:::note +> **Attention, aspiring wizards of code!** +> Welcome to a magical journey where we shall unleash the power of TypeScript upon our Create React App. Fear not, for this enchanting endeavor shall aid you in writing more robust and delightful spells in the realm of React! +::: + +## Introduction: + +Welcome, brave Code Apprentices, to the realm of TypeScript—a powerful sorcery that brings type safety and enchanting possibilities to your JavaScript spells. In this guide, we shall embark on an epic quest to integrate TypeScript into your Create React App, paving the way for a magical journey of robust and error-free coding! + +### 1: Embrace the TypeScript Magic + +TypeScript, a captivating typed superset of JavaScript, compiles to pure JavaScript, bringing clarity and precision to your code incantations. But fear not, for its integration is swift and graceful. To commence your journey, ensure your `react-scripts` version is 2.1.0 or higher, and invoke the sacred command: + +```sh +npx create-react-app my-app --template typescript +``` + +Or, if you are a follower of the yarn tradition: + +```sh +yarn create react-app my-app --template typescript +``` + +Fear not, for a seamless TypeScript setup awaits you! + +### 2: Enchanting Existing Projects + +For seasoned adventurers with existing Create React App projects, the path to TypeScript enlightenment is equally accessible. Embark on this path by installing the following mystical packages: + +```sh +npm install --save typescript @types/node @types/react @types/react-dom @types/jest +``` + +Or let yarn's magic weave its wonders: + +```sh +yarn add typescript @types/node @types/react @types/react-dom @types/jest +``` + +But be mindful, to unlock the true essence of TypeScript, bestow upon your files the illustrious `.tsx` extension (e.g., `src/index.js` to `src/index.tsx`). And lo, as you cast your eyes upon your code, a [`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) shall emerge, guiding your TypeScript endeavors. + +Finally, to invoke the full powers of TypeScript, perform the sacred rite: **restart your development server!** Your creation shall now be shielded by the embrace of type safety. + +Behold, as the veil of type errors reveals itself in the console! Fear not, for by resolving these, you shall wield the mighty powers of TypeScript and take your React project to new heights. For the intrepid explorers, [advanced configuration](../advanced-usage/advanced-configuration.md) awaits! + +### 3: Venturing into TypeScript and React + +Dear adventurers, rejoice, for the journey has only begun! As you dive deeper into the depths of TypeScript, treasure troves of knowledge await: + +- [The TypeScript Handbook](https://www.typescriptlang.org/): An exquisite tome that unveils the secrets of TypeScript's arcane syntax and features. +- [TypeScript Example on React](https://www.typescriptlang.org/play/index.html?jsx=2&esModuleInterop=true&e=196#example/typescript-with-react): A magical sandbox where you can experiment with TypeScript in the realm of React. +- [React + TypeScript Cheatsheets](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#reacttypescript-cheatsheets): A sacred manuscript offering invaluable insights into the fusion of React and TypeScript. + +### 4: Overcoming Challenges and Sorcery + +In every adventurer's journey, challenges arise, and even TypeScript is not immune. Should you encounter the absence of TypeScript in your creation, heed this advice: cast away the lingering shadows of cached versions by uninstalling `create-react-app` globally. Allow `npx` to guide you to the latest version, ever fresh and powerful! + +As you grow in wisdom, be mindful of the limitations of TypeScript and Babel. Constant enums and namespaces may elude you in this union, but fret not! [Understanding the constraints](https://babeljs.io/docs/en/babel-plugin-transform-typescript#caveats) shall aid your path to enlightenment. + +## Conclusion: + +Congratulations, esteemed Code Apprentices! You have harnessed the power of TypeScript within your React projects, ushering in an era of type safety and spellbinding possibilities. Let your code flourish in the embrace of TypeScript, safeguarded from the clutches of runtime errors! + +Remember, the journey of a Code Apprentice is never-ending, filled with knowledge and growth. Embrace TypeScript's magic and let your code inspire and dazzle fellow adventurers. May your journey be filled with wonder and enchantment! \ No newline at end of file diff --git a/docs/react/building-your-app/importing-a-component.md b/docs/react/building-your-app/importing-a-component.md new file mode 100644 index 000000000..efcd77ada --- /dev/null +++ b/docs/react/building-your-app/importing-a-component.md @@ -0,0 +1,96 @@ +--- +id: importing-a-component +title: Importing Components in React +sidebar_label: Importing a Component +sidebar_position: 2 +tags: [react, import, component, importation, import, export, module, file, path, relative, absolute, jsx, javascript, code, code-splitting, dynamic, lazy, suspense, react.lazy, react.suspense, dynamic-import, import, export, module, file, path, relative, absolute, jsx, javascript, code, code-splitting, dynamic, lazy, suspense, react.lazy, react.suspense, dynamic-import] +description: "Learn how to import components in your React applications. Unleash the magic of component importation and integrate them into your app with ease!" +--- + +Welcome, brave Code Masterminds, to the wondrous world of component importation! In this guide, we shall unravel the secrets of importing components in your React applications, enabling you to summon their powers and weave them into the fabric of your app. + +## The Art of Component Summoning + +When crafting your React masterpiece, you'll often encounter the need to import components from external sources. Fear not, for we shall equip you with the mystical knowledge to achieve this feat! + +To import a component, follow these steps: + +**Step 1:** Prepare your spellbook (a.k.a. your code editor) and open the file where you wish to import the component. + +**Step 2:** Utter the sacred incantation, starting with the `import` keyword. Specify the name of the component you wish to summon, and assign it to a variable of your choosing. + +```jsx +import { ComponentName } from './path/to/component'; +``` + +Here, `ComponentName` represents the name you desire for your component variable, and `'./path/to/component'` refers to the relative path of the component file from the current file. Feel free to customize these as per your needs! + +**Step 3:** With the component summoned, you are now ready to employ its powers within your code. Invoke it as a JSX tag, just like any other HTML element, and witness the magic unfold! + +```jsx title="MyMagicalApp.jsx" +import { ComponentName } from './path/to/component'; + +function MyMagicalApp() { + return ( +
+

Welcome to My Magical App!

+ +
+ ); +} +``` + +Voilà! You have successfully summoned and integrated the component into your app. The magic of React is now at your fingertips! + +## A Live Example to Unleash the Magic + +To solidify your understanding, let us embark on a mystical journey with a live example. Imagine you possess a component called `Wizard`, capable of conjuring spells and enchantments. We shall import this component and unleash its powers within our app. + +**Step 1:** Create a new file called `Wizard.jsx` and add the following code: + +```jsx title="Wizard.jsx" +import React from 'react'; + +function Wizard() { + return

I am a Wizard! Prepare to be amazed!

; +} + +export default Wizard; +``` + +**Step 2:** Open your main app file (e.g., `App.js`) and import the `Wizard` component: + +```jsx title="App.js" +import React from 'react'; +import Wizard from './Wizard'; + +function App() { + return ( +
+

Welcome to My Magical App!

+ +
+ ); +} + +export default App; +``` + +Behold the power of importation! The `Wizard` component shall grace your app, displaying the majestic message "I am a Wizard! Prepare to be amazed!" + + + +
+

Welcome to My Magical App!

+

I am a Wizard! Prepare to be amazed!

+
+ +
+ +## Conclusion + +Congratulations, dear apprentice! You have mastered the art of importing components in your React app. With this newfound knowledge, you can now summon and integrate a myriad of components to bring your app to life. + +Remember, the path of a Code Mastermind is filled with curiosity and exploration. Experiment with different components, combine their powers, and create awe-inspiring React applications that mesmerize the world! + +May your code be elegant, your components harmonious, and your journey through React be filled with laughter and enchantment. \ No newline at end of file diff --git a/docs/react/building-your-app/installing-a-dependency.md b/docs/react/building-your-app/installing-a-dependency.md new file mode 100644 index 000000000..c2c1a3d21 --- /dev/null +++ b/docs/react/building-your-app/installing-a-dependency.md @@ -0,0 +1,106 @@ +--- +id: installing-a-dependency +title: Installing a Dependency +sidebar_label: Dependency +sidebar_position: 1 +tags: [react, create react app, npm, dependencies, package, install, installation, node package manager, react-scripts, react-dom, react-icons, react-scripts, react-app, react-app-template] +description: Learn how to install a dependency in your Create React App project. Unleash the power of enchanting packages and add new spells to your React app with the help of npm. +--- + +:::note +Welcome, brave apprentice! Let's embark on a magical quest of installing dependencies in your enchanted Create React App. Fear not, for we shall guide you through the mystical process step-by-step. +::: + +## 🧙‍♂️ The Art of Dependency Sorcery + +In the realm of React, dependencies are powerful allies that bestow extraordinary abilities upon your app. These magical spells come in the form of packages, designed and crafted by the brilliant wizards of the open-source community. + +## 📦 Unveiling the Magic of `npm` + +To summon these powerful allies, we shall wield the mighty `npm`, also known as Node Package Manager. `npm` is the gateway to a vast library of enchanting packages. With a single incantation, it can fetch and install any spell your heart desires. + +## 🔮 The Chant of Installation + +Let's dive into the process of installing a dependency. Open your command-line spellbook, and within the enchanted directory of your Create React App, invoke the sacred incantation: + +```bash +npm install +``` + +Replace `` with the name of the magical package you wish to add. For instance, if you seek the powers of a styling spell called `awesome-styler`, the chant shall be: + +```bash +npm install awesome-styler +``` + +## 🌟 Casting the Spell - A Live Example + +Behold! As a testament to our guidance, we shall demonstrate the mystical art of installing a dependency with a live example. + +### Step 1: Create Your Enchanted React App + +First, create a new Create React App. In your command-line spellbook, execute: + +```bash +npx create-react-app magical-app +cd magical-app +``` + +### Step 2: Unleash the Spell + +Now, it is time to summon a magical package! Let's bring forth the mystical `react-icons`, a library full of captivating icons for your app. + +```bash +npm install react-icons +``` + +### Step 3: Wield the Magic + +Open the spellbook of your React app, and behold the wonders of `react-icons`. Cast the spell by adding this code to your enchanted `App.js`: + +```jsx +import React from 'react'; +import { FaReact } from 'react-icons/fa'; + +const App = () => { + return ( +
+

Welcome to Your Magical App!

+

Behold the sacred symbol of React:

+ +
+ ); +}; + +export default App; +``` + +### Step 4: Enchant the World + +With your spell complete, return to your command-line spellbook, and recite the following: + +```bash +npm start +``` + + + +
+

Welcome to Your Magical App!

+

Behold the sacred symbol of React:

+ +
+ +
+ +Witness the magic come to life as your app springs forth with the enchanting `FaReact` icon, symbolizing the power of React! + +## 🎉 Celebration and Further Exploration + +Congratulations, brave apprentice! You have delved into the secrets of installing dependencies and wielded the magic of `react-icons`. But fear not, for this is just the beginning of your journey. + +Explore the vast magical repository of `npm`, and discover new spells to enhance your creations. Unravel the mysteries of more complex dependencies and conquer the challenges that lie ahead. + +Remember, the quest of a developer is a never-ending adventure, filled with wonder, excitement, and endless possibilities. + +May your code be bug-free, and your creativity know no bounds. Onwards to new magical horizons! \ No newline at end of file diff --git a/docs/react/building-your-app/making-a-progressive-web-app.md b/docs/react/building-your-app/making-a-progressive-web-app.md new file mode 100644 index 000000000..e96209632 --- /dev/null +++ b/docs/react/building-your-app/making-a-progressive-web-app.md @@ -0,0 +1,120 @@ +--- +id: making-a-progressive-web-app +title: Making a Progressive Web App with Create React App +sidebar_label: Making a Progressive Web App +sidebar_position: 10 +tags: [] +keywords: [ create react app, react, react-scripts, node, node.js, npm, start, build, test, production, development, local, pwa, progressive web app, service worker, caching, offline, access, fast, loading, engaging, experience, responsive, design, web, mobile, app, native, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript, responsive, devices, desktop, smartphone, tablet, reliable, fast, engaging, offline, access, responsive, design, service, workers, caching, strategies, user, experience, user, retention, web, technologies, html, css, javascript] +description: Learn how to turn your regular React application into a fully-fledged Progressive Web App (PWA) using Create React App. +--- + +Welcome to the exciting world of Progressive Web Apps (PWAs)! In this guide, we'll explore how to turn your regular React application into a fully-fledged PWA using Create React App. + +## What is a Progressive Web App (PWA)? + +Progressive Web Apps (PWAs) are modern web applications that provide a native app-like experience to users, combining the best of web and mobile apps. They are reliable, fast, and engaging, and they work offline too! + +PWAs are built using web technologies like HTML, CSS, and JavaScript and are designed to be responsive across different devices, including desktops, smartphones, and tablets. They are a great way to enhance user experience and boost user retention. + +A Progressive Web App is a web application that takes advantage of modern web technologies to deliver an enhanced user experience. PWAs are designed to be fast, reliable, and engaging, providing a native-app-like feel to users while being accessible directly from their web browsers. + +## Why build a PWA? + +PWAs offer several benefits: + +1. **Offline Access:** PWAs can work offline or in low-network conditions, allowing your users to access your app anytime, anywhere. + +2. **Fast Loading:** With service workers and caching strategies, PWAs load quickly, reducing bounce rates and keeping users engaged. + +3. **Engaging Experience:** PWAs can be installed on users' devices, providing a more immersive experience without the need to visit an app store. + +4. **Responsive Design:** PWAs adapt to different screen sizes and devices, ensuring a seamless experience across all platforms. + +## Prerequisites + +Before we begin, make sure you have the following: + +- Node.js and npm installed on your machine. +- Basic knowledge of React.js and Create React App. + +## Let's Get Started! + +### Step 1: Create a new Create React App project + +If you haven't already, let's create a new React project using Create React App: + +```bash +npx create-react-app my-pwa-app +cd my-pwa-app +``` + +### Step 2: Install the Workbox Library + +Workbox is a powerful library that simplifies service worker creation and caching strategies. To install Workbox, run the following command in your project directory: + +```bash +npm install workbox-webpack-plugin --save-dev +``` + +### Step 3: Update the Service Worker + +Now, let's create a service worker file and configure it to cache our app's assets for offline access. Create a new file called `service-worker.js` in the `public` folder and add the following code: + +```javascript title="public/service-worker.js" + +import { precacheAndRoute } from 'workbox-precaching'; + +// Precache all the assets generated by webpack +precacheAndRoute(self.__WB_MANIFEST); +``` + +### Step 4: Configure the Webpack to Use the Service Worker + +Next, we need to configure Create React App to use our service worker during the build process. Open the `webpack.config.js` file located in the `config` folder and make the following changes: + +```javascript title="config/webpack.config.js" + +const { InjectManifest } = require('workbox-webpack-plugin'); + +module.exports = function override(config, env) { + if (env === 'production') { + // Add the Workbox plugin to generate the service worker + config.plugins.push(new InjectManifest({ + swSrc: './public/service-worker.js', + // Add any additional configuration options here + })); + } + return config; +}; +``` + +### Step 5: Build your PWA + +With the configuration in place, it's time to build your PWA: + +```bash +npm run build +``` + +### Step 6: Test your PWA Locally + +You can now test your PWA locally by serving the production build: + +```bash +npm install -g serve +serve -s build +``` + +Visit `http://localhost:5000` in your web browser to see your awesome PWA in action! + +### Step 7: Deploy your PWA + +To share your PWA with the world, deploy it on a hosting platform like Vercel, Netlify, or GitHub Pages. + +Congratulations! You've just transformed your React app into a Progressive Web App. Users will now enjoy a faster, more engaging experience with offline access. Enjoy the power of PWAs! + +## Conclusion + +In this guide, we've explored the process of creating a Progressive Web App using Create React App. By implementing service workers and caching strategies, your app is now capable of running offline and delivering a fantastic user experience. + +Remember, PWAs are a constantly evolving field, so keep exploring new possibilities and enhancing your app to provide the best user experience possible. Happy coding! diff --git a/docs/react/building-your-app/measuring-performance.md b/docs/react/building-your-app/measuring-performance.md new file mode 100644 index 000000000..22c7001d8 --- /dev/null +++ b/docs/react/building-your-app/measuring-performance.md @@ -0,0 +1,138 @@ +--- +id: measuring-performance +title: Measuring Performance in React with Create React App +sidebar_label: Measuring Performance +sidebar_position: 11 +tags: [react, performance, web vitals, lighthouse, react devtools, performance.measure, react profiler, performance, web vitals, lighthouse, react devtools, performance.measure, react profiler, performance, web vitals, lighthouse, react devtools, performance.measure, react profiler, performance, web vitals, lighthouse, react devtools, performance.measure, react profiler] +description: Learn how to measure and optimize the performance of your React app using Create React App. Unleash the power of Web Vitals, Lighthouse, and React DevTools to create a blazing-fast user experience! +--- + +Create React App comes with a built-in feature to help you measure and analyze your app's performance. It uses something called "Web Vitals," which are helpful metrics that capture how users experience your web page. Let's see how we can use this powerful tool to optimize your app! + +## Measuring Performance in Your React App + +Create React App comes with a built-in feature to help you measure and analyze your app's performance. It uses something called "Web Vitals," which are helpful metrics that capture how users experience your web page. Let's see how we can use this powerful tool to optimize your app! + +## What are Web Vitals? + +Web Vitals are metrics that tell us about the user experience of a web page. They help us understand how fast the page loads, how quickly it responds to user actions, and more. This way, we can make our app snappier and delightful for users. + +## Introduction + +When building a React app, it's essential to ensure that it performs optimally to provide a smooth and responsive user experience. Measuring the performance of your React application can help you identify potential bottlenecks and optimize its speed and efficiency. In this guide, we'll explore some practical techniques for measuring performance using Create React App (CRA), a popular tool for bootstrapping React projects. + +## 1. Why Measure Performance? + +Imagine you have created a fantastic React app with stunning visuals and innovative features, but it feels sluggish and unresponsive. Users may get frustrated and abandon your app, leading to a loss in engagement and potential customers. Measuring performance helps you: + +- **Identify Performance Issues:** By analyzing metrics, you can pinpoint areas where your app might be slow or inefficient. + +- **Optimize User Experience:** Improving performance leads to faster load times, smoother interactions, and happier users. + +- **Boost Conversion Rates:** A performant app encourages users to stick around and engage more, which can lead to higher conversion rates. + +Now, let's dive into how you can measure the performance of your React app effectively. + +## 2. Performance Metrics to Track + +Before we start measuring, let's understand the essential performance metrics: + +- **First Contentful Paint (FCP):** This metric measures the time from navigation to when the first content appears on the screen. A lower FCP indicates a faster-loading app. + +- **Time to Interactive (TTI):** TTI measures how long it takes for the app to become fully interactive. Users can click buttons or interact with elements after this point. + +- **Total Blocking Time (TBT):** TBT calculates the total duration when the app is unresponsive to user input due to long tasks running on the main thread. + +- **Memory Usage:** Monitoring memory consumption helps you identify memory leaks and improve resource management. + +## 3. Using Lighthouse for Performance Auditing + +Create React App comes with excellent tools for performance auditing, and one such tool is Google Lighthouse. Lighthouse is an open-source tool that can help you assess various aspects of your app's performance, accessibility, and more. + +To use Lighthouse, follow these steps: + +1. Open your app in Google Chrome. +2. Press `F12` or right-click and select "Inspect" to open DevTools. +3. Click on the "Lighthouse" tab. +4. Choose the desired categories (Performance, Accessibility, etc.). +5. Click "Generate Report." + +Lighthouse will analyze your app and provide a detailed report with suggestions to improve performance. + +## 4. Analyzing Performance with React DevTools + +React DevTools is another powerful tool for measuring performance and debugging React applications. It's available as a browser extension and allows you to inspect React component hierarchies, state changes, and performance profiles. + +To get started with React DevTools: + +1. Install the extension in your preferred browser. +2. Open your app and launch DevTools (`F12` or right-click and select "Inspect"). +3. Look for the "React" or "Components" tab in the DevTools panel. + +You can use React DevTools to check component rendering times, identify unnecessary re-renders, and optimize your app's performance. + +## 5. Manual Performance Profiling + +For more advanced performance analysis, you can manually profile your app using the following approaches: + +- **Performance.measure():** This API allows you to measure custom metrics and performance between specific points in your code. + +- **React Profiler:** This built-in component provides detailed information about rendering time, re-renders, and component hierarchies. + +## Getting Started + +To start measuring Web Vitals, all you need to do is use the `reportWebVitals` function in your `index.js` file. It's as simple as passing a function to it, like this: + +```js +reportWebVitals(console.log); +``` + +This function will give you the final values of various metrics after they finish calculating on the page. You can log these results to the console or even send them to an analytics endpoint. + +## Sending Results to Analytics + +By sending Web Vitals data to analytics, you can track how your app performs in the real world for actual users. Here's an example of how to send the results to an analytics endpoint: + +```js +function sendToAnalytics(metric) { + const body = JSON.stringify(metric); + const url = 'https://example.com/analytics'; + + // Use `navigator.sendBeacon()` if available, falling back to `fetch()` + if (navigator.sendBeacon) { + navigator.sendBeacon(url, body); + } else { + fetch(url, { body, method: 'POST', keepalive: true }); + } +} + +reportWebVitals(sendToAnalytics); +``` + +:::note Note for Google Analytics Users +If you use Google Analytics, you can send the results to it using the `id` value. This helps you easily analyze and calculate important metrics. +::: + +```js +function sendToAnalytics({ id, name, value }) { + ga('send', 'event', { + eventCategory: 'Web Vitals', + eventAction: name, + eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers + eventLabel: id, // id unique to the current page load + nonInteraction: true, // avoids affecting bounce rate + }); +} + +reportWebVitals(sendToAnalytics); +``` + +That's it! With these simple steps, you can now measure your app's performance and make it faster and more enjoyable for your users. + +## Conclusion + +Measuring performance is a critical step in the development process. By using tools like Lighthouse and React DevTools, along with manual profiling techniques, you can identify performance bottlenecks and optimize your React app for a better user experience. + +Remember, a faster app not only delights your users but also improves your chances of success in the competitive world of web development! + +Now go ahead, measure your app's performance, and unleash the true potential of your React project! \ No newline at end of file diff --git a/docs/react/building-your-app/production-build.md b/docs/react/building-your-app/production-build.md new file mode 100644 index 000000000..03d548ab5 --- /dev/null +++ b/docs/react/building-your-app/production-build.md @@ -0,0 +1,127 @@ +--- +id: production-build +title: Creating a Production Build in Create React App +sidebar_label: Production Build +sidebar_position: 12 +tags: [react, create react app, production build, react build, production build, create react app production build, react production build, create react app build, react build, production build, create react app production build, react production build, create react app build, react build, production build, create react app production build, react production build, create react app build, react build, production build, create react app production build, react production build, create react app build, react build, production build, create react app production build, react production build, create react app build, react build, production build ] +keywords: ["create react app production build", "react production build", "create react app build", "react build", "production build", "create react app production build", "react production build", "create react app build", "react build", "production build", "create react app production build", "react production build", "create react app build", "react build", "production build", "create react app production build", "react production build", "create react app build", "react build", "production build" ] +description: Learn how to create a production build for your React app using Create React App. Optimize your code, reduce file sizes, and enhance performance for your users with this enchanting guide! +--- + +Welcome, aspiring developers, to the magical world of React production builds! In this enchanting guide, we'll walk you through the process of creating a production build for your Create React App. Brace yourselves for optimized code, faster load times, and an immersive user experience! + +## Understanding Production Builds + +Before we set sail on our quest, let's unravel the mystery of production builds. During development, we often use a special mode that helps with debugging and hot-reloading. But when it's time to release our app into the wild, we want it to be nimble and performant. Enter the production build! + +A production build is the polished and optimized version of your React app. It reduces file sizes, implements caching techniques, and enhances performance for your end-users. Imagine your app transforming from a budding sapling to a majestic oak tree—ready to stand tall in the digital forest! + +### 📁 Static File Caching 🚀 + +When you create a production build in Create React App, a fascinating magic happens! Each file inside the `build/static` directory receives a unique hash 🧙‍♂️. It's like a secret spell that's generated based on the file's contents 📝. This enchanting hash allows us to use aggressive caching techniques ✨. Imagine it as a magical seal that prevents the browser from re-downloading your assets if nothing has changed 🚫🔄. + +For instance, let's say your React app has a magical image ✨🌟 that rarely changes, like your logo. During the first build, the image gets a unique hash in its filename, like `logo.abc123.png` 🎇. When you deploy your app, the browser happily caches this logo with its magical seal for a year 🗓️. + +Now, imagine you decide to update the image slightly. No worries! During the subsequent build, the contents of the image change, and voilà, a new unique hash is born 🎉. The updated image now has a filename like `logo.xyz456.png`. Since the filename hash has changed, the browser knows it's time to download the new version with excitement 🎊. + +To deliver the ultimate performance to your users, you can use the Cache-Control header 📜. Think of it as a scroll of command that controls the caching duration. For example, you can set `Cache-Control: max-age=31536000` for your `build/static` assets, like your JavaScript and CSS files. This delightful spell ensures that your user's browser will cache these files for a whole year 🗓️. + +Now, imagine you have a spellbinding HTML file, your `index.html`, which might change more often than the static assets. In this case, you can set `Cache-Control: no-cache` for your `index.html`. This clever trick ensures the browser will always check for an updated version of your HTML spellbook whenever your app is revisited 📖. + +To sum it all up, using these caching spells wisely ensures your users will experience the magic of your app with lightning-fast loading times and a delightful user experience! 🌟⚡ + +### 🎭 Profiling: Peek Behind the Curtain! + +In the magical land of React, performance profiling is like gazing into a crystal ball, revealing the secrets of your app's performance. 🌟 + +In development mode (v16.5+), ReactDOM automatically supports profiling without any special incantations. However, in production mode, profiling remains hidden, adding just a touch of extra magic. To unveil its powers, you must opt-in using the `--profile` flag. 🧙‍♂️ + +Imagine you're preparing for the grand performance of your app, and you want to ensure it shines like a dazzling star. To enable profiling in the production build, wave your wand (terminal) and chant: + +```bash +npm run build -- --profile +``` + +Or if you prefer yarn magic: + +```bash +yarn build --profile +``` + +Now, behold the wondrous React DevTools! 🌌 They hold the key to understanding your app's performance like never before. Consult the [React docs](https://reactjs.org/docs/optimizing-performance.html#profiling-components-with-the-devtools-profiler) to master the art of using the DevTools Profiler. It's like learning to control the elements! 🔥💨💧🌪 + +Just as a talented performer perfects their craft by studying their act, you, too, can dive into your app's performance to discover hidden bottlenecks and optimize its speed and efficiency. 🎉 + + +## The Production Build Process + +To create a production build in Create React App, you'll need Node.js and npm (Node Package Manager) installed on your computer. If you don't have them already, head to https://nodejs.org and follow the installation instructions. + +Now, let's dive into the steps to create a magical production build: + +### Step 1: Navigate to Your App Directory + +Open your favorite terminal or command prompt and navigate to your React app's root directory. If you're not sure where it is, run the following command to create a new React app: + +```bash +npx create-react-app my-awesome-app +cd my-awesome-app +``` + +Replace `my-awesome-app` with your desired app name. + +### Step 2: Cast the Spell of Optimization + +With your wand (terminal) in hand, it's time to unleash the power of optimization upon your app. To create the production build, run the following command: + +```bash +npm run build +``` + +This command works its magic and conjures a `build` directory containing your production-ready app. + +### Step 3: Unveil the Artifacts + +Behold, the fruits of your labor are revealed within the `build` directory! Inside the `build/static` folder, you'll find the precious JavaScript and CSS files. Each filename will be appended with a unique hash, like a secret spell, to enable [long term caching techniques](#-static-file-caching-). + +Additionally, you'll encounter several `.js` files, also known as _chunks_, within the `build/static/js` directory: + +- `main.[hash].chunk.js`: This houses your application code, including your beloved `App.js`. + +- `[number].[hash].chunk.js`: These files contain either _vendor_ code or [code splitting chunks](../styles-and-assets/code-splitting.md). _Vendor_ code includes modules imported from `node_modules`. Separating _vendor_ and _application_ code allows for better caching and improved loading performance. + +- `runtime-main.[hash].js`: This small chunk of [webpack runtime](https://webpack.js.org/configuration/optimization/#optimization-runtimechunk) logic is used to load and run your application. By default, it's embedded in your `build/index.html` file to save a network request. + +### Step 4: Embrace Static File Caching + +In the realm of production builds, caching is a powerful ally for performance. Each file inside `build/static` has a unique hash based on its contents. This enables [aggressive caching techniques](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#invalidating_and_updating_cached_responses), preventing unnecessary re-downloads when file contents haven't changed. + +To optimize caching, specify a `Cache-Control` header for both `index.html` and the files within `build/static`. This header controls the caching duration for the browser and Content Delivery Networks (CDNs). Here's an example of setting `Cache-Control` headers: + +```html + + + + + + Header set Cache-Control "max-age=31536000" + +``` + +With these caching spells in place, your app's static assets will be cached for a year, and your users will enjoy a delightful experience. + +### Step 5: Profiling Your App (Optional) + +For those who wish to dive deeper into the magical arts of performance optimization, React offers profiling in development mode (v16.5+). In production mode, profiling is opt-in, providing insights into your app's performance. To enable profiling, add the `--profile` flag when running the build command: + +```bash +npm run build -- --profile +``` + +With profiling activated, you can leverage the React DevTools to delve into the mysteries of your app's performance. For more details, visit the [React Docs](https://reactjs.org/docs/optimizing-performance.html#profiling-components-with-the-devtools-profiler). + +## Conclusion + +Congratulations, young wizards! You've successfully mastered the art of creating a production build for your React app. Now, your code is optimized, your performance is enchanting, and your users will be spellbound by the experience. As you embark on your coding adventures, remember to cast the spells of optimization and caching to create truly magical web applications! + +May your code be bug-free, your designs be captivating, and your journey be filled with awe-inspiring creations. Happy coding! diff --git a/docs/react/building-your-app/style.css b/docs/react/building-your-app/style.css new file mode 100644 index 000000000..ee43220e3 --- /dev/null +++ b/docs/react/building-your-app/style.css @@ -0,0 +1,136 @@ +.btn { + display: inline-block; + font-weight: 400; + text-align: center; + white-space: nowrap; + vertical-align: middle; + user-select: none; + border: 1px solid transparent; + padding: 0.375rem 0.75rem; + font-size: 1rem; + line-height: 1.5; + border-radius: 0.25rem; + transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, + border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; +} + +.btn-primary { + color: #fff; + background-color: #007bff; + border-color: #007bff; +} + +.btn-primary:hover { + background-color: #0056b3; + border-color: #0056b3; +} + +.btn-primary:focus { + box-shadow: 0 0 0 0.2rem rgba(38, 143, 255, 0.5); +} + +.btn-success { + color: #fff; + background-color: #28a745; + border-color: #28a745; +} + +.btn-success:hover { + background-color: #218838; + border-color: #1e7e34; +} + +.btn-success:focus { + box-shadow: 0 0 0 0.2rem rgba(72, 180, 97, 0.5); +} + +.btn-danger { + color: #fff; + background-color: #dc3545; + border-color: #dc3545; +} + +.btn-danger:hover { + background-color: #c82333; + border-color: #bd2130; +} + +.btn-danger:focus { + box-shadow: 0 0 0 0.2rem rgba(225, 83, 97, 0.5); +} + +.btn-warning { + color: #212529; + background-color: #ffc107; + border-color: #ffc107; +} + +.btn-warning:hover { + background-color: #e0a800; + border-color: #d39e00; +} + +.btn-warning:focus { + box-shadow: 0 0 0 0.2rem rgba(255, 213, 106, 0.5); +} + +.btn-secondary { + color: #fff; + background-color: #6c757d; + border-color: #6c757d; +} + +.btn-secondary:hover { + background-color: #6c757e; + border-color: #dae0e5; +} + +.btn-secondary:focus { + box-shadow: 0 0 0 0.2rem rgba(216, 217, 219, 0.5); +} + +.form-control { + font-size: 16px; + padding: 10px; + border: 1px solid #ccc; + border-radius: 4px; + box-shadow: none; + outline: none; + transition: border-color 0.2s ease-in-out; +} + +.form-control:focus { + border-color: #80bdff; + box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); +} + +.row { + display: flex; + flex-wrap: wrap; + margin: 0 -15px; +} +@media screen and (max-width: 365px) { + .row { + display: block; + } +} +.col-sm-6 { + flex: 0 0 50%; + max-width: 50%; + padding: 15px; + box-sizing: border-box; + font-size: 18px; +} + +.mt-4 { + margin-top: 16px; +} + +.mt-5 { + margin-top: 3rem !important; +} + +.lead { + font-size: 16px; + line-height: 1.5; +} diff --git a/docs/react/building-your-app/using-global-variables.md b/docs/react/building-your-app/using-global-variables.md new file mode 100644 index 000000000..9a73e839e --- /dev/null +++ b/docs/react/building-your-app/using-global-variables.md @@ -0,0 +1,225 @@ +--- +id: using-global-variables +title: Using Global Variables +sidebar_position: 3 +tags: [react, global, variables, global-variables, global-variables-in-react, global-variables-in-javascript, global-variables-in-react-app, global-variables-in-react-component, global-variables-in-react-application, global-variables-in-react-js, global-variables-in-react-jsx, global-variables-in-react-javascript, global-variables-in-react-jsx-javascript, global-variables-in-react-jsx-component, global-variables-in-react-jsx-application, global-variables-in-react-jsx-app, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-javascripts, global-variables-in-react-jsx-javascript, global-variables-in-react-jsx-apps, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-component, global-variables-in-react-jsx-application, global-variables-in-react-jsx-app, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-javascripts, global-variables-in-react-jsx-javascript, global-variables-in-react-jsx-apps, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-component, global-variables-in-react-jsx-application, global-variables-in-react-jsx-app, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-javascripts, global-variables-in-react-jsx-javascript, global-variables-in-react-jsx-apps, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-component, global-variables-in-react-jsx-application, global-variables-in-react-jsx-app, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-javascripts, global-variables-in-react-jsx-javascript, global-variables-in-react-jsx-apps, global-variables-in-react-jsx-applications, global-variables-in-react-jsx-components, global-variables-in-react-jsx-component, global-variables-in-react-jsx-application, global-variables-in-react-jsx-app, global-variables-in-react-jsx-applications, global-variables-in-react-jsx] +description: "Learn how to use global variables in your React applications. Unleash the magic of global variables and wield their power to share data across your entire app!" +--- + +:::note +*Attention, aspiring Coders! Let's delve into the arcane world of global variables. Fear not, for this knowledge shall empower you to wield their magic with finesse.* +::: + +## The Mysterious Realm of Global Variables + +Welcome to the mystical realm of global variables—a source of both power and peril in the world of React. These special entities hold information that can be accessed from anywhere within your enchanted application. + +But beware, dear apprentice! With great power comes great responsibility. Mishandling global variables can lead to chaos and tangled spells within your code. + +## The Enchantment Spell: Defining a Global Variable + +Let us cast the incantation to define a global variable. Within the sacred halls of your `src` folder, create a file named `env.js`. It shall be our vessel to hold the magic: + +```js title="src/env.js" +const globalWizardName = 'Merlin'; +export default globalWizardName; +``` + +Behold, `globalWizardName` is now accessible throughout your sorcery, for it has been declared within the mystical realm of global variables! + +## The Spellbook: Accessing the Global Variable + +Now that we have conjured our global variable, let us learn how to access its power. Within any of your enchanted components, simply recite the `import` spell and invoke the global variable: + +```jsx title="src/components/MagicComponent.jsx" +// src/components/MagicComponent.jsx +import React from 'react'; +import globalWizardName from '../env'; + +const MagicComponent = () => { + return ( +
+

Welcome, esteemed apprentice, to the realm of {globalWizardName}!

+

Prepare to embark on a journey of magical coding.

+
+ ); +}; + +export default MagicComponent; +``` + + +
+

Welcome, esteemed apprentice, to the realm of Merlin!

+

Prepare to embark on a journey of magical coding.

+
+
+ +See how `globalWizardName` enriches your component with its knowledge? Embrace its power, but always remember to wield it responsibly. + +## The Bewitching Dance: Using the Global Variable in Your Spells + +Now that you've grasped the essence of global variables, let us create a spellbinding example using them. + +**Step 1:** Create a new component, `SpellComponent.jsx`, and import the global variable: + +```js title="src/components/SpellComponent.jsx" +// src/components/SpellComponent.jsx +import React from 'react'; +import globalWizardName from '../env'; + +const SpellComponent = () => { + const spellText = `Hear my words, for I invoke the great ${globalWizardName}!`; + + return ( +
+

Behold the Magic Spell:

+

{spellText}

+
+ ); +}; + +export default SpellComponent; +``` + +Step 2: Embrace the unity of spells by adding `SpellComponent` to your main enchantment, `App.js`: + +```js title="src/App.js" +// src/App.js +import React from 'react'; +import MagicComponent from './components/MagicComponent'; +import SpellComponent from './components/SpellComponent'; + +const App = () => { + return ( +
+ + +
+ ); +}; + +export default App; +``` + + +**Step 3:** Witness the magic come alive as you run your application! The mystical words of the great `{globalWizardName}` shall grace your screen. + + +
+
+

Welcome, esteemed apprentice, to the realm of Merlin!

+

Prepare to embark on a journey of magical coding.

+
+
+

Behold the Magic Spell:

+

Hear my words, for I invoke the great Merlin!

+
+
+
+ +## The Perils of the Dark Arts: Misusing Global Variables + +Ah, but heed this warning, dear apprentice! Misusing global variables can lead to unexpected enchantments and tangled webs of code. + +**Example of a Dark Spell:** + +```js title="src/components/DarkComponent.jsx" +// src/components/DarkComponent.jsx +import React from 'react'; +import globalWizardName from '../env'; + +const DarkComponent = () => { + globalWizardName = 'Voldemort'; // Oops! You shall not reassign a const from the magical realm! + + return ( +
+

Dark Arts Warning:

+

{`Beware, ${globalWizardName} is a name not to be spoken lightly!`}

+
+ ); +}; + +export default DarkComponent; +``` + +:::tip +Greetings, young Code Apprentices! This knowledge is unveiled with `react-scripts@3.0.0` and higher. +::: + +## Unleashing the Power of Global Variables + +Behold, the realm of global variables—a mystical concept that grants you the ability to wield data accessible across your entire React kingdom. However, heed this warning, dear beginners: global variables are both a potent weapon and a treacherous pitfall. With great power comes great responsibility. + +### The Forbidden Artifact - The Global Object + +In the enchanted lands of Create React App, there exists a powerful artifact called the "Global Object." It is an omnipotent entity that can hold any data you desire, accessible from any corner of your kingdom. But beware! Mishandling this artifact may lead to chaos, bugs, and cursed code. + +As guardians of the React realm, we advocate for the wise use of global variables. But first, let us uncover their hidden potential. + +### Discovering the Global Object's True Form + +To conjure the Global Object, you must invoke its essence within your React spells. Fear not, for it is a natural part of the cosmic order and requires no additional incantations. + +In your JavaScript tomes, simply access the Global Object using the mystical keyword `window`. Witness its grandeur in the code snippet below: + +```jsx +// A noble variable, fit for the Global Object +const mysticalData = 'I am available across the realm!'; + +// Binding the noble variable to the Global Object +window.globalVariable = mysticalData; +``` + +### Beware the Pitfalls of Unbridled Magic + +As the wise elders of the React realm advise, global variables must be used with caution. Excessive use of this power may lead to unpredictable behavior and jeopardize the harmony of your code. + +Remember, dear apprentices, the React way encourages the use of state management libraries like Redux or React Context for managing shared data. These time-honored practices ensure order and maintain the sanctity of your codebase. + +### A Tale of Practicality - A Live Example + +Let us weave a tale of practicality, where global variables serve a noble purpose in enhancing our application. + +In this example, we shall bestow our React kingdom with a day-night toggle switch—a magical artifact that changes the theme of our site. + +```jsx live +// Within the enchanted lands of React, we create a functional component +function DayNightToggle () { + // Embrace the power of state to control the day and night + const [isDay, setDay] = useState(true); + + // A mystical function to toggle the day and night + const toggleDayNight = () => { + setDay((prevIsDay) => !prevIsDay); + }; + + // The enchanted return statement, where we create the toggle + return ( +
+ +

{isDay ? 'Good day, brave traveler!' : 'Good night, weary soul.'}

+
+ ); +} +``` + +With this enchanting example, the DayNightToggle component shall bring harmony and joy to your React kingdom, all thanks to the wise use of global variables. + +### Parting Wisdom + +Remember, dear Code Apprentices, global variables are powerful tools—tools that should be used sparingly and judiciously. Embrace the React way, and you shall discover the true beauty of state management libraries, which offer a more structured and scalable approach to shared data. + +Go forth now, and may your React kingdom flourish with enchanted code and mesmerizing user experiences! + +## In Conclusion + +Congratulations, aspiring wizard! You have unlocked the secrets of global variables and wielded their power in your magical React spells. + +But remember, with great power comes great responsibility. Use global variables wisely, and your journey into the enchanted realm of React shall be filled with joy and triumph. + +Now, go forth and create wondrous applications, for you are now equipped with the knowledge to conjure and control the magic of global variables! + +May your code be bug-free and your spells enchanting. Onwards to new magical horizons! \ No newline at end of file diff --git a/docs/react/create-react-app.md b/docs/react/create-react-app.md new file mode 100644 index 000000000..cc86729bf --- /dev/null +++ b/docs/react/create-react-app.md @@ -0,0 +1,65 @@ +--- +id: create-react-app +title: Getting Started with React +sidebar_label: Create React App +sidebar_position: 1 +description: Development and implementation the API of interaction of two sites +--- + +Welcome to the React tutorial series! In this comprehensive guide, we will take you through the fundamentals of React, a popular JavaScript library for building user interfaces. Whether you're a beginner or have some experience with web development, this tutorial will provide you with a solid foundation to start building dynamic and interactive web applications using React. + +### Content Agenda: + +1. Introduction to React + - What is React? + - Why use React? + - React's key features +2. Setting Up the Development Environment + - Installing Node.js and npm + - Creating a new React project + - Familiarizing with the project structure +3. Components and JSX + - Understanding React components + - Writing JSX code + - Rendering components +4. State and Props + - Managing component state + - Passing data using props + - Updating state and re-rendering +5. Handling Events + - React event handling + - Binding event handlers + - Handling form submissions +6. Working with Lists and Conditional Rendering + - Rendering dynamic lists of data + - Conditional rendering based on state +7. React Router + - Introduction to React Router + - Setting up routes + - Navigating between pages +8. Introduction to React Hooks + - Understanding Hooks + - useState and useEffect + - Custom Hooks +9. Working with APIs + - Fetching data from APIs + - Async/await and Promises + - Error handling and loading states +10. Deploying React Apps + - Preparing your app for deployment + - Deploying to platforms like Vercel or Netlify + - Optimizing your app for production + +Throughout this tutorial, we will provide practical examples, code snippets, and exercises to help reinforce your understanding of React. By the end of the series, you'll have the skills and knowledge to build your own React applications from scratch. + +## Feedback + +We value your feedback! If you have any suggestions, questions, or issues related to Create React App or this documentation, please don't hesitate to reach out to us. Your input helps us improve the documentation and provide a better experience for all users. + +To provide feedback, you can: +- Send us an email at ajaydhangar49@gmail.com +- Open an issue on our GitHub repository: [issue](https://github.com/Ajay-Dhangar/code-harbor-hub/issues) +- Join our community forum and engage in discussions: [Discussions](https://github.com/Ajay-Dhangar/code-harbor-hub/discussions) + +We appreciate your contribution in making Create React App even better! + diff --git a/docs/react/css/style.css b/docs/react/css/style.css new file mode 100644 index 000000000..b898eddf2 --- /dev/null +++ b/docs/react/css/style.css @@ -0,0 +1,20 @@ + @media (prefers-reduced-motion: no-preference) { + .App-logo { + animation: App-logo-spin infinite 20s linear; + } + } + + @keyframes App-logo-spin { + from { + transform: rotate(0deg); + } + + to { + transform: rotate(360deg); + } + } + + .error{ + background-color: red; + } + \ No newline at end of file diff --git a/docs/react/deployment/_category_.json b/docs/react/deployment/_category_.json new file mode 100644 index 000000000..4c6b8fdfb --- /dev/null +++ b/docs/react/deployment/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Deployment", + "position": 9, + "link": { + "type": "generated-index", + "description": "5 minutes to learn the most important RoadMap for React Mastery." + } + } \ No newline at end of file diff --git a/docs/react/deployment/deployment.md b/docs/react/deployment/deployment.md new file mode 100644 index 000000000..a1969e6e8 --- /dev/null +++ b/docs/react/deployment/deployment.md @@ -0,0 +1,103 @@ +--- +id: deployment +title: Deployment in Create React App +sidebar_label: Deployment +sidebar_position: 1 +tags: [react, create-react-app, deployment, vercel, hosting, deployment-platform, production, build, optimization, deployment-steps, deployment-guide, deployment-process, deployment-platforms, deployment-tutorial, deployment-instructions, deployment-in-react, deployment-in-CRA, deployment-in-Create-React-App, Vercel, Vercel-deployment, Vercel-tutorial, Vercel-guide, Vercel-deployment-guide, Vercel-deployment-tutorial, Vercel-deployment-instructions, Vercel-deployment-process, Vercel-deployment-platform, Vercel-deployment-steps] +description: "Learn how to deploy your Create React App to the internet using Vercel. Follow the steps to optimize your app, choose a deployment platform, and deploy your app with Vercel." +--- + + +Congratulations, Coders! You've built an amazing React application using Create React App (CRA), and now it's time to show it to the world. In this guide, we'll walk you through the process of deploying your React app step by step, sprinkled with some fun details along the way! + +## What is Deployment? + +Imagine you've cooked a delicious pizza, and now you want to share it with your friends at a party. Deployment is like serving your app to the internet so that anyone can access it using a web browser. Just like your friends can enjoy the pizza without knowing the recipe, users can use your app without seeing its code! + +## Prerequisites + +Before we begin, make sure you have the following: + +**1. Your completed React app:** If you haven't built it yet, check out our guides on [creating a React app](../getting-started/getting-started.md) and [building components](../building-your-app/importing-a-component) to get started. + +**2. A version control system:** If you haven't set up Git yet, don't worry! It's like a time-travel machine for your code, allowing you to go back in time if needed. + +## Step 1: Optimize Your App + +Before deployment, let's optimize your React app to make it run faster and smoother. This way, users won't have to wait long for your app to load! + +**Fun Fact:** Optimizing your app is like making your pizza taste even better by adding extra cheese and your favorite toppings! + +To optimize, open your terminal and navigate to your project's root directory. Run the following command: + +```bash +npm run build +``` + +This will create a production-ready version of your app with minimized code and optimized assets. The build folder will be generated, ready for deployment. + +## Step 2: Choose a Deployment Platform + +Now that your app is ready to be served, you need to choose a platform to deploy it. There are several options, but for simplicity, we'll use Vercel, a fantastic platform that makes deployment a breeze. + +**Fun Fact:** Vercel is like a magical teleportation device for your app. It will take your app from your computer to the internet in seconds! + +Sign up for a Vercel account at [vercel.com](https://vercel.com) if you haven't already. Don't worry; it's free for most small projects! + +## Step 3: Deploy with Vercel + +Once you have a Vercel account, follow these simple steps to deploy your app: + +1. Install the Vercel CLI (Command-Line Interface) by running this command: + +```bash +npm install -g vercel +``` + +2. Log in to your Vercel account using the CLI: + +```bash +vercel login +``` + +3. Now, it's time to deploy your app! Run this command in your project's root directory: + +```bash +vercel --prod +``` + +**Fun Fact:** Deploying with Vercel is like putting your pizza in a high-speed delivery drone. It will fly your app to the cloud, where users can access it globally! + +4. Vercel will provide you with a unique URL for your deployed app. Share this URL with your friends, family, and the world! + +## Step 4: Celebrate! + +You did it! Your React app is now live on the internet, and anyone can access it. Take a moment to celebrate your achievement! + +**Fun Fact:** Celebrating is like enjoying a slice of pizza after all your hard work. You deserve it! + +## Updating Your App + +As you continue to improve your app, you might want to deploy new versions. Don't worry; it's as easy as eating a second slice of pizza! + +1. Make your changes to the app. + +2. Run the build command again: + +```bash +npm run build +``` + +3. Deploy the updated app to Vercel: + +```bash +vercel --prod +``` + +Vercel will take care of updating your app, and the new version will be live in no time! + +## Conclusion + +You've learned how to deploy your Create React App like a pro! Remember, the more you practice deploying apps, the better you'll become at it. So keep building, optimizing, and deploying! + +**Fun Fact:** Just like mastering the art of making pizza, deploying apps will make you a coding maestro! \ No newline at end of file diff --git a/docs/react/development/_category_.json b/docs/react/development/_category_.json new file mode 100644 index 000000000..acef1f498 --- /dev/null +++ b/docs/react/development/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Development", + "position": 4, + "link": { + "type": "generated-index", + "description": "5 minutes to learn the most important RoadMap for React Mastery." + } + } \ No newline at end of file diff --git a/docs/react/development/analyzing-the-bundle-size.md b/docs/react/development/analyzing-the-bundle-size.md new file mode 100644 index 000000000..f79599096 --- /dev/null +++ b/docs/react/development/analyzing-the-bundle-size.md @@ -0,0 +1,63 @@ +--- +id: analyzing-the-bundle-size +title: Analyzing Bundle Size +sidebar_label: Analyzing Bundle Size +sidebar_position: 3 +tags: [react, create-react-app, source-map-explorer, bundle-size, performance] +description: "Learn how to analyze the bundle size of your Create React App project using Source Map Explorer. Identify areas of your codebase that might be bloated and optimize them for better performance." +--- + +If you want to understand where the excess code in your JavaScript bundles is coming from, you can use a helpful tool called Source Map Explorer. In this guide, we'll learn how to add Source Map Explorer to your Create React App project and analyze the bundle size. + +## Installation + +To get started, follow these steps: + +1. Open your command line interface. + +2. If you're using npm, run the following command: +```sh +npm install --save source-map-explorer +``` + If you prefer using yarn, use this command instead: +```sh +yarn add source-map-explorer +``` + +## Configuration + +Once you've installed Source Map Explorer, you need to configure your project to use it. Here's how: + +1. Open your `package.json` file. + +2. Locate the `"scripts"` section and add the following line: +```diff + "scripts": { ++ "analyze": "source-map-explorer 'build/static/js/*.js'", + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", +``` + This adds a new script named `"analyze"` that will run Source Map Explorer on your production build. + +## Analyzing the Bundle + +Now that you've set up Source Map Explorer, it's time to analyze your bundle size. Follow these steps: + +1. Run the production build command in your command line interface: +```sh +npm run build +``` + This command generates the optimized and minified version of your React app. + +2. After the build process completes, run the analyze script: +```sh +npm run analyze +``` + Source Map Explorer will open in your default browser and display a visual representation of your bundle. It will show you which parts of your code contribute the most to the bundle size. + +By analyzing the bundle size, you can identify areas of your codebase that might be bloated and optimize them for better performance. + +Congratulations! You now know how to use Source Map Explorer to analyze the bundle size of your Create React App project. + +Remember to regularly analyze your bundle size to ensure your app remains fast and efficient. diff --git a/docs/react/development/developing-components-in-isolation.md b/docs/react/development/developing-components-in-isolation.md new file mode 100644 index 000000000..9c51ce431 --- /dev/null +++ b/docs/react/development/developing-components-in-isolation.md @@ -0,0 +1,83 @@ +--- +id: developing-components-in-issolation +title: Developing Components in Isolation +sidebar_label: Developing Components +sidebar_position: 2 +tags: [react, storybook, react-styleguidist, components, ui, development, isolation, preview, states, storybook-for-react, react-styleguidist] +description: "Learn how to develop and preview your React components in isolation from your main app using Storybook or React Styleguidist. Create a convenient way to work on components individually and view all their states." +--- + +In a typical app, you have various UI components, each having multiple states. Let's take a basic button component as an example, which can have the following states: + +- Regular state with a text label. +- Disabled mode. +- Loading state. + +However, it can be challenging to visualize these states without running a sample app or looking at examples. + +By using third-party tools like [Storybook for React](https://storybook.js.org) or [React Styleguidist](https://react-styleguidist.js.org/), you can develop and preview your components in isolation from your main app. These tools provide a convenient way to work on components individually and view all their states. + +![Storybook for React Demo](https://raw.githubusercontent.com/storybookjs/storybook/next/docs/get-started/storybook-third-party-docs.gif) + +Additionally, you can deploy your Storybook or style guide as a static app, allowing your team members to review different UI component states without the need for a backend server or creating app accounts. + +## Getting Started with Storybook + +Storybook is a development environment specifically designed for React UI components. It enables you to browse a component library, view different states of each component, and interactively develop and test your components. + +To set up Storybook in your project, run the following command within your app's directory: + +```sh +npx sb init +``` + +Follow the instructions displayed on the screen after running the command. + +Here are some resources to learn more about React Storybook: + +- [Learn Storybook (tutorial)](https://storybook.js.org/tutorials/) +- [Documentation](https://storybook.js.org/docs/react/get-started/introduction) +- [GitHub Repo](https://github.com/storybooks/storybook) +- [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot + +## Getting Started with Styleguidist + +Styleguidist is another useful tool that combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, and an environment for developing components in isolation, similar to Storybook. In Styleguidist, you write examples in Markdown, and each code snippet is rendered as a live editable playground. + +To install Styleguidist, use the following command: + +```sh +npm install --save react-styleguidist +``` + +Alternatively, you can use `yarn`: + +```sh +yarn add react-styleguidist +``` + +After installing Styleguidist, add the following scripts to your `package.json` file: + +```diff + "scripts": { ++ "styleguide": "styleguidist server", ++ "styleguide:build": "styleguidist build", + "start": "react-scripts start", +``` + +To start the Styleguidist server, run the following command within your app's directory: + +```sh +npm run styleguide +``` + +Follow the instructions provided on the screen to continue setting up Styleguidist. + +Here are some resources to learn more about React Styleguidist: + +- [GitHub Repo](https://github.com/styleguidist/react-styleguidist) +- [Documentation](https://react-styleguidist.js.org/docs/getting-started.html) + +Now, whenever you make a commit, Prettier will automatically format the changed files. If you want to format your entire project for the first time, you can run `./node_modules/.bin/prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}"`. + +To integrate Prettier into your favorite editor, refer to the [Editor Integration](https://prettier.io/docs/en/editors.html) section on the Prettier GitHub page. diff --git a/docs/react/development/setting-up-your-editor.md b/docs/react/development/setting-up-your-editor.md new file mode 100644 index 000000000..883d0f76d --- /dev/null +++ b/docs/react/development/setting-up-your-editor.md @@ -0,0 +1,166 @@ +--- +id: setting-up-your-editor +title: Setting Up Your Editor +sidebar_label: Editor Setup +sidebar_position: 1 +tags: [react, create-react-app, editor, syntax-highlighting, linting, debugging, code-formatting, prettier, vscode, webstorm] +description: "Learn how to set up your text editor for working with Create React App. Enhance your editing experience and maximize productivity with these tips." +--- + +When working with Create React App, there are several tools you can use to enhance your editing experience and maximize productivity. Let's go through some tips to get your editor set up correctly. + +## Syntax Highlighting + +To enable syntax highlighting in your favorite text editor, you can refer to the [Babel documentation page](https://babeljs.io/docs/editors) for instructions. Most popular editors have coverage in the documentation. + +## Displaying Lint Output in the Editor + +:::note +- This feature requires `react-scripts@0.2.0` or higher. + +- For projects created with `react-scripts@2.0.3` or higher, this feature works out of the box. + +- Please ensure you have npm 3 or higher. +::: + +Some editors like Sublime Text, Atom, and Visual Studio Code provide ESLint plugins for displaying linting output in the editor. However, these plugins are not mandatory. You will still see the linting results in your terminal and browser console by default. If you prefer to view the linting results directly in your editor, you can install an ESLint plugin or extension. + +Keep in mind that any customizations made to your ESLint config will only affect the editor integration, not the terminal or in-browser lint output. Create React App intentionally provides a minimal set of rules to catch common mistakes. + +If you want to enforce a specific coding style for your project, you can consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. + +### Extending or Replacing the Default ESLint Config + +You have the option to extend the base ESLint config provided by Create React App or replace it entirely, depending on your needs. Here are a few things to remember: + +1. We highly recommend extending the base config instead of removing it completely, as removing it may introduce hard-to-find issues. +2. When working with TypeScript, you'll need to provide an `overrides` object to apply rules specifically to TypeScript files. +3. It's important to note that any rules set to `"error"` will prevent the project from building. + +In the example below: + +- The base config is extended by a shared ESLint config. +- A new rule is added that applies to all JavaScript and TypeScript files. +- Another new rule is added that targets TypeScript files only. + +```json +{ + "eslintConfig": { + "extends": ["react-app", "shared-config"], + "rules": { + "additional-rule": "warn" + }, + "overrides": [ + { + "files": ["**/*.ts?(x)"], + "rules": { + "additional-typescript-only-rule": "warn" + } + } + ] + } +} +``` + +## Debugging in the Editor + +**This feature currently supports only [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** + +Create React App provides built-in support for debugging in Visual Studio Code and WebStorm, allowing you to write and debug your React code seamlessly within the editor. This minimizes the need for context switching between tools and provides a continuous development workflow. + +### Visual Studio Code + +Make sure you have the latest version of [VS Code](https://code.visualstudio.com) installed. + +To enable debugging in VS Code, add the following block to your `launch.json` file, located inside the `.vscode` folder in your app's root directory: + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000", + "webRoot": "${workspaceFolder}/src", + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + } + ] +} +``` + +:::note +- If you've adjusted the HOST or PORT environment variables, the URL may be different. +::: +Start your app by running `npm start`, and then you can start debugging in VS Code by pressing `F5` or clicking the green debug icon. This allows you to write code, set breakpoints, make changes, and debug your code without leaving the editor. + +If you encounter any issues with VS Code debugging, refer to their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). + +### WebStorm + +To use the debugging feature in WebStorm, you'll need [WebStorm](https://www.jetbrains.com/webstorm/) and the [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed. + +In WebStorm, go to the `Run` menu and select `Edit Configurations...`. Click the `+` button, choose `JavaScript Debug`, and paste `http://localhost:3000` into the URL field. Save the configuration. + +:::note +- If you've adjusted the HOST or PORT environment variables, the URL may be different. +::: + +Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux, or click the green debug icon in WebStorm to start debugging. + +You can also use this method to debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. + +## Automatic Code Formatting + +Prettier is an opinionated code formatter that supports JavaScript, CSS, and JSON. It helps maintain consistent code style within your project. For more information, you can visit [Prettier's GitHub page](https://github.com/prettier/prettier) or see it in action on their [playground](https://prettier.io/playground/). + +To format your code automatically whenever you make a commit in Git, you need to install the following dependencies: + +```sh +npm install --save husky lint-staged prettier +``` + +Alternatively, you can use `yarn`: + +```sh +yarn add husky lint-staged prettier +``` + +- `husky` enables using Git hooks as if they are npm scripts. +- `lint-staged` allows running scripts on staged files in Git. You can learn more about it in this [blog post about lint-staged](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). +- `prettier` is the JavaScript formatter that will run before commits. + +After installing the dependencies, you can ensure that every file is formatted correctly by adding a few lines to the `package.json` file in your project's root. + +Add the following field to the `package.json`: + +```diff ++ "husky": { ++ "hooks": { ++ "pre-commit": "lint-staged" ++ } ++ } +``` + +Next, add a `lint-staged` field to the `package.json`, for example: + +```diff + "dependencies": { + // ... + }, ++ "lint-staged": { ++ "src/**/*.{js, + +jsx,ts,tsx,json,css,scss,md}": [ ++ "prettier --write" ++ ] ++ }, + "scripts": { +``` + +Now, whenever you make a commit, Prettier will automatically format the changed files. You can also run `./node_modules/.bin/prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}"` to format your entire project for the first time. + +To integrate Prettier with your favorite editor, refer to the [Editor Integration](https://prettier.io/docs/en/editors.html) section on the Prettier GitHub page. \ No newline at end of file diff --git a/docs/react/development/using-https-in-development.md b/docs/react/development/using-https-in-development.md new file mode 100644 index 000000000..64c924d36 --- /dev/null +++ b/docs/react/development/using-https-in-development.md @@ -0,0 +1,82 @@ +--- +id: using-https-in-development +title: Using HTTPS in Development +sidebar_label: HTTPS in Development +sidebar_position: 4 +tags: [react, create-react-app, https, development, environment-variables, ssl, certificate, custom-certificate, environment, npm, package.json, .env, create-react-app, CRA, development-server, HTTPS, SSL, SSL certificate, self-signed certificate, custom SSL certificate, environment variables, HTTPS environment variable, SSL_CRT_FILE, SSL_KEY_FILE, start script, .env file, environment variables, environment variables in Create React App, CRA documentation, custom environment variables] +description: "Learn how to serve your Create React App over HTTPS in development. This is useful when you need to send requests to an API server that requires HTTPS, or when you want to test your site using a secure connection." +--- + +When you're developing a website using Create React App (CRA), you might need to serve your pages over HTTPS instead of HTTP. This is especially important if you're using the "proxy" feature to send requests from your development server to an API server that requires HTTPS. + +### Starting the Development Server with HTTPS + +To start the development server with HTTPS, follow these steps: + +1. Open your command prompt or terminal. + +2. Set the `HTTPS` environment variable to `true`. This tells the development server to use HTTPS. + - **Windows (cmd.exe):** + ```cmd + set HTTPS=true + ``` + + - **Windows (PowerShell):** + ```PowerShell + $env:HTTPS = "true" + ``` + + - **Linux, macOS (Bash):** + ```sh + export HTTPS=true + ``` + +3. Start the development server by running the following command: + ```sh + npm start + ``` + + After executing this command, the development server will serve your pages over HTTPS using a self-signed certificate. It's important to note that self-signed certificates are not trusted by default, so your web browser will display a warning when accessing the page. You can safely proceed past the warning to view your site. + +### Using a Custom SSL Certificate + +If you prefer to use a custom SSL certificate instead of the self-signed certificate, you can follow these additional steps: + +1. Set the `HTTPS` environment variable to `true`, as explained in the previous section. + +2. Set the `SSL_CRT_FILE` and `SSL_KEY_FILE` environment variables to the paths of your custom certificate and key files. + - **Linux, macOS (Bash):** + ```bash + export HTTPS=true + export SSL_CRT_FILE=path/to/cert.crt + export SSL_KEY_FILE=path/to/cert.key + ``` + + Replace `path/to/cert.crt` with the actual path to your SSL certificate file, and `path/to/cert.key` with the path to your SSL key file. + +3. Start the development server by running the following command: + ```sh + npm start + ``` + + With these environment variables set, the development server will use your custom SSL certificate for HTTPS connections. + +To avoid having to set the environment variables every time you start the development server, you have two options: + +1. Update the `start` script in your `package.json` file to include the environment variables. Here's an example of how the `start` script could look: + ```json + { + "start": "HTTPS=true SSL_CRT_FILE=path/to/cert.crt SSL_KEY_FILE=path/to/cert.key react-scripts start" + } + ``` + + Replace `path/to/cert.crt` with the actual path to your SSL certificate file, and `path/to/cert.key` with the path to your SSL key file. + +2. Create a `.env` file in your project's root directory and set the `HTTPS` variable to `true`: + ``` + HTTPS=true + ``` + + This approach is useful if you want to keep your environment variables separate from the `package.json` file. However, remember to keep your `.env` file private and never commit it to a public repository. + +For more detailed information on using environment variables in Create React App (CRA), you can refer to the [official CRA documentation on adding custom environment variables](https://create-react-app.dev/docs/adding-custom-environment-variables). \ No newline at end of file diff --git a/docs/react/getting-started/_category_.json b/docs/react/getting-started/_category_.json new file mode 100644 index 000000000..ff4bc5f01 --- /dev/null +++ b/docs/react/getting-started/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Getting Started", + "position": 3, + "link": { + "type": "generated-index", + "description": "Getting Started with React" + } + } \ No newline at end of file diff --git a/docs/react/getting-started/available-scripts.md b/docs/react/getting-started/available-scripts.md new file mode 100644 index 000000000..31c9ab02c --- /dev/null +++ b/docs/react/getting-started/available-scripts.md @@ -0,0 +1,45 @@ +--- +id: available-scripts +title: Available Scripts +sidebar_position: 3 +tags: [react, create-react-app, scripts, npm, start, test, build, eject, react-scripts, react-dom, react-app] +description: "Learn about the available scripts in a Create React App project. Use these scripts to start, test, build, and eject your app, as well as to run custom scripts." +--- + +In your project directory, you can use the following scripts: + +## `npm start` + +This script runs your app in development mode. It starts a local server and opens your app in a web browser at [http://localhost:3000](http://localhost:3000). Whenever you make changes to your code, the page will automatically reload. If there are any errors in your code, you will see them in the console. + +## `npm test` + +This script launches the test runner in interactive watch mode. It helps you run tests for your app and provides feedback. You can learn more about running tests in the running tests section. + +## `npm run build` + +This script builds your app for production. It creates an optimized version of your app in the `build` folder. The production build is minified and the filenames include unique hashes to ensure browser caching works correctly. React is also bundled in production mode for better performance. If needed, you can enable class and function names for profiling purposes. You can find more information about the production build process in the production build section. + +Your app is now ready to be deployed! Check out the deployment section to learn how to deploy your application to popular hosting providers. + +## `npm run eject` + +**Note: This is a one-way operation. Once you `eject`, you can't go back!** + +If you're not satisfied with the build tool and configuration choices, you can use this script to eject. Ejecting removes the single build dependency from your project. + +Instead, it copies all the configuration files and the necessary dependencies (like webpack, Babel, ESLint, etc.) into your project's `package.json`. The distinction between regular dependencies and development dependencies is less important for front-end apps that produce static bundles. + +In the past, this separation caused issues with some hosting platforms that didn't install development dependencies. As a result, they couldn't build or test the project properly before deployment. By ejecting, you're free to arrange your dependencies in `package.json` as you see fit. + +All the commands except `eject` will continue to work, but they will now refer to the copied scripts, allowing you to customize them. However, from this point forward, you're responsible for maintaining and configuring the build tools on your own. + +Remember, you don't have to use `eject`. The pre-configured features are suitable for small to medium deployments, and you're not obligated to use this customization feature. However, we understand that customization is important when you're ready for it. You can read more about the ejecting process in the documentation. + +## Custom Scripts + +You can also run custom scripts by adding them to the `scripts` section of your `package.json` file. For example, you can add a script to run a linter or a custom build process. You can then run the script using `npm run `. For more information, refer to the custom scripts section. + +## Learn More + +You can learn more about the available scripts and their usage in the [Create React App documentation](https://create-react-app.dev/docs/available-scripts). \ No newline at end of file diff --git a/docs/react/getting-started/folder-structure.md b/docs/react/getting-started/folder-structure.md new file mode 100644 index 000000000..9d4f1b673 --- /dev/null +++ b/docs/react/getting-started/folder-structure.md @@ -0,0 +1,70 @@ +--- +id: folder-structure +title: Folder Structure +sidebar_position: 2 +tags: [react, create-react-app, folder-structure, project-structure, file-structure] +description: "Learn how to organize your files and folders in a new React project. This structure will help you keep things tidy and make it easier to build and maintain your site." +--- + +When you create a new project for your website, it's important to organize your files in a specific way. This structure will help you keep things tidy and make it easier to build and maintain your site. + +Here's how your project should look like: + +``` +my-app +├── README.md +├── node_modules +├── package.json +├── .gitignore +├── public +│ ├── favicon.ico +│ ├── index.html +│ ├── logo192.png +│ ├── logo512.png +│ ├── manifest.json +│ └── robots.txt +└── src + ├── App.css + ├── App.js + ├── App.test.js + ├── index.css + ├── index.js + ├── logo.svg + ├── serviceWorker.js + └── setupTests.js +``` + + +Let's break it down: + +- **`my-app/`:** This is the main folder for your project. You can choose any name you like for this folder. + +- **`README.md`:** This is a file where you can provide information and instructions about your project. It's helpful for others (and yourself) to understand what your website is about and how to use it. + +- **`node_modules/`:** This folder contains all the external libraries and packages that your website depends on. You don't need to worry too much about this folder for now. Just know that it's important for your website to work correctly. + +- **`package.json`:** This file holds various information about your project, such as its name, version, and dependencies. It's used by tools to manage and build your website correctly. + +- **`public/`:** This folder contains files that are publicly accessible from your website. It includes the main HTML file, `index.html`, which serves as the starting point for your site. + +- **`src/`:** This folder is where you'll put most of your code. It stands for "source" and holds the JavaScript and CSS files that make up your website. + + - **`App.css`:** This file contains styles specific to your main app component, such as colors, layout, and fonts. + + - **`App.js`:** This is the main JavaScript file that defines your app component. It's where you'll write most of your code. + + - **`App.test.js`:** This file is used for testing your app. You can ignore it for now if you're just starting out. + + - **`index.css`:** This file contains styles that apply globally to your entire website. + + - **`index.js`:** This is the entry point of your JavaScript code. It's where your app starts and gets rendered on the page. + + - **`logo.svg`:** This file is an example of an image file. You can use it for your website's logo or replace it with your own image. + +You can delete or rename any files that you don't need for your project. Remember to keep the `public/index.html` and `src/index.js` files as they are, because they're essential for your website to work. + +As a beginner, it's recommended to put your JavaScript and CSS files inside the `src` folder to ensure they get processed correctly. Webpack, a tool used for building websites, will take care of bundling and optimizing your code. + +Feel free to create additional folders at the top level for organizing your project, like "images" or "docs". However, keep in mind that files in these folders won't be included in the final version of your website when you're ready to publish it. + +If you're using Git version control system and your project is not part of a larger repository, a new repository will be initialized, creating a `.git` folder. This helps you track changes to your code and collaborate with others if needed. You can ignore this folder for now if you're not familiar with Git. \ No newline at end of file diff --git a/docs/react/getting-started/getting-started.md b/docs/react/getting-started/getting-started.md new file mode 100644 index 000000000..b1cd61e69 --- /dev/null +++ b/docs/react/getting-started/getting-started.md @@ -0,0 +1,194 @@ +--- +id: getting-started +title: Getting Started with React +sidebar_label: Getting Started +sidebar_position: 1 +description: "Learn how to get started with React by creating a new app using Create React App. Follow the steps to set up your development environment and build your first React application." +tags: [React, JavaScript, User interfaces, Library, Virtual DOM, Declarative syntax, Components, Rendering, Web applications, Node.js, Create React App, Development server, React fundamentals, State management, Props, React documentation, React hooks, React Router, React Context API, Awesome React] +--- + +import '../css/style.css'; + +Create React App is an officially supported way to create single-page React applications. It provides a modern build setup with zero configuration required. + +## Quick Start + +To quickly get started with Create React App, follow these steps: + +```sh npm2yarn +npx create-react-app my-app +cd my-app +npm start +``` + +If you have previously installed `create-react-app` globally using `npm install -g create-react-app`, we recommend uninstalling it using `npm uninstall -g create-react-app` or `yarn global remove create-react-app` to ensure that the latest version is always used. + +Once the above commands have executed successfully, open [http://localhost:3000/](http://localhost:3000/) in your browser to see your app. + + +When you are ready to deploy your app to production, create a minified bundle using `npm run build`. + +![npm start](./../img/getting-started-react.svg) + + +## Get Started Immediately + +With Create React App, you don't need to install or configure tools like webpack or Babel. They are already preconfigured and hidden, allowing you to focus solely on writing code. + +Just create a project, and you're good to go! + +## Creating a New App + +To create a new React app, you can choose one of the following methods based on your preferred package manager: + +### Using npx + +```pwsh npm2yarn +npx create-react-app@latest my-app +``` + +### Using npm + +```pwsh +npm init react-app my-app +``` + +Make sure you have npm 6+ installed on your machine. + +### Using Yarn + +```pwsh +yarn create react-app my-app +``` + +Make sure you have Yarn 0.25+ installed. + +## Selecting a Template + +You can optionally start a new app from a template by appending `--template [template-name]` to the creation command. If no template is selected, your project will be created with the base template. + +Templates are named in the format `cra-template-[template-name]`. You only need to provide the `[template-name]` to the creation command. + +For example: + +```pwsh npm2yarn +npx create-react-app my-app --template [template-name] +``` + +You can find a list of available templates by searching for ["cra-template-\*"](https://www.npmjs.com/search?q=cra-template-*) on npm. + +To build your own template, refer to our `Custom Templates` documentation. + +### Creating a TypeScript App + +To start a new TypeScript app, append `--template typescript` to the creation command: + +```pwsh npm2yarn +npx create-react-app my-app --template typescript +``` + +If you already have a project and want to add TypeScript, check out our Adding TypeScript documentation. + +## Selecting a Package Manager + +When creating a new app, the CLI will use either npm or Yarn to install dependencies, depending on the tool you use to run `create-react-app`. + +```pwsh npm2yarn +npx create-react-app my-app +``` + +## Project Structure + +Running the above commands will create a directory named `my-app` in the current folder. Inside this directory, the initial project structure and necessary dependencies will be generated: + +``` +my-app +├── README.md +├── node_modules +├── package.json +├── .gitignore +├── public +│ ├── favicon.ico +│ ├── index.html +│ ├── logo192.png +│ ├── logo512.png +│ ├── manifest.json +│ └── robots.txt +└── src + ├── App.css + ├── App.js + ├── App.test.js + ├── index.css + ├── index.js + ├── logo.svg + ├── serviceWorker.js + └── setupTests.js +``` + +No configuration or complex folder structures are required. You will find only the files necessary to build your app. Once the installation is complete, navigate to your project folder: + +```pwsh +cd my-app +``` + +## Available Scripts + +Inside the project folder, you can run the following built-in commands: + +### Start the Development Server + +```pwsh npm2yarn +npm start +``` + +Runs the app in development mode. Open [http://localhost:3000](http://localhost:3000) in your browser to view it. + + +
+
+ logo +
+

+ Edit src/App.js and save to reload. +

+ + Learn React + +
+
+
+ +The page will automatically reload if you make changes to the code. Any build errors or lint warnings will be displayed in the console. + +### Test the App + +```pwsh npm2yarn +npm test +``` + +Runs the test watcher in interactive mode. By default, it runs tests related to files changed since the last commit. Refer to our `Running Tests`` documentation for more details. + +### Build the App for Production + +```pwsh npm2yarn +npm run build +``` + +Builds the app for production in the `build` folder. It bundles React in production mode and optimizes the build for better performance. + +The build output is minified, and the filenames include hashes for caching. + +Your app is now ready to be deployed! Check out our `Deployment` documentation to learn how to deploy your app to popular hosting providers. + +:::tip Vite for React Development +For an alternative and more modern approach to setting up your React projects, consider using Vite, a blazing-fast build tool. Learn more about getting started with React and Vite in our dedicated guide: [Getting Started with React and Vite](/blog/getting-started-with-vite). +::: + +## Conclusion + +In this guide, we learned how to get started with React by creating a new app using Create React App. We followed the steps to set up our development environment and build our first React application. We also explored the project structure and available scripts for managing our React app. \ No newline at end of file diff --git a/docs/react/getting-started/supported-browsers-features.md b/docs/react/getting-started/supported-browsers-features.md new file mode 100644 index 000000000..6aa728b5a --- /dev/null +++ b/docs/react/getting-started/supported-browsers-features.md @@ -0,0 +1,47 @@ +--- +id: supported-browsers-features +title: Supported Browsers and Features +sidebar_position: 4 +tags: [react, create-react-app, browsers, browser compatibility, polyfills, modern JavaScript, language features, async/await, object rest/spread properties, dynamic import, class fields, static properties, JSX, Flow, TypeScript, browserslist, react-app-polyfill, JavaScript] +description: "Learn about the supported browsers and advanced language features in the website project. Understand how to ensure broad browser compatibility and leverage modern JavaScript capabilities." +--- + +## Supported Browsers + +When building your website, it is designed to work well with all modern web browsers. This means that visitors using popular browsers like Chrome, Firefox, Safari, and Edge should have a smooth experience without any issues. + +However, if you need to support older browsers such as Internet Explorer 9, 10, and 11, you'll need to do a little extra work. These older browsers require something called "polyfills" to understand and use some of the newer features your website might be using. Polyfills are like language translators that help older browsers understand and execute modern code. + +To include the necessary polyfills for older browsers, you can use a package called [react-app-polyfill](https://github.com/facebook/create-react-app/blob/main/packages/react-app-polyfill/README.md). It provides the polyfills you need, so your website will work smoothly across different browsers. + +## Supported Language Features + +The website project supports various advanced features of the JavaScript language. These features enhance the capabilities of your website and make it easier to write clean and efficient code. + +Here are some of the supported language features: + +- **Exponentiation Operator**: This feature allows you to perform exponentiation calculations easily. For example, `2 ** 3` means 2 raised to the power of 3, which equals 8. + +- **Async/await**: This feature simplifies working with asynchronous operations, such as fetching data from an API or loading resources. With `async/await`, you can write asynchronous code in a more readable and sequential manner. + +- **Object Rest/Spread Properties**: This feature provides a concise way to clone or merge objects. It allows you to copy properties from one object to another or extract specific properties from an object effortlessly. + +- **Dynamic import()**: With dynamic import, you can load JavaScript modules on-demand, when they are needed. This feature is particularly useful for code splitting, where you can load parts of your website only when required, optimizing performance. + +- **Class Fields and Static Properties**: This feature simplifies the declaration of instance variables and static properties within classes. It allows you to define properties directly inside the class, making your code cleaner and more readable. + +- **JSX, Flow, and TypeScript**: The website project fully supports JSX syntax, which is a powerful way to write React components. Additionally, it provides optional support for static type checking using Flow or TypeScript. These type checkers help catch errors and provide better documentation for your code. + +It's important to note that while these features are supported, some of them are still considered experimental and may not be fully standardized. Therefore, it's recommended to use them with caution and keep an eye on any updates or changes in the future. + +## Configuring Supported Browsers + +By default, the website project is configured to work well with a wide range of web browsers. The configuration is specified in a file called `package.json`, which you'll find in your project. + +The configuration includes a section called `browserslist`. It defines the list of browsers your website will target for compatibility. By default, the production build targets a broad range of browsers that cover the majority of users, while the development build focuses on more modern browsers for a better development experience. + +The `browserslist` configuration is set up to ensure your website works smoothly across different browsers. It takes into account factors like browser usage statistics and compatibility data. + +Please note that the `browserslist` configuration does not automatically include polyfills for you. If you're using any other modern JavaScript features that require additional support, make sure to include the necessary polyfills manually. + +To summarize, your website is designed to work with all modern web browsers out of the box. If you need to support older browsers, you can include the required polyfills using the [react-app-polyfill](https://github.com/facebook/create-react-app/blob/main/packages/react-app-polyfill/README.md) package. Additionally, the website project supports advanced JavaScript language features to enhance your coding experience. The `browserslist` configuration ensures broad browser compatibility, and you can manually add polyfills if needed. \ No newline at end of file diff --git a/docs/react/getting-started/updating-to-new-releases.md b/docs/react/getting-started/updating-to-new-releases.md new file mode 100644 index 000000000..36c33ff9e --- /dev/null +++ b/docs/react/getting-started/updating-to-new-releases.md @@ -0,0 +1,44 @@ +--- +id: updating-to-new-releases +title: Updating to New Releases +sidebar_position: 5 +tags: [react, create-react, react-scripts, updating, upgrading, migration, changelog, breaking-changes, polyfills, babel-loader, browserslist, package.json, npm, yarn, dependencies, development] +description: "Learn how to update an existing Create React App project to a newer version of react-scripts. Keep your project up to date with the latest features and improvements." +--- + +In Create React App, there are two important packages: + +1. **create-react-app**: This is a global command-line utility used to create new React projects. +2. **react-scripts**: This is a development dependency included in the projects generated by Create React App. + +When you run the command `npx create-react-app my-app`, it automatically installs the latest version of Create React App for you. + +:::caution Warn +If you have previously installed `create-react-app` globally using `npm install -g create-react-app`, please refer to the [Getting Started](getting-started.md) guide to learn about the current installation steps. +::: + +Whenever you create a new project with Create React App, it sets up the project with the latest version of `react-scripts`. This ensures that you benefit from all the new features and improvements available in the latest version. + +## Updating `react-scripts` in an Existing Project + +To update an existing project to a newer version of `react-scripts`, you can follow these steps: + +1. Open the [changelog](https://github.com/CodeMastermindHQ/CodeMastermindHQ/blob/main/CHANGELOG.md) for Create React App. +2. Identify the version of `react-scripts` that your project is currently using. You can find this information in the `package.json` file located in your project folder. +3. Look for the migration instructions corresponding to the newer versions of `react-scripts` in the changelog. + +In most cases, simply updating the `react-scripts` version in the `package.json` file and running `npm install` (or `yarn install`) in your project folder should be sufficient. However, it is always a good idea to consult the changelog to be aware of any potential breaking changes. + +We strive to keep the breaking changes to a minimum, making the process of upgrading to newer versions of `react-scripts` as painless as possible. + +:::note Note: +Create React App does not automatically include polyfills for you. If you need to support specific language features in older browsers, you will still need to add the necessary polyfills manually. +::: + +:::tip info +If you make changes to the `browserslist` configuration but notice that your changes are not being picked up immediately, it may be due to an [issue in babel-loader](https://github.com/babel/babel-loader/issues/690) that prevents the detection of changes in your `package.json`. To resolve this, you can delete the `node_modules/.cache` folder and try again. +::: + +## Summary + +Keeping your project up to date with the latest version of `react-scripts` is important to ensure that you benefit from the latest features and improvements. By following the migration instructions in the changelog, you can safely update your project to a newer version of `react-scripts` and keep your project in sync with the latest developments in the React ecosystem. \ No newline at end of file diff --git a/docs/react/img/getting-started-react.svg b/docs/react/img/getting-started-react.svg new file mode 100644 index 000000000..ded1f06c9 --- /dev/null +++ b/docs/react/img/getting-started-react.svg @@ -0,0 +1 @@ +λλnλnpλnpxλnpxcreate-react-appλnpxcreate-react-appmy-appnpx:installed114in4.308sCreatinganewReactappin~/my-app.Installingpackages.Thismighttakeacoupleofminutes.Installingreact,react-dom,andreact-scripts...yarnaddv1.2.1infoNolockfilefound.[1/4]🔍Resolvingpackages...[2/4]🚚Fetchingpackages...[3/4]🔗Linkingdependencies...[4/4]📃Buildingfreshpackages...successSavedlockfile.successSaved915newdependencies.Donein12.06s.Success!Createdmy-appat~/my-appInsidethatdirectory,youcanrunseveralcommands:yarnstartStartsthedevelopmentserver.yarnbuildBundlestheappintostaticfilesforproduction.yarntestStartsthetestrunner.yarnejectRemovesthistoolandcopiesbuilddependencies,configurationfilesandscriptsintotheappdirectory.Ifyoudothis,youcan’tgoback!Wesuggestthatyoubeginbytyping:cdmy-appHappyhacking!λcdλcdmy-appλnpmλnpmstart>my-app@0.1.0start~/my-app>react-scriptsstartStartingthedevelopmentserver...Compiledsuccessfully!Youcannowviewmy-appinthebrowser.Local:http://localhost:3000/OnYourNetwork:http://192.168.37.106:3000/Notethatthedevelopmentbuildisnotoptimized.Tocreateaproductionbuild,useyarnbuild.Compiling...λnpxcλnpxcrλnpxcreλnpxcreaλnpxcreatλnpxcreateλnpxcreate-λnpxcreate-rλnpxcreate-reλnpxcreate-reaλnpxcreate-reacλnpxcreate-reactλnpxcreate-react-λnpxcreate-react-aλnpxcreate-react-apλnpxcreate-react-appmλnpxcreate-react-appmyλnpxcreate-react-appmy-λnpxcreate-react-appmy-aλnpxcreate-react-appmy-apλcλcdmλcdmy-λcdmy-aλcdmy-apλnpmstλnpmstaλnpmstar \ No newline at end of file diff --git a/docs/react/img/local-host-2.gif b/docs/react/img/local-host-2.gif new file mode 100644 index 000000000..bcdb9a463 Binary files /dev/null and b/docs/react/img/local-host-2.gif differ diff --git a/docs/react/img/logo.svg b/docs/react/img/logo.svg new file mode 100644 index 000000000..9dfc1c058 --- /dev/null +++ b/docs/react/img/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/react/img/react.svg b/docs/react/img/react.svg new file mode 100644 index 000000000..3ed4587a6 --- /dev/null +++ b/docs/react/img/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/react/intro-react.md b/docs/react/intro-react.md new file mode 100644 index 000000000..3b0ee59d5 --- /dev/null +++ b/docs/react/intro-react.md @@ -0,0 +1,52 @@ +--- +id: react-intro +title: Welcome to React +sidebar_label: Welcome +sidebar_position: 2 +description: Development and implementation the API of interaction of two sites +tags: [React, JavaScript library, User interfaces, Virtual DOM, Declarative syntax, UI components, Web development, Front-end, Single-page applications, Performance optimization, State management, Component-based architecture, JavaScript framework] +--- + +React is a JavaScript library for building user interfaces. It allows you to create reusable UI components and efficiently update and render them as the data changes. With its virtual DOM and declarative syntax, React makes it easier to build interactive and performant web applications. + +## Getting Started with React + +To get started with React, you can follow these steps: + +**1. Install Node.js:** React requires Node.js, so make sure you have it installed on your machine. You can download and install Node.js from the official website: [https://nodejs.org](https://nodejs.org) + +**2. Create a New React Project:** Open your terminal or command prompt and run the following command to create a new React project using Create React App: + + ```sh + npx create-react-app my-app + ``` + + This will create a new directory called `my-app` with a basic React project structure and configuration. + +**3. Run the Development Server:** Navigate to the project directory (`my-app`) and start the development server by running the following command: + + ```sh + cd my-app + npm start + ``` + + This will start the development server and open your React app in a web browser. You can make changes to the code in the project and see the live updates in the browser. + +**4. Learn React Fundamentals:** Once your project is set up, you can start learning the fundamentals of React. The official React documentation is an excellent resource to begin with: [https://reactjs.org/docs/getting-started.html](https://reactjs.org/docs/getting-started.html) + +**5. Build Your React App:** With the knowledge of React fundamentals, you can start building your own React applications. Use React components to structure your UI, manage state and props, and handle user interactions. Combine React with other libraries and tools to create powerful and interactive web applications. + +## Resources for Learning React + +Here are some additional resources to help you learn React: + +- **Official React Documentation:** [https://reactjs.org/docs](https://reactjs.org/docs/getting-started.html) +- **React Tutorial:** [https://reactjs.org/tutorial/tutorial.html](https://reactjs.org/tutorial/tutorial.html) +- **React Hooks Documentation:** [https://reactjs.org/docs/hooks-intro.html](https://reactjs.org/docs/hooks-intro.html) +- **React Router Documentation:** [https://reactrouter.com](https://reactrouter.com) +- **React Context API Documentation:** [https://reactjs.org/docs/context.html](https://reactjs.org/docs/context.html) +- **Awesome React:** [https://github.com/enaqx/awesome-react](https://github.com/enaqx/awesome-react) + +Remember, practice is key to mastering React. Explore and build various projects to gain hands-on experience and improve your React skills. + +Start your journey with React today and enjoy building awesome web applications with ease! If you have any questions or need assistance, feel free to reach out to us. We're here to help you succeed with React. \ No newline at end of file diff --git a/docs/react/styles-and-assets/_category_.json b/docs/react/styles-and-assets/_category_.json new file mode 100644 index 000000000..922cf02a4 --- /dev/null +++ b/docs/react/styles-and-assets/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Styles and Assets", + "position": 5, + "link": { + "type": "generated-index", + "description": "5 minutes to learn the most important RoadMap for React Mastery." + } + } \ No newline at end of file diff --git a/docs/react/styles-and-assets/adding-a-css-modules-stylesheet.md b/docs/react/styles-and-assets/adding-a-css-modules-stylesheet.md new file mode 100644 index 000000000..275e26ef8 --- /dev/null +++ b/docs/react/styles-and-assets/adding-a-css-modules-stylesheet.md @@ -0,0 +1,202 @@ +--- +id: adding-a-css-modules-stylesheet +title: Adding A CSS Modules Stylesheet +sidebar_label: CSS Modules Stylesheet +sidebar_position: 2 +tags: [react, create-react-app, css-modules, css, stylesheet, styling, react-scripts, react-dom, react-app] +description: "Learn how to add a CSS Modules stylesheet to your Create React App project. Use scoped styling and prevent naming clashes by automatically generating unique class names for your styles." +--- + +import '../css/style.css' + +:::note +This feature is available with `react-scripts@2.0.0` and higher. +::: + +This tutorial will guide you through the process of adding a CSS Modules stylesheet to your React project. CSS Modules provide scoped styling and prevent naming clashes by automatically generating unique class names for your styles. + +:::tip +If you prefer to use Sass for preprocessing your stylesheets, make sure to [follow the installation instructions](https://codemastermindhq.vercel.app/docs/react/create-react-app/styles-and-assets/adding-a-sass-stylesheet) and use the `.module.scss` or `.module.sass` file extension. +::: +CSS Modules allow you to reuse the same class names across different files without worrying about conflicts. To learn more about CSS Modules, check out this [CSS-Tricks article](https://css-tricks.com/css-modules-part-1-need/). + + +CSS Modules is a popular approach for styling React applications, providing a scoped and modularized way of managing styles. In this guide, we will walk you through the steps of adding a CSS Modules stylesheet to your Create React App project. + +## Step 1: Set up a Create React App project + +If you haven't already, create a new React project using Create React App. Open your command line and run the following command: + +```shell title="Terminal" +npx create-react-app my-app +``` + +This command will set up a new React project in a directory called `my-app`. + +## Step 2: Create a CSS file + +Inside the `src` directory of your project, create a new CSS file. Let's name it `styles.module.css`. The `.module.css` extension is important as it tells Create React App to enable CSS Modules for this file. + +## Step 3: Write some CSS code + +Open the `styles.module.css` file and write your desired CSS code. For example: + +```css title="styles.module.css" +.container { + max-width: 800px; + margin: 0 auto; +} + +.title { + font-size: 24px; + color: #333; +} + +.button { + padding: 10px 20px; + background-color: #007bff; + color: #fff; + border: none; + border-radius: 4px; +} +``` + +Feel free to add more CSS rules as per your project requirements. + +## Step 4: Import and use the CSS classes + +Now, go to the JavaScript file where you want to use the CSS classes. Import the `styles` object from the CSS file you created: + +```javascript title="MyComponent.jsx" +import styles from './styles.module.css'; +``` + +You can now use the imported `styles` object to access the CSS classes defined in the file. For example: + +```javascript title="MyComponent.jsx" +function MyComponent() { + return ( +
+

Welcome to My App

+ +
+ ); +} +``` + +By using `styles.container`, `styles.title`, and `styles.button`, you are ensuring that the CSS class names are scoped locally to the components, preventing any conflicts with other styles. + +## Step 5: Start the development server + +Save your changes and start the development server by running the following command in your project directory: + +```shell title="Terminal" +cd my-app +npm start +``` + +Now, you can visit `http://localhost:3000` in your browser to see your React application with the CSS Modules styles applied. + + + + +
+

Welcome to My App

+ +
+ +
+ + +## Create a CSS Modules stylesheet + +First, create a new CSS file in the `src` directory of your React project. For example, let's name it `Button.module.css`. The `.module.css` extension is crucial, as it enables CSS Modules for that specific file. + +Add the following CSS code to your `Button.module.css` file: + +```css title="Button.module.css" +.error { + background-color: red; +} +``` + +## Import the CSS Modules stylesheet + +Next, open the component file where you want to use the CSS Modules styles. Import the CSS classes from the `Button.module.css` file and apply them to your elements. + +For instance, in your `Button.js` file, import the CSS classes as follows: + +```javascript title="Button.jsx" +import React, { Component } from 'react'; +import styles from './Button.module.css'; + +class Button extends Component { + render() { + return ; + } +} +``` + +In this example, the `styles.error` class is applied to the button, which will give it a red background color. + + +## Use CSS Modules and regular stylesheets together + +CSS Modules can coexist with regular stylesheets in your project. To demonstrate this, let's assume you have another regular stylesheet named `another-stylesheet.css` that defines an `.error` class with different styles. + +To use the regular stylesheet, import it in your `Button.js` file: + +```javascript +import './another-stylesheet.css'; +``` + +Now, the `Button` component will have both the CSS Modules styles and the styles from the regular stylesheet. + +## Result + +When the `Button` component is rendered, the CSS Modules class will automatically generate a unique class name, preventing clashes with other `.error` class names. + +***This button has a red background but not red text*** + + + +
+ +
+ +
+ +CSS Modules provide a convenient and efficient way to manage styles in your React project, ensuring encapsulation and avoiding global style conflicts. + +:::note +Using CSS Modules is optional. You can still use regular `` stylesheets and CSS files in your project. CSS Modules are only enabled for files with the `.module.css` extension. +::: + +## Live Coding + +### Example-1: + +```jsx live +function MyComponent() { + return ( +
+

Welcome to My App

+ +
+ ); +} +``` + +### Example-2: + +```jsx live +class Button extends Component { + render() { + return ; + } +} +``` + +## Conclusion + +You've successfully learned how to add a CSS Modules stylesheet to your Create React App project. By using CSS Modules, you can manage your styles in a modular and scoped manner, preventing naming clashes and ensuring encapsulation. \ No newline at end of file diff --git a/docs/react/styles-and-assets/adding-a-sass-stylesheet.md b/docs/react/styles-and-assets/adding-a-sass-stylesheet.md new file mode 100644 index 000000000..59c6baffb --- /dev/null +++ b/docs/react/styles-and-assets/adding-a-sass-stylesheet.md @@ -0,0 +1,132 @@ +--- +id: adding-a-sass-stylesheet +title: Adding A Sass Stylesheet +sidebar_label: Sass Stylesheet +sidebar_position: 3 +tags: [react, create-react-app, sass, stylesheet] +description: "Learn how to add a Sass stylesheet to your Create React App project. Use the power of Sass to write cleaner and more maintainable styles for your React components." +--- + +:::caution warn +This feature is available with `react-scripts@2.0.0` and higher. +::: + +When working with React components, it's generally recommended not to reuse the same CSS classes across different components. Instead, it's better to create separate component styles and compose them together. However, if you find CSS preprocessors valuable, you can integrate Sass into your React project. + +***To use Sass in your Create React App project, follow these steps:*** + +## Step 1: Install Sass +First, install the `sass` package by running the following command in your project's terminal: + +```sh title="Terminal" +$ npm install sass +# or +$ yarn add sass +``` + +## Step 2: Rename and Import the Sass Stylesheet + +Next, rename the `src/App.css` file to `src/App.scss`. This will signal Create React App to use the Sass compiler for this file. Update `src/App.js` to import `src/App.scss` as follows: + +```jsx title="App.js" +import React from 'react'; +import './App.scss'; + +function App() { + // Your component code goes here + return ( + // JSX code + ); +} + +export default App; +``` + +By importing the Sass file, Create React App will automatically compile it. + +## Step 3: Share Variables Between Sass Files + +To share variables between Sass files, you can use the `@use` rule provided by Sass. For example, in `src/App.scss` or other component style files, you can include the following line to import a shared Sass file with variable definitions: + +```scss +@use "./shared.scss"; +``` + +You can then use those variables within your component styles. + +## Step 4: Importing External Sass Files + +To import Sass files from external sources or libraries, you can use the `@use` rule. Here are a couple of examples: + +```scss +@use 'styles/_colors.scss'; // assuming a styles directory under src/ +@use '~nprogress/nprogress'; // loading a CSS file from the nprogress node module +``` + +The `~` symbol followed by the module name allows you to resolve modules from the `node_modules` directory. + +:::tip info +If you're using Windows, separate your paths by semicolons: + +``` +SASS_PATH=path1;path2;path3 +``` +::: + +Step 5: Using Sass with CSS Modules +---------------------------------- +You can also use Sass in combination with [CSS modules](adding-a-css-modules-stylesheet.md). To enable this feature, follow the same steps mentioned above, but use `.module.scss` as the file extension instead (e.g., `src/App.module.scss`). + +:::tip info +If you're using Flow, make sure to update your `.flowconfig` file to recognize `.sass` or `.scss` files. Add the following lines to the `[options]` section: + +``` +module.file_ext=.sass +module.file_ext=.scss +``` +::: + +:::note +LibSass and the packages built on top of it, including Node Sass, are deprecated. If you're currently using Node Sass, it's recommended to migrate to Dart Sass. You can do this by replacing `node-sass` in your `package.json` file with `sass` or by running the following commands: + +```sh +$ npm uninstall node-sass +$ npm install sass +# or +$ yarn remove node-sass +$ yarn add sass +``` +::: + +That's it! You've successfully added a Sass stylesheet to your Create React App project. Now you can leverage the power of Sass to write cleaner and more maintainable styles for your React components. + + +**Some popular resources and official sites that beginners can refer to when learning about adding Sass stylesheets in a React project:** + +1. **Sass Documentation** - The official Sass documentation is an excellent resource for learning about Sass features, syntax, and usage. It provides comprehensive guides, examples, and explanations: [Sass Documentation](https://sass-lang.com/documentation) + +2. **Create React App Documentation** - The official documentation for Create React App includes a section on adding Sass stylesheets. It provides instructions and guidelines specific to Create React App projects: [Create React App - Adding a Sass Stylesheet](https://create-react-app.dev/docs/adding-a-sass-stylesheet) + +3. **React Documentation** - The official React documentation is a valuable resource for understanding React concepts and features. While it doesn't specifically focus on Sass, it provides information on working with styles in React components: [React Documentation - Styling and CSS](https://reactjs.org/docs/faq-styling.html) + +4. **Sass Guidelines** - The Sass Guidelines website offers a collection of best practices, tips, and coding conventions for writing maintainable Sass code. It covers various aspects of Sass development, including architecture and organization: [Sass Guidelines](https://sass-guidelin.es/) + +5. **CSS-Tricks** - CSS-Tricks is a popular web development resource that covers a wide range of topics, including Sass. It has a dedicated section with tutorials, articles, and examples related to Sass: [CSS-Tricks - Sass](https://css-tricks.com/category/sass/) + +6. **Smashing Magazine** - Smashing Magazine is a well-known online publication for web designers and developers. It has a collection of articles and tutorials related to Sass, covering different aspects and techniques: [Smashing Magazine - Sass](https://www.smashingmagazine.com/tag/sass/) + +7. **SitePoint** - SitePoint offers an extensive library of web development tutorials and articles. It has a section dedicated to Sass, featuring tutorials, tips, and tricks for using Sass in various contexts: [SitePoint - Sass](https://www.sitepoint.com/tag/sass/) + +These resources should provide beginners with a solid foundation for learning about Sass and its integration with React. Remember to provide appropriate attribution and links to the original sources when including content from these sites on your own website. This helps maintain ethical and legal standards for content usage and sharing. + +**Some popular resources and official sites that beginners can refer to when learning about adding Sass stylesheets in a React project:** + +1. **Sass Documentation** - The official Sass documentation is an excellent resource for learning about Sass features, syntax, and usage. It provides comprehensive guides, examples, and explanations: [Sass Documentation](https://sass-lang.com/documentation) +2. **Create React App Documentation** - The official documentation for Create React App includes a section on adding Sass stylesheets to a project. It provides instructions and guidelines specific to Create React App projects: [Create React App - Adding a Sass Stylesheet](https://create-react-app.dev/docs/adding-a-sass-stylesheet) +3. **React Documentation** - The official React documentation is a valuable resource for understanding React concepts and features. While it doesn't specifically focus on Sass, it provides information on working with styles in React components: [React Documentation - Styling and CSS](https://reactjs.org/docs/faq-styling.html) +4. **Sass Guidelines** - The Sass Guidelines website offers a collection of best practices, tips, and coding conventions for writing maintainable Sass code. It covers various aspects of Sass development, including architecture and organization: [Sass Guidelines](https://sass-guidelin.es/) +5. **CSS-Tricks** - CSS-Tricks is a popular web development resource that covers a wide range of topics, including Sass. It has a dedicated section with tutorials, articles, and examples related to Sass: [CSS-Tricks - Sass](https://css-tricks.com/category/sass/) +6. **Smashing Magazine** - Smashing Magazine is a well-known online publication for web designers and developers. It has a collection of articles and tutorials related to Sass, covering different aspects and techniques: [Smashing Magazine - Sass](https://www.smashingmagazine.com/tag/sass/) +7. **SitePoint** - SitePoint offers an extensive library of web development tutorials and articles. It has a section dedicated to Sass, featuring tutorials, tips, and tricks for using Sass in various contexts: [SitePoint - Sass](https://www.sitepoint.com/tag/sass/) + +These resources should provide beginners with a solid foundation for learning about Sass and its integration with React. Remember to provide appropriate attribution and links to the original sources when including content from these sites on your own website. This helps maintain ethical and legal standards for content usage and sharing. \ No newline at end of file diff --git a/docs/react/styles-and-assets/adding-a-stylesheet.md b/docs/react/styles-and-assets/adding-a-stylesheet.md new file mode 100644 index 000000000..e07f1ab0c --- /dev/null +++ b/docs/react/styles-and-assets/adding-a-stylesheet.md @@ -0,0 +1,113 @@ +--- +id: adding-a-stylesheet +title: Adding A Stylesheet +sidebar_label: Stylesheet +sidebar_position: 1 +tags: [react, create-react-app, css, stylesheet, styling, react-scripts, react-dom, react-app] +description: "Learn how to add a stylesheet to your Create React App project. Style your components and make them visually appealing with CSS." +--- + +## Introduction: +In this guide, we will explore how to add a stylesheet to your React application created with Create React App. Cascading Style Sheets (CSS) allow you to style your components and make them visually appealing. We'll walk through the process step by step, making it easy for beginners to understand. + +## Prerequisites: +Before we begin, make sure you have the following installed on your computer: +- Node.js: You can download and install it from https://nodejs.org. +- Create React App: If you don't have it, install it globally by running `npm install -g create-react-app` in your terminal or command prompt. + +### Step 1: Create a new React app +If you haven't created a React app yet, open your terminal or command prompt and run the following command: +``` +npx create-react-app my-app +``` +This command will create a new folder called `my-app` with all the necessary files and dependencies to start your React project. + +### Step 2: Open your project folder +Navigate to the project folder by running `cd my-app` in your terminal or command prompt. + +### Step 3: Add a CSS file +Inside the `src` folder of your project, create a new file called `styles.css`. This file will hold your CSS styles. + +### Step 4: Write some CSS +Open the `styles.css` file in a text editor and add the following CSS code: +```css title="styles.css" +/* styles.css */ + +/* Example styles */ +body { + background-color: blue; + font-family: Arial, sans-serif; +} + +h1 { + color: #fff; + text-align: center; +} +p{ + color: #fff; +} +``` +Feel free to modify the styles as per your preferences. These are just basic examples to get you started. + +### Step 5: Import the stylesheet +Open the `src/App.js` file in your text editor. At the top of the file, import the CSS file by adding the following line: +```javascript title="App.js" +import './styles.css'; +``` +This tells React to include the styles from the `styles.css` file in your application. + +### Step 6: Apply styles to components +Now that you have your stylesheet imported, you can start applying the styles to your components. Open the `src/App.js` file and find the component you want to style. Add the appropriate CSS classes to the elements you want to style, like this: +```jsx title="App.js" +import React from 'react'; +import './styles.css'; + +function App() { + return ( +
+

Welcome to My App

+

This is a sample paragraph.

+
+ ); +} + +export default App; +``` +Here, we've added the `title` and `description` classes to the `

` and `

` elements, respectively. + +### Step 7: Run your React app +To see your styles in action, go back to your terminal or command prompt, make sure you're in the project folder (`my-app`), and run the following command: +``` +npm start +``` +This will start the development server, and you can view your app in your browser at `http://localhost:3000`. + + + +

+

Welcome to My App

+

This is a sample paragraph.

+
+ + + +## Conclusion: +Congratulations! You have successfully added a stylesheet to your React app. Now you can experiment with different CSS styles to enhance the visual appeal of your components. Remember to import the stylesheet and apply the appropriate CSS classes to the elements you want to style. + +Please note that the example above is a simplified explanation of adding a stylesheet to a React app. For more advanced styling techniques and best practices, consider exploring CSS frameworks and libraries like Bootstrap or Material-UI. + +Remember to have fun and get creative with your styles as you continue your React journey! + +## Additional Resources: + +- [CSS Introduction](https://www.w3schools.com/css/css_intro.asp) - W3Schools provides a comprehensive guide to CSS, including tutorials and examples. +- [CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference) - MDN Web Docs offers an extensive reference for CSS properties and selectors. +- [Bootstrap](https://getbootstrap.com/) - Bootstrap is a popular CSS framework that provides pre-built components and styles for web development. +- [Material-UI](https://material-ui.com/) - Material-UI is a React component library that implements Google's Material Design for web applications. +- [CSS Tricks](https://css-tricks.com/) - CSS Tricks is a web development community that offers articles, tutorials, and resources for CSS and front-end development. +- [React Documentation](https://reactjs.org/docs/getting-started.html) - The official React documentation provides in-depth guides and examples for learning React. +- [Create React App Documentation](https://create-react-app.dev/docs/getting-started) - The official documentation for Create React App includes detailed information on getting started with React projects. +- [React Community](https://reactjs.org/community/support.html) - The React community provides support and resources for developers learning and working with React. +- [React on Stack Overflow](https://stackoverflow.com/questions/tagged/reactjs) - Stack Overflow is a popular Q&A platform for programming questions, including those related to React. + +These resources should help you gain a deeper understanding of CSS and its integration with React. Remember to explore different styles and techniques to create visually stunning applications. \ No newline at end of file diff --git a/docs/react/styles-and-assets/adding-css-reset.md b/docs/react/styles-and-assets/adding-css-reset.md new file mode 100644 index 000000000..14fc5a04b --- /dev/null +++ b/docs/react/styles-and-assets/adding-css-reset.md @@ -0,0 +1,77 @@ +--- +id: adding-css-reset +title: Adding A CSS Reset +sidebar_label: CSS Reset +sidebar_position: 4 +tags: [react, create-react-app, css, stylesheet, styling, react-scripts, react-dom, react-app] +description: "Learn how to add a CSS reset to your Create React App project using PostCSS Normalize. Ensure consistent styling across different browsers by providing a solid foundation for your React components." +--- + +This tutorial will guide you on adding a CSS reset to your React project using [PostCSS Normalize], which provides a solid foundation for consistent styling across different browsers. + +**To get started, follow these steps:** + +## Step 1: Set up PostCSS Normalize + +**1. Install the necessary dependencies by running the following command in your terminal:** + + ```shell + npm install postcss-normalize + ``` + +**2. In your project's main CSS file (e.g., `index.css` or `App.css`), import PostCSS Normalize by adding the following line:** + + ```css title="index.css" + @import-normalize; /* Import normalize.css styles */ + ``` + + By including this line, you bring in the necessary CSS reset styles. + +:::tip +If you're using Visual Studio Code and encounter an "_Unknown at rule @import-normalize css(unknownAtRules)_" warning, you can change the `css.lint.unknownAtRules` setting to `ignore` in your editor preferences. +::: + +**3. Feel free to add your custom styles below the `@import-normalize` line. This is where you can customize the appearance of your React components.** + +## Step 2: Customize Normalize.css (Optional) + +PostCSS Normalize allows you to control which parts of [normalize.css] you want to include based on your project's specific requirements. The styles provided by normalize.css ensure consistent rendering across different browsers. + +For example, when targeting older browsers like Internet Explorer 9, you may see the following styles added to your CSS: + +```css title="normalize.css" +/** + * Add the correct display in IE 9-. + */ + +audio, +video { + display: inline-block; +} + +/** + * Remove the border on images inside links in IE 10-. + */ + +img { + border-style: none; +} +``` + +If you only need to support the last two versions of modern browsers, these additional styles will be omitted. + +## Browser Support + +PostCSS Normalize supports a wide range of browsers, ensuring your styles render consistently across different platforms. The supported browsers include: + +- Chrome (last 3 versions) +- Edge (last 3 versions) +- Firefox (last 3 versions) +- Firefox ESR +- Opera (last 3 versions) +- Safari (last 3 versions) +- iOS Safari (last 2 versions) +- Internet Explorer 9 and above + +[PostCSS Normalize]: https://github.com/csstools/postcss-normalize +[normalize.css]: https://github.com/csstools/normalize.css diff --git a/docs/react/styles-and-assets/adding-images-fonts-and-files.md b/docs/react/styles-and-assets/adding-images-fonts-and-files.md new file mode 100644 index 000000000..aeece94b3 --- /dev/null +++ b/docs/react/styles-and-assets/adding-images-fonts-and-files.md @@ -0,0 +1,198 @@ +--- +id: adding-images-fonts-and-files +title: Adding Images, Fonts, and Files in a React App +sidebar_label: Images Fonts and Files +sidebar_position: 6 +tags: [react, create-react-app, images, fonts, files, assets, react-scripts, react-dom, react-app] +description: "Learn how to work with images, fonts, and files in a React application. Manage and utilize these assets effectively to create visually appealing and interactive web experiences." +--- + +In this guide, we'll explore how to work with images, fonts, and files in a React application. These assets are essential for creating visually appealing and interactive web experiences. We'll cover everything you need to know to manage and utilize these assets effectively. + +## Table of Contents + +1. [Adding Images](#1-adding-images) +2. [Using Fonts](#2-using-fonts) +3. [Handling Files](#3-handling-files) + +## 1. Adding Images + +To include images in your React app, follow these simple steps: + +### Step 1: Prepare Your Image + +Before adding an image, make sure you have it in a suitable format like JPEG, PNG, or GIF. Also, consider resizing or compressing images to optimize your app's performance. + +### Step 2: Import the Image + +In your component file, import the image using ES6's `import` statement: + +```jsx title="App.js" +import React from 'react'; +import logo from './path/to/your/logo.png'; + +function App() { + return ( +
+ Logo +
+ ); +} + +export default App; +``` + +**Live Preview:** + + + +
+ Logo +
+ +
+ + +### Step 3: Display the Image + +Now, you can display the imported image using the `img` tag as shown above. Don't forget to add an informative `alt` attribute for accessibility purposes. + +## 2. Using Fonts + +Custom fonts can greatly enhance the visual appeal of your React app. Here's how you can include them: + +### Step 1: Obtain the Font Files + +Find or download the font files (usually in `.ttf`, `.woff`, or `.woff2` formats) you want to use and place them in a directory within your project, such as `src/fonts/`. + +### Step 2: Create a CSS File + +Create a new CSS file, e.g., `fonts.css`, in the `src` directory and define the font-face: + +```css title="fonts.css" +/* src/fonts/fonts.css */ + +@font-face { + font-family: 'YourFontName'; + src: url('./path/to/your/font.woff2') format('woff2'), + url('./path/to/your/font.woff') format('woff'); + /* Add more formats for compatibility if necessary */ + font-weight: normal; + font-style: normal; +} +``` + +### Step 3: Import and Apply the Font + +In your main `index.js` file, import the `fonts.css`: + +```js title="index.js" +import React from 'react'; +import ReactDOM from 'react-dom'; +import './fonts/fonts.css'; // Import the CSS file + +import App from './App'; + +ReactDOM.render( + + + , + document.getElementById('root') +); +``` + +Now, you can apply the font to specific elements in your components: + +```jsx title="App.js" +import React from 'react'; + +function App() { + return ( +
+

Welcome to My App!

+

Enjoy your stay!

+
+ ); +} + +export default App; +``` + +**Live Preview:** + + + +
+

Welcome to My App!

+

Enjoy your stay!

+
+ +
+ +## 3. Handling Files + +React allows you to work with various file types easily, such as PDFs, documents, or audio files. You can handle files by providing download links or embedding media players in your app. + +To link to a file for download: + +```jsx title="App.js" +import React from 'react'; + +function App() { + return ( + + ); +} + +export default App; +``` + +**Live Preview:** + + + + + + + +To embed media, like audio: + +```jsx title="App.js" +import React from 'react'; + +function App() { + return ( +
+ +
+ ); +} + +export default App; +``` + +## Live coding + +```jsx live +function App() { + return ( +
+

Welcome to My App!

+

Enjoy your stay!

+
+ ); +} +``` + +With this knowledge, you're ready to manage images, fonts, and files effectively in your React app. Have fun experimenting and enhancing your web projects! + +Remember, continuous learning is the key to becoming a mastermind developer! + +If you have any questions or need further assistance, don't hesitate to reach out to the React community for support. Happy coding! \ No newline at end of file diff --git a/docs/react/styles-and-assets/code-splitting.md b/docs/react/styles-and-assets/code-splitting.md new file mode 100644 index 000000000..ee29773a5 --- /dev/null +++ b/docs/react/styles-and-assets/code-splitting.md @@ -0,0 +1,74 @@ +--- +id: code-splitting +title: Code Splitting +sidebar_label: Code Splitting +sidebar_position: 9 +tags: [react, performance, optimization, code-splitting, lazy-loading, suspense, react-lazy] +description: "Learn how to optimize your React application's performance by code splitting. Split your code into smaller chunks and load them only when needed, resulting in faster load times and improved user experiences." +--- + +import React, { lazy, Suspense } from 'react'; + +### Introduction: +Welcome to the enchanting world of React code splitting! In this guide, we'll explore the art of code splitting, a powerful technique that will bring exceptional performance and delightful user experiences to your React applications. Whether you're a seasoned developer or a curious beginner, get ready to embark on an adventure where we uncover the secrets of optimizing your app's loading times and resource utilization. + +### What is Code Splitting? +Imagine your React application as a grand castle, with its walls adorned by beautiful paintings and its halls filled with intricate statues. Code splitting allows you to divide this vast castle into smaller sections, each containing its own set of paintings and statues. Instead of displaying the entire castle all at once, we'll only reveal the chambers our visitors wish to explore. + +## Benefits of Code Splitting: +1. **Swift Sorcery - Faster Load Times**: By breaking down our castle into smaller pieces, we can summon only the required sections when a visitor arrives. This magical trick ensures faster load times, granting instant access to essential features. + +2. **Performance Potions**: Smaller code bundles result in faster parsing and execution of spells (code). This leads to a smoother and more responsive experience, even on humble devices. + +3. **Caching Charms**: Code splitting opens the door to potent caching charms. Reusable code sections can be cached by visitors, reducing the need for reinvocations and accelerating subsequent visits. + +4. **Wizardly Network Resource Management**: Visitors will only download the specific portions they need, making our network resource management as efficient as a seasoned wizard's spellbook. + +Unfolding the Mysteries of Code Splitting: +To unlock the secrets of code splitting in React, we shall invoke two mystical artifacts: `React.lazy()` and the enchanted `Suspense` component. + +```jsx title="MyComponent.js" +import React from 'react'; + +const MyComponent = () => { + return
Behold, my dynamically-imported component!
; +}; + +export default MyComponent; +``` + +```jsx title="App.js" +// App.js +import React, { lazy, Suspense } from 'react'; + +const MyComponent = lazy(() => import('./MyComponent')); + +const App = () => { + return ( +
+

Welcome to My Enchanted React App!

+ Casting a spell...
}> + + + + ); +}; + +export default App; +``` + + +
+

Welcome to My Enchanted React App!

+ Casting a spell...
}> +
Behold, my dynamically-imported component!
+ + +
+ + +In this enchanting example, we've harnessed the magic of `React.lazy()` to conjure the `MyComponent` dynamically. Wrapped within the protective embrace of the `Suspense` component, we can gracefully display a fallback message, "Casting a spell...," while the magical import unfolds. + +### Conclusion: + +Congratulations, dear apprentice! You've now mastered the art of code splitting in React. With your newfound skills, you can deliver captivating and swift experiences to all those who enter your digital realm. Remember, as you continue to explore the depths of React, the secrets of code splitting will serve you well on your journey to becoming a true Code Mastermind. Happy coding and may your React spells cast wondrous delights for your users! \ No newline at end of file diff --git a/docs/react/styles-and-assets/loading-graphql-files.md b/docs/react/styles-and-assets/loading-graphql-files.md new file mode 100644 index 000000000..0f3081f69 --- /dev/null +++ b/docs/react/styles-and-assets/loading-graphql-files.md @@ -0,0 +1,130 @@ +--- +id: loading-graphql-files +title: How to Load GraphQL Files in React +sidebar_label: Loading GraphQL Files +sidebar_position: 7 +tags: [react, create-react-app, graphql, apollo-client, graphql-code-generator, react-apollo, react-apollo-hooks] +description: Learn how to load GraphQL files in a Create React App project. Use Apollo Client or GraphQL Code Generator to fetch data from your GraphQL server and simplify your React application development. +--- + +## Introduction + +GraphQL is a powerful query language for APIs that allows you to efficiently request only the data you need from your server. If you are using GraphQL in your React application created with Create React App, you might wonder how to load your GraphQL files effectively. + +In this guide, we'll walk you through the process of loading GraphQL files in a Create React App project. We'll cover two popular approaches: using Apollo Client and using GraphQL Code Generator. Buckle up, and let's dive into the world of GraphQL! + +## Prerequisites + +Before we proceed, make sure you have the following installed in your development environment: + +1. [Node.js](https://nodejs.org) - JavaScript runtime environment. +2. [Create React App](../getting-started/getting-started.md) - Get Started to Create React app. +3. [Create React App](https://reactjs.org/docs/create-a-new-react-app.html) - The official tool to create React applications. + +## Method 1: Using Apollo Client + +[Apollo Client](https://www.apollographql.com/docs/react/) is a widely-used GraphQL client that simplifies the process of fetching data from a GraphQL server in your React application. Let's see how you can set up Apollo Client in your Create React App project: + +**1. Install Dependencies** + +Open your terminal and navigate to your project directory. Run the following command to install the required packages: + +```bash +npm install @apollo/client graphql +``` + +**2. Set up Apollo Client** + +Create a new file called `apolloClient.js` in the `src` directory and add the following code: + +```javascript title="apolloClient.js" +import { ApolloClient, InMemoryCache } from '@apollo/client'; + +const client = new ApolloClient({ + uri: 'https://your-graphql-server.com/graphql', // Replace this with your GraphQL server URL + cache: new InMemoryCache(), +}); + +export default client; +``` + +**3. Wrap your App with Apollo Provider** + +Open the `index.js` file in the `src` directory, and modify it as follows: + +```javascript title="index.js" +import React from 'react'; +import ReactDOM from 'react-dom'; +import { ApolloProvider } from '@apollo/client'; +import client from './apolloClient'; +import App from './App'; + +ReactDOM.render( + + + , + document.getElementById('root') +); +``` + +Now, your React application is equipped with Apollo Client, and you can start making GraphQL queries and mutations! + +## Method 2: Using GraphQL Code Generator + +[GraphQL Code Generator](https://graphql-code-generator.com/) is a fantastic tool that generates TypeScript types and React hooks based on your GraphQL schema and operations. It simplifies working with GraphQL in React by providing type safety and autocompletion for your queries and mutations. Let's get started: + +**1. Install Dependencies** + +Run the following command in your terminal to install the required packages: + +```bash +npm install -g graphql-codegen +``` + +**2. Set up GraphQL Code Generator** + +Create a `codegen.yml` file in the root of your project and add the following configuration: + +```yaml +overwrite: true +schema: https://your-graphql-server.com/graphql # Replace this with your GraphQL schema URL +documents: src/**/*.graphql +generates: + src/generated/graphql.tsx: + plugins: + - 'typescript' + - 'typescript-operations' + - 'typescript-react-apollo' +``` + +**3. Create GraphQL Operations** + +In the `src` directory, create a folder called `graphql` and add your GraphQL query or mutation files with the `.graphql` extension. For example, `query.graphql`. + +**4. Generate Code** + +Now, run the following command to generate TypeScript types and React hooks based on your GraphQL operations: + +```bash +graphql-codegen +``` + +You will see a new file `graphql.tsx` in the `generated` folder inside `src`, containing the generated code. + +**5. Use Generated Code in your Components** + +You can now import and use the generated hooks in your React components: + +```javascript +import { useMyQuery } from '../generated/graphql'; + +const MyComponent = () => { + const { data, loading, error } = useMyQuery(); + + // Your component logic here +}; +``` + +## Conclusion + +In this guide, you learned how to load GraphQL files in a Create React App project using two popular approaches: Apollo Client and GraphQL Code Generator. You can choose the method that best suits your project requirements and start building powerful React applications with GraphQL. Happy coding! \ No newline at end of file diff --git a/docs/react/styles-and-assets/post-processing-css.md b/docs/react/styles-and-assets/post-processing-css.md new file mode 100644 index 000000000..d28090b1a --- /dev/null +++ b/docs/react/styles-and-assets/post-processing-css.md @@ -0,0 +1,152 @@ +--- +id: post-processing-css +title: Post Processing CSS +sidebar_label: Post Processing CSS +sidebar_position: 5 +tags: [react, create-react-app, css, stylesheet, styling, react-scripts, react-dom, react-app] +description: "Learn how to leverage post-processing CSS in Create React App to enhance your stylesheets and ensure cross-browser compatibility. Automatically add vendor prefixes, embrace new CSS features, and more." +--- + +import '../css/style.css' + +## Introduction: +Welcome to the enchanting world of post-processing CSS! In Create React App, your CSS is automatically minified and provided with vendor prefixes by the powerful [Autoprefixer](https://github.com/postcss/autoprefixer), saving you from the hassle. If you've ever wished to sprinkle a touch of magic onto your stylesheets, you've come to the right place. In this guide, we'll delve into the fascinating realm of post-processing CSS and explore how it can enhance your React applications. + +Moreover, with the support of post-processing tools, you can embrace new CSS features and ensure compatibility with older browsers. Custom properties, media query ranges, and other cutting-edge features are automatically polyfilled to deliver a consistent experience. + +## Customizing Browser Support + +You have the flexibility to define your target browser support by adjusting the `browserslist` key in your `package.json` file. This allows you to cater to your specific audience while considering the [Browserslist specification](https://github.com/browserslist/browserslist#readme). + +For example, you can specify support for modern browsers by updating your `browserslist` to: + +``` +"browserslist": [ + "last 2 Chrome versions", + "last 2 Firefox versions", + "last 2 Safari versions" +] +``` + +## A Magical Transformation + +Let's witness the enchanting transformation of a CSS class using Autoprefixer: + +```css +/* Before */ +.App { + display: flex; + flex-direction: row; + align-items: center; +} +``` + +```css +/* After */ +.App { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; +} +``` + +Isn't it magical? Autoprefixer gracefully adds the necessary vendor prefixes, ensuring the widest browser compatibility for your styles. + +## Fine-Tuning Autoprefixer + +If, for any reason, you need to disable Autoprefixer for specific CSS rules, you can follow [this section](https://github.com/postcss/autoprefixer#disabling) to learn how. + +By default, Autoprefixer doesn't add prefixes for [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout). However, manual prefixes will be preserved. If you'd like to opt-in to CSS Grid prefixing, make sure you understand its limitations by reading [this documentation](https://github.com/postcss/autoprefixer#does-autoprefixer-polyfill-grid-layout-for-ie). + +To enable CSS Grid prefixing, simply add the following comment at the top of your CSS file: + +```css +/* autoprefixer grid: autoplace */ +``` + +Now, go forth and create captivating styles with the power of post-processing CSS in Create React App! + +## For Example + +***Step-by-step example demonstrating the post-processing CSS capabilities in Create React App:*** + +**1. Create a new React application using Create React App by running the following command in your terminal:** +```shell +npx create-react-app my-app +``` + +**2. Navigate into the project directory:** +```shell +cd my-app +``` + +**3. Open the `src/App.css` file in your preferred code editor.** + +**4. Replace the existing CSS code with the following:** + +```css +.App { + display: grid; + grid-template-columns: repeat(2, 1fr); +} +``` + +**5. Save the file and start the development server:** +```shell +npm start +``` + +**6. Open your browser and visit `http://localhost:3000` to see the React application running.** + + + +
+

Welcome to My Magical App

+

Enjoy the wonders of post-processing CSS!

+
+ +
+ +**1. Now, let's witness the magic of post-processing CSS. Open the browser's developer tools and inspect the `.App` element.** + +**2. In the Styles tab, you'll notice that the CSS properties have been automatically prefixed by the browser. For example, the `display: grid` property is transformed into:** + +```css +display: -ms-grid; +display: grid; +``` + +This transformation is performed by Autoprefixer, one of the post-processing tools integrated with Create React App. It ensures that your styles are compatible with various browsers. + +**9. Stop the development server by pressing `Ctrl + C` in the terminal.** + +Congratulations! You have successfully experienced the post-processing CSS in Create React App. In this example, Autoprefixer automatically added the necessary prefixes to the CSS property `display: grid`, ensuring cross-browser compatibility. + +Feel free to explore more CSS features and observe how Autoprefixer and other post-processing tools enhance your styles in Create React App. + + +## Live Coding + +```jsx live +function App() { + return ( +
+
Box 1
+
Box 2
+
Box 3
+
+ ); +} +``` + + +## Conclusion + +In this guide, we explored the captivating world of post-processing CSS in Create React App. By leveraging the power of post-processing tools like Autoprefixer, you can effortlessly enhance your stylesheets and ensure cross-browser compatibility. Whether you're embracing new CSS features or catering to specific browser requirements, post-processing CSS has got you covered. Now, go forth and create captivating styles with the magic of post-processing CSS in Create React App! \ No newline at end of file diff --git a/docs/react/styles-and-assets/using-the-public-folder.md b/docs/react/styles-and-assets/using-the-public-folder.md new file mode 100644 index 000000000..314c65397 --- /dev/null +++ b/docs/react/styles-and-assets/using-the-public-folder.md @@ -0,0 +1,63 @@ +--- +id: using-the-public-folder +title: Unleash the Magic of the Public Folder +sidebar_label: Using the Public Folder +sidebar_position: 8 +tags: [react, create-react-app, public-folder, assets, react-scripts, react-dom, react-app] +description: "Learn how to use the public folder in a Create React App project. Customize the HTML file and add assets directly to the public folder to enhance your React application." +--- + +:::tip info +Attention, brave adventurers! This feature requires `react-scripts@0.5.0` or higher. +::: + +## Unveiling the Mysteries of HTML + +Prepare to embark on a journey of HTML customization! Within the sacred `public` folder lies the fabled HTML file, ready to be molded to your will. Feel free to tweak it to your heart's content, whether it's altering the page title or adding [enchanting meta tags](../back-end-integration/title-and-meta-tags.md). And fear not, for the build process shall automatically incorporate the compiled code into this mystical artifact. + +## Discover the Art of Asset Conjuring + +While we typically encourage importing assets through JavaScript for their magical benefits (minification, bundling, and caching), there exists an alternate path—an escape hatch—to add assets directly to the `public` folder. + +Here's the secret: any file you place within the `public` folder will retain its original form, untampered by the sorcery of webpack. To summon these assets, you must invoke the powers of an ancient incantation: the `PUBLIC_URL` environment variable. + +For instance, within `index.html`, witness the power of the `PUBLIC_URL`: + +```html + +``` + +But beware! Only the files within the `public` folder can be accessed through this mystical prefix. Should you require a file from `src` or `node_modules`, you must duplicate it within the `public` folder, thus clearly stating your intention to include it in the grand build. + +During the sacred ritual of `npm run build`, Create React App shall infuse `%PUBLIC_URL%` with the correct absolute path. This ensures your project remains robust, even amidst the treacherous realm of client-side routing or when hosted at a non-root URL. + +To wield the power of `PUBLIC_URL` in your JavaScript spells, simply invoke the `process.env.PUBLIC_URL` incantation: + +```js +render() { + // Note: this is an escape hatch and should be used sparingly! + // Normally, we recommend importing assets using `import`, as described in the "Adding Images and Fonts" section above. + return ; +} +``` + +Yet, be warned of the perils that await you on this path: + +- None of the files in the `public` folder shall undergo post-processing or minification. +- Beware the wrath of missing files, for they shall manifest as dreaded 404 errors upon unsuspecting users. +- The filenames of your results shall remain unchanged, devoid of the mighty content hashes. You must add query arguments or rename them manually whenever they change. + +## Embracing the Arcane Knowledge + +The `public` folder, though an unconventional ally, shines in rare scenarios where alternative methods falter: + +- When you seek to manifest a file with a specific name in the build output, such as the elusive [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +- In the presence of a multitude of images, demanding dynamic path references that push the boundaries of mortal comprehension. +- Should you yearn to include a humble script like [`pace.js`](https://codebyzach.github.io/pace/docs/) outside the confines of bundled code. +- And there are some libraries, resistant to the charms of webpack, that leave you no choice but to beckon them with a humble `