# JavaScript

* Use "modern" JavaScript approaches (aka [**ES5**](https://www.w3schools.com/js/js_es5.asp), [**ES6**](https://www.w3schools.com/js/js_es6.asp) & newer)
  * **variables**: `const` & `let` (instead of `var`) [**\[1\]**](https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/)[**\[2\]**](https://www.shecodes.io/athena/124459-why-are-we-using-let-and-not-const)
    * try to use `const` when possible [**\[1\]**](https://stackoverflow.com/questions/41086633/in-javascript-why-should-i-usually-prefer-const-to-let)[**\[2\]**](https://youtu.be/dqmtzHB2zTM?si=WXkRgSIdxQ9EVOXs\&t=1509)
      * If you must use `let` for your implementation, it may be a sign of "code smell". Consider alternate implementations that allow you to use `const`
      * When "reassigning the variable" makes the most sense, use **`let` + switch statement** (vs const + nested ternary operators)

<details>

<summary>Example (const vs let -- immutable vs mutable vs reassignable)</summary>

```tsx
// Variables -- const vs let

// IMMUTABLE / READ-ONLY / CONSTANT VALUES
// - const, UPPER_CASE
// - cannot be reassigned or mutated

// (1) primitive values
const SERVER_URL = "https://api.example.com";

// (2) object values (JS objects, arrays, functions, ...)
const BRANDS_WE_WORK_WITH = Object.freeze(["Apple", "Google", "Microsoft"]);


// MUTABLE / CONSTANT REFERENCES
// - const, camelCase
// - cannot be reassigned (constant references), CAN be mutated (e.g. array.push())
const brands = [...BRANDS_WE_WORK_WITH];


// REASSIGNABLE / VARIABLE REFERENCES
// - let, camelCase
// - CAN be reassigned, CAN be mutated
let count = 0;
```

</details>

<details>

<summary>Example (const vs let -- let + switch statement)</summary>

```tsx
// let + switch statement (preferred)
let chip = null;
switch (hasReviewedSection) {
  case null:
    chip = <Chip label="Not reviewed" color="default" />;
    break;
  case "changed":
    chip = <Chip label="Changes" color="warning" />;
    break;
  default:
    chip = (
      <Chip
        label={hasReviewedSection ? "Reviewed" : "Reviewing"}
        color={hasReviewedSection ? "success" : "primary"}
      />
    );
    break;
}

// const + nested ternary operators
const chip =
  hasReviewedSection === null ? (
    <Chip label="Not reviewed" color="default" />
  ) : hasReviewedSection === "changed" ? (
    <Chip label="Changes" color="warning" />
  ) : (
    <Chip
      label={hasReviewedSection ? "Reviewed" : "Reviewing"}
      color={hasReviewedSection ? "success" : "primary"}
    />
  );
```

</details>

* **array methods** [**\[1\]**](https://www.freecodecamp.org/news/loop-through-arrays-javascript/)
  * `forEach`, `map`, `filter`, `reduce`, `sort`, `some`, `every`, ...
  * ![](https://2248755224-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FkVQm1PpPMvCvQccIZPyj%2Fuploads%2Ft75DRm0fb09NKwGp0AsN%2FIMG_3060.jpg?alt=media\&token=721cec8c-cc13-4e4a-b5cc-a693ffba8618)
* ...
