HackMD
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # JavaScript Essentials: A Beginner's Journey ## Array.filter() - Select Specific Items The `filter()` method creates a new array containing only elements that pass a test condition. It's essential when you need to extract subset of data matching criteria, like finding completed tasks or valid user inputs. Unlike loops, filter returns a new array without modifying the original, making your code predictable and safe. ```javascript const numbers = [1, 2, 3, 4, 5]; const evens = numbers.filter(num => num % 2 === 0); console.log(evens); // [2, 4] ``` **Practice**: Filter an array `['apple', 'banana', 'apricot']` to keep only fruits starting with 'a'. --- ## String Methods - Text Manipulation JavaScript provides powerful string methods like `toLowerCase()` and `includes()` for text processing. These are crucial for search features, validation, and data cleaning. `toLowerCase()` ensures case-insensitive comparisons, while `includes()` checks if a substring exists. Chaining these methods creates clean, readable code for complex text operations. ```javascript const text = "Hello World"; const hasHello = text.toLowerCase().includes('hello'); console.log(hasHello); // true ``` **Practice**: Check if the string "JavaScript" contains "script" (case-insensitive). --- ## JSON.stringify() - Data Comparison `JSON.stringify()` converts JavaScript objects and arrays into JSON strings, enabling deep equality checks. This is vital when comparing complex data structures, as `===` only checks reference equality for objects. Stringify transforms data into comparable string format, perfect for validating API responses or testing array contents. ```javascript const arr1 = [1, 2, 3]; const arr2 = [1, 2, 3]; console.log(JSON.stringify(arr1) === JSON.stringify(arr2)); // true ``` **Practice**: Compare two objects `{a: 1}` and `{a: 1}` using JSON.stringify(). --- ## Array.reduce() - Accumulate Values The `reduce()` method processes arrays to produce single values—perfect for sums, products, or building objects. It takes an accumulator function and initial value, applying logic to each element sequentially. Reduce replaces verbose loops for aggregation tasks, making code more functional and expressive. Mastering reduce unlocks elegant solutions to complex calculations. ```javascript const prices = [10, 20, 30]; const total = prices.reduce((sum, price) => sum + price, 0); console.log(total); // 60 ``` **Practice**: Use reduce to find the product of `[2, 3, 4]`. --- ## Method Chaining - Combine Operations Chaining connects multiple array methods in sequence, where each method's output feeds into the next. This creates data pipelines that filter, transform, and reduce in one readable statement. Chaining eliminates intermediate variables and makes data transformation logic flow naturally from left to right, improving code maintainability. ```javascript const nums = [1, 2, 3, 4]; const result = nums.filter(n => n > 2).map(n => n * 2); console.log(result); // [6, 8] ``` **Practice**: Chain filter and reduce to sum all even numbers in `[1, 2, 3, 4, 5, 6]`. --- ## atob() - Decode Base64 `atob()` decodes Base64-encoded strings back to readable text, essential for processing encoded data from APIs or storage. Base64 encoding represents binary data in ASCII format for safe transmission. This function is commonly used alongside `btoa()` (encodes to Base64) for simple encryption-like obfuscation, though not for true security. ```javascript const encoded = "SGVsbG8="; const decoded = atob(encoded); console.log(decoded); // "Hello" ``` **Practice**: Decode the Base64 string "V29ybGQ=" using atob(). --- ## Array.map() - Transform Each Element `map()` creates a new array by applying a transformation function to every element. It's fundamental for data conversion, like formatting prices or normalizing user inputs. Map maintains array length while changing content, making it perfect for parallel transformations. This method embodies functional programming principles by keeping operations pure and predictable. ```javascript const numbers = [1, 2, 3]; const doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6] ``` **Practice**: Convert `['a', 'b', 'c']` to uppercase using map(). --- ## String.split() and Array.join() - Text Assembly `split()` breaks strings into arrays using delimiters, while `join()` reassembles arrays into strings. This pair handles tokenization, word processing, and data formatting. Split with `reverse()` enables palindrome checks and string manipulation. Together, they bridge string and array operations, essential for parsing CSV data, URLs, or custom formats. ```javascript const word = "hello"; const reversed = word.split('').reverse().join(''); console.log(reversed); // "olleh" ``` **Practice**: Split "one-two-three" by "-" and join with spaces. --- ## Math.floor() and Math.min() - Numeric Control `Math.floor()` rounds decimals down to integers, crucial for division results and pagination. `Math.min()` finds the smallest value, essential for limiting ranges and preventing overflows. These methods ensure predictable numeric behavior without external libraries. They're building blocks for algorithms involving resource allocation, rate limiting, or game scoring systems. ```javascript const perPerson = Math.floor(100 / 3); const limited = Math.min(50, 60); console.log(perPerson, limited); // 33, 50 ``` **Practice**: Use Math.floor() to divide 17 by 4, then find minimum of result and 5. --- ## Array.map() with Index - Positional Logic Map's optional second parameter provides the current index, enabling position-dependent transformations. This unlocks conditional logic based on array position, like alternating patterns or tracking coordinates. Index awareness transforms map from simple transformations into a powerful tool for complex data processing requiring positional context. ```javascript const letters = ['a', 'b', 'c']; const indexed = letters.map((letter, i) => `${i}: ${letter}`); console.log(indexed); // ["0: a", "1: b", "2: c"] ``` **Practice**: Use map with index to create array of squares: `[0, 1, 4, 9]` from `[10, 20, 30, 40]`. --- ## Spread Operator - Array Copying The spread operator `...` creates shallow copies of arrays, preventing unintended mutations. This is critical when sorting or modifying arrays without affecting originals. Spread syntax provides cleaner alternatives to `slice()` or manual copying. It's foundational for immutable programming patterns that prevent bugs in React, Redux, and modern JavaScript architectures. ```javascript const original = [3, 1, 2]; const sorted = [...original].sort(); console.log(original, sorted); // [3, 1, 2], [1, 2, 3] ``` **Practice**: Create a copy of `[5, 2, 8]` and reverse it without changing the original. --- ## Array.sort() - Custom Ordering `sort()` arranges array elements using comparison functions. Default alphabetic sorting fails for numbers, so custom comparators `(a, b) => a - b` enable numeric ordering. Ascending uses `a - b`, descending uses `b - a`. Understanding comparators is vital for leaderboards, priority queues, and data presentation requiring specific ordering logic. ```javascript const nums = [10, 5, 100]; nums.sort((a, b) => b - a); // Descending console.log(nums); // [100, 10, 5] ``` **Practice**: Sort `[20, 5, 15]` in ascending order using a comparator. --- ## For Loop Fundamentals - Iteration Control For loops provide explicit iteration control with initialization, condition, and increment. They're essential when you need index access or complex loop logic that array methods can't handle elegantly. Understanding for loops builds intuition for algorithm implementation, from searching to accumulation. They remain relevant for performance-critical code and breaking early from iterations. ```javascript const items = ['a', 'b', 'c']; for (let i = 0; i < items.length; i++) { console.log(items[i]); } ``` **Practice**: Write a for loop that sums numbers from 1 to 5. --- ## Array.sort() on Strings - Lexicographic Order Calling `sort()` without arguments orders strings alphabetically using lexicographic comparison. This is perfect for name lists, file sorting, or alphabetizing data. String sorting is case-sensitive by default—'Z' comes before 'a'. For case-insensitive sorting, combine with `toLowerCase()` in comparator functions for consistent, predictable alphabetization. ```javascript const words = ['banana', 'apple', 'cherry']; words.sort(); console.log(words); // ['apple', 'banana', 'cherry'] ``` **Practice**: Sort `['dog', 'cat', 'bird']` alphabetically. --- ## Object Accumulation with Reduce - Counting Patterns Using `reduce()` with objects creates powerful counting and grouping logic. Initialize with an empty object, then build key-value pairs dynamically. This pattern counts occurrences, groups by category, or builds lookup tables. The `||` operator provides default values for new keys, enabling one-pass data aggregation without separate initialization loops. ```javascript const items = ['a', 'b', 'a']; const counts = items.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {}); console.log(counts); // {a: 2, b: 1} ``` **Practice**: Count occurrences of each number in `[1, 2, 1, 3, 2, 1]` using reduce.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully