## 💻 UNIT II: JavaScript and ECMAScript
This unit covers the core fundamentals of **JavaScript** and key features introduced in
**ECMAScript 2015 (ES6)** and later versions.
### 1. JavaScript Fundamentals
#### Grammar and Types
JavaScript is a **dynamically typed** language.
* **Syntax:** Uses a C-style grammar (curly braces for blocks, semicolons for termination, though
often optional due to automatic semicolon insertion).
* **Case Sensitivity:** JavaScript identifiers (variables, functions, keywords) are **case-sensitive**.
* **Data Types:**
* **Primitive Types (Value Types):**
* `Number` (includes integers and floating-point numbers)
* `String` (textual data)
* `Boolean` (`true` or `false`)
* `Undefined` (a variable has been declared but not assigned a value)
* `Null` (intentional absence of any object value)
* `Symbol` (ES6, unique identifiers)
* `BigInt` (ES2020, for very large integers)
* **Non-Primitive Type (Reference Type):**
* `Object` (includes standard objects, `Arrays`, and `Functions`)
#### Control Flow and Error Handling
These structures dictate the order in which code executes.
* **Conditional Statements:**
* `if...else` / `else if`: Executes a block of code based on a condition's truthiness.
* `switch`: Evaluates an expression against multiple potential cases.
* **Error Handling:**
* `try...catch...finally`:
* `try`: Contains the code block to monitor for errors.
* `catch (error)`: Contains the code block to execute if an error occurs in the `try` block.
* `finally`: Contains the code that executes after the `try` and `catch` blocks, regardless of the
outcome.
* `throw`: Used to explicitly create and throw an exception (error).
#### Loops
Loops execute a block of code repeatedly until a specific condition is met.
* `for` loop: Ideal when the number of iterations is known.
* `while` loop: Executes as long as a condition is `true`.
* `do...while` loop: Executes the block *once* before checking the condition, then continues while
the condition is `true`.
* `for...in`: Iterates over the **enumerable properties of an object**.
* `for...of` (ES6): Iterates over **iterable objects** like arrays, strings, maps, and sets.
---
### 2. Core Data Structures: Functions, Objects, and Arrays
#### Function
Functions are a fundamental building block, encapsulating reusable code.
* **Definition:** Declared using the `function` keyword, a function name, parameters, and a body.
* **First-Class Citizens:** In JavaScript, functions are **first-class objects**, meaning they can be:
* Assigned to variables.
* Passed as arguments to other functions (callbacks).
* Returned as values from other functions (higher-order functions).
#### Objects
Objects are collections of **key-value pairs** and are the foundation of JavaScript programming.
* **Creation:** Often created using literal notation (`{ key: value, method: function() {...} }`).
* **Properties:** The keys (strings or Symbols) are properties, and their associated values can be
any data type, including other objects or functions (methods).
#### Arrays
Arrays are a special type of object used to store ordered collections of values.
* **Zero-Indexed:** Elements are accessed using a zero-based index (`array[0]`).
* **Dynamic:** Arrays are dynamic; their size can change during runtime.
* **Methods:** Possess numerous built-in methods for manipulation (`push`, `pop`, `shift`, `unshift`,
`splice`, `map`, `filter`, `reduce`).
---
### 3. Asynchronous Programming
#### Promises
A **Promise** is an object representing the eventual completion (or failure) of an asynchronous
operation and its resulting value.
* **States:** A Promise exists in one of three mutually exclusive states:
1. **`pending`:** Initial state; the operation hasn't finished.
2. **`fulfilled` (or `resolved`):** The operation completed successfully.
3. **`rejected`:** The operation failed, and an error was thrown.
* **Handling:** Handled using `.then()` for successful resolution and `.catch()` for rejection.
---
### 4. ECMAScript 6 (ES6) and Beyond
ECMAScript 2015 (ES6) introduced significant syntax improvements, improving code readability and
manageability.
#### Let and Const
These are the modern ways to declare variables, offering **block-scoping**, unlike the function-
scoping of `var`.
* **`let`:** Used for variables that **will be reassigned** (i.e., their value will change).
* **`const`:** Used for variables that **should not be reassigned** (i.e., their reference remains
constant). *Note: The value/contents of an object or array declared with `const` can still be
mutated.*
#### Template Literals
A way to create strings using backticks (`` ` ``) that allows for **embedded expressions** and
**multi-line strings** without using the `+` operator or `\n`.
* **Syntax:** `` `Hello, ${name}. Your age is ${age + 1}.` ``
#### Arrow Function (`=>`)
A concise syntax for writing function expressions.
* **Conciseness:** Omits the `function` keyword and often the `return` keyword and curly braces for
single-expression functions.
* **Lexical `this`:** Unlike traditional functions, arrow functions **do not bind their own `this`
value**. They inherit `this` from the surrounding (lexical) scope, which simplifies development in
object-oriented and asynchronous contexts.
#### Default Parameter
Allows formal parameters to be initialized with a default value if no value or `undefined` is passed.
* **Syntax:** `function greet(name = 'Guest') { ... }`
#### Async Await (ES2017)
Syntactic sugar built on top of Promises to make asynchronous code appear and behave more like
synchronous code, making it easier to read and debug.
* **`async` Keyword:** Used to define a function that returns a Promise.
* **`await` Keyword:** Can only be used inside an `async` function. It pauses the execution of the
`async` function until the Promise it precedes is resolved, and then returns the resolved value.
***
Would you like a deeper dive into any specific topic, such as the difference between `map`, `filter`,
and `reduce` for Arrays?