JavaScript is a high-level, interpreted programming language primarily used to add interactivity to websites.
- Key Features:
- Dynamically typed
- Prototype-based object-oriented
- First-class functions
JavaScript is a high-level, interpreted programming language primarily used to add interactivity to websites.
|
To include JavaScript in an HTML file, use the
Alternatively, link an external JavaScript file:
|
Basic Syntax:
|
The
|
|
|
|
|
Comments are used to explain code and are ignored by the JavaScript interpreter.
|
|
Good commenting practices:
|
JavaScript has a single number type which can represent both integers and floating-point numbers. |
|
|
Converts a string to an integer.
|
|
Converts a string to a floating-point number.
|
Special Number Values |
|
Number Methods |
|
Variables are used to store data values.
|
|
|
Function-scoped or globally-scoped if declared outside a function. Can be re-declared and re-assigned.
|
|
Block-scoped. Cannot be re-declared within the same scope, but can be re-assigned.
|
|
Block-scoped. Cannot be re-declared or re-assigned. Must be initialized upon declaration.
|
Strings are sequences of characters enclosed in single quotes ( |
|
String Length |
Use
|
String Methods |
|
String Concatenation |
Use the
|
JavaScript supports standard arithmetic operators:
|
|
Increment and Decrement Operators:
|
|
Assignment operators assign values to variables.
|
|
|
|
|
|
|
|
|
|
|
|
String interpolation allows you to embed expressions directly within string literals, using template literals (backticks |
|
Basic Usage |
Use
|
Expression Evaluation |
Expressions inside
|
Multiline Strings |
Template literals can span multiple lines without needing concatenation or escape characters.
|
The
|
|
|
|
Temporal Dead Zone (TDZ): |
The
|
|
|
|
Note:
|
The
|
Example:
|
The condition is a Boolean expression that evaluates to |
If the condition is |
If the condition is |
You can also nest |
|
The ternary operator is a shorthand way of writing an
|
Example:
|
If |
The ternary operator can be useful for assigning values based on a condition. |
It is often used for simple, concise conditional logic. |
Avoid using nested ternary operators, as they can become difficult to read and understand. |
Comparison Operators: |
Used to compare values and return a Boolean result. |
|
Equal to (value only) |
|
Strict equal to (value and type) |
|
Not equal to (value only) |
|
Strict not equal to (value and type) |
|
Greater than |
|
Greater than or equal to |
|
Less than |
|
Less than or equal to |
The
|
Example:
|
You can have multiple |
The |
JavaScript executes the first |
The
|
Example:
|
The |
If a |
The |
The |
You can group multiple |
|
Checks for equality of values after performing type coercion (if necessary). |
Example:
|
|
|
Checks for equality of both value and type without type coercion. |
Example:
|
|
Recommendation: |
Always use |
A function declaration defines a named function.
Example:
|
Function declarations are hoisted, meaning they can be called before they are defined in the code. |
The |
A function expression defines a function inside an expression.
Example:
|
Function expressions are not hoisted, so they must be defined before they are called. |
The function can be anonymous (as shown above) or have a name (named function expression). |
An anonymous function is a function without a name. They are often used in function expressions or as arguments to other functions.
Example:
|
Anonymous functions are commonly used as callback functions. |
They can be immediately invoked using the IIFE (Immediately Invoked Function Expression) pattern. |
Arrow functions provide a concise syntax for writing function expressions. Introduced in ES6.
Example:
|
If there is only one parameter, the parentheses can be omitted: |
If the function body is a single expression, the curly braces and |
Arrow functions do not have their own |
The
Example:
|
If the |
The |
Functions are called by using their name followed by parentheses, optionally including arguments.
Example:
|
Functions can be called directly or assigned to variables. |
If a function expects arguments but none are provided, the missing arguments will have a value of |
If more arguments are passed than expected, the extra arguments are ignored. |
Function parameters are the names listed in the function’s definition.
Example:
|
Parameters are local variables within the function’s scope. |
ES6 allows default parameter values:
|
Rest parameters allow a function to accept an indefinite number of arguments as an array:
|
Scope determines the accessibility of variables. In JavaScript, scope can be global or local.
|
JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible from outside the function. |
Example:
|
|
|
Using |
When you declare a variable outside any function, it becomes a global variable. Global variables can be accessed and modified from anywhere in your code. |
|
Important Note: Avoid using global variables excessively, as they can lead to naming conflicts and make code harder to maintain and debug. |
Accidental Global Variables: If you assign a value to a variable that has not been declared, JavaScript will automatically declare it as a global variable (in non-strict mode). Always declare variables using |
|
Function-scoped or globally-scoped. Can be re-declared and updated. Hoisted to the top of its scope and initialized with |
|
Block-scoped. Can be updated but not re-declared within its scope. Hoisted but not initialized, resulting in a |
Example: |
|
A common pitfall involves using |
Incorrect (using
In this case, by the time the |
Correct (using
|
Alternatively, using an IIFE (Immediately Invoked Function Expression) with
|
When a variable is used, JavaScript engine tries to find the variable in the current scope. If it’s not found, it looks in the outer scope, and continues up the chain of scopes until it reaches the global scope. This is called the scope chain. |
|
In the |
JavaScript uses lexical scoping (also known as static scoping). The scope of a variable is determined by its position in the source code. |
|
|
Arrays in JavaScript are ordered lists of values. They can hold values of any data type, including numbers, strings, booleans, objects, and even other arrays. |
Arrays are dynamic, meaning their size can grow or shrink as needed. |
Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. |
Creating Arrays: Using array literal:
Using the
|
Note: |
The |
|
You can modify the length of an array by assigning a new value to the |
|
Array elements are accessed using their index, starting from 0. |
|
If you try to access an index that doesn’t exist, you’ll get |
|
Arrays in JavaScript are mutable, meaning you can change their contents after they are created. |
You can modify an array by assigning new values to specific indices. |
|
The |
|
The |
|
If the array is empty, |
|
The |
|
If the array is empty, |
|
The |
|
The |
|
You can concatenate multiple arrays or values: |
|
The
|
Example:
|
Important: Ensure the condition eventually becomes false to avoid infinite loops. |
Looping backwards is useful for certain array manipulations or when needing to process elements in reverse order.
|
Example:
|
The
|
Example:
|
Even if the condition is initially false, the loop body will execute once:
|
The
|
|
Example:
|
Arrays are commonly iterated over using
|
The |
The
|
The
|
Loops can be nested inside other loops to handle multi-dimensional data or complex iterative tasks.
|
The
|
Note: Be cautious when using |
The
|
It is a cleaner and more direct way to iterate over values in iterable objects compared to the traditional |
In JavaScript, functions can be assigned to variables, allowing for flexible and reusable code. Declaration:
Usage:
|
Arrow Function Assignment:
Usage:
|
Benefits:
|
A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete an action. Example:
|
Asynchronous Callbacks: Example:
|
Benefits:
|
The Syntax:
Parameters:
|
Example:
|
Use Cases:
|
The Syntax:
Parameters:
|
Example:
|
Use Cases:
|
The Syntax:
Parameters:
|
Example:
|
Use Cases:
|
The Syntax:
Parameters:
|
Example:
|
Use Cases:
|
Array methods can be chained together to perform multiple operations in a concise way. Example:
|
Explanation:
|
Benefits:
|
Example 1: Extracting Names from Objects
|
Example 2: Calculating Average Score
|
Example 3: Filtering Active Users
|
Dot notation |
Access properties using a dot followed by the property name.
|
Bracket notation |
Access properties using square brackets with the property name as a string.
|
Dynamic access |
Bracket notation allows accessing properties with dynamically determined names.
|
Valid names |
Property names can be strings or symbols. String names must follow JavaScript identifier rules or be quoted.
|
Reserved words |
Avoid using reserved words as property names to prevent unexpected behavior.
|
Accessing undefined properties |
Accessing a property that doesn’t exist returns
|
Checking property existence |
Use
|
Object mutability |
Objects are mutable, meaning their properties can be changed after creation.
|
Const objects |
|
Property value shorthand |
If a variable name matches the property name, you can use the shorthand.
|
Computed property names |
Use square brackets to define property names dynamically.
|
Deleting properties |
The
|
Non-configurable properties |
Properties defined as non-configurable cannot be deleted.
|
Passing objects |
Objects are passed by reference. Modifying the object inside a function affects the original object.
|
Destructuring arguments |
Use destructuring to extract properties from an object passed as an argument.
|
Example |
When a variable name is the same as the object key you can simplify the object declaration
|
Context |
Refers to the context in which a function is executed.
|
Arrow functions |
Arrow functions do not bind their own
|
Definition |
A function that returns a new object.
|
Definition |
Functions assigned as properties of objects.
|
Definition |
Special methods that allow you to define custom behavior when getting or setting a property value.
|
Classes are a template for creating objects. They encapsulate data with code to work on that data. JavaScript classes are built on prototypes but also have some syntax and semantics that are unique to classes.
|
|
Classes are in fact “special functions”, and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations. |
The |
|
If you do not specify a constructor method, a default constructor is used. The arguments for the default constructor are the arguments passed to the class’s |
|
Class methods are defined inside the class body. They can access the class’s properties and other methods using
|
Methods can return values or perform actions within the class.
|
|
Static methods are called directly on the class (not on an instance) and are often used for utility functions.
|
Static methods are useful for creating utility functions that are related to the class but don’t require an instance.
|
|
The
|
Use
|
You can override methods from the parent class in the child class to provide specialized behavior.
|
Modules in JavaScript allow you to split your code into separate files. This improves code organization, reusability, and maintainability. Modules help avoid naming conflicts and provide a way to manage dependencies. Key Concepts:
|
JavaScript modules primarily come in two flavors:
|
Named Exports: |
Exporting specific variables, functions, or classes by their names.
|
Default Export: |
Exporting a single value as the default export.
|
Exporting at the End: |
You can also declare variables and functions first, then export them.
|
Named Imports: |
Importing specific values using their names.
|
Default Import: |
Importing the default export. You can name the import anything you like.
|
Importing Everything: |
Importing all exports into a single namespace.
|
Renaming Imports: |
Renaming imports using the
|
Exporting Properties: |
In CommonJS, you use the
|
Exporting a Single Value: |
You can also export a single value by assigning it directly to
|
Importing Modules: |
Use the
|
Importing a Single Value: |
If a module exports a single value,
|
Dynamic imports allow you to load modules asynchronously, typically used for code splitting or loading modules on demand. They use the
Use Cases:
|
Pending: Initial state; neither fulfilled nor rejected. Fulfilled: The operation completed successfully. Rejected: The operation failed. |
A promise can only resolve once. Subsequent calls to |
Promises help manage asynchronous operations in JavaScript, providing a cleaner alternative to callbacks. |
The executor function is passed to the It takes two arguments: |
|
The executor function is executed immediately when the |
It delays the execution of a function by a specified number of milliseconds. |
|
This allows you to work with asynchronous code in a synchronous-like manner. |
The It takes one or two arguments: a callback function for fulfillment and an optional callback function for rejection. |
|
It returns a new promise, allowing for chaining. |
The It’s a shorthand for |
|
Using |
|
|
It’s useful when you need to wait for multiple asynchronous operations to complete before proceeding. |
Nesting Use promise chaining to avoid excessive nesting. |
|
Chaining makes the code flow more linearly and easier to understand. |
To create a Promise, use the |
|
|
You can chain multiple Each |
|
This allows you to build complex asynchronous workflows in a readable manner. |
Simulating an HTTP request with a Promise and |
|
This example simulates fetching data from a server and handles both success and failure scenarios. |
JavaScript is single-threaded, meaning it executes code sequentially. Asynchronous operations allow the program to continue running while waiting for long-running tasks (like network requests) to complete. Key Concepts:
|
Async/await simplifies asynchronous JavaScript, making it easier to read and write asynchronous code. It’s built on promises. |
Promises represent the eventual result of an asynchronous operation. They can be in one of three states:
To handle the result of a promise, you use |
|
An
|
|
The
|
|
Async/await makes asynchronous code look and behave a bit more like synchronous code. This can drastically improve the readability and maintainability of your asynchronous JavaScript. Benefits:
|
|
Error handling in async/await is done using the standard Best Practices:
|
|
The If the Promise rejects, the Example:
|
|
Async/await can be used in various scenarios, such as fetching data from an API, reading files, or interacting with databases. Fetching Multiple APIs:
Sequential API Calls:
|
JSON (JavaScript Object Notation): A lightweight data-interchange format. Easy for humans to read and write. Easy for machines to parse and generate. Key Features:
|
JSON Syntax Rules:
|
Example:
|
JSON Values:
|
JSON.stringify(): Converts a JavaScript object to a JSON string. Example:
|
JSON.parse(): Converts a JSON string to a JavaScript object. Example:
|
XMLHttpRequest (XHR): A browser API to transfer data between a client and a server without a full page refresh. Note: Creating an XHR Object:
|
Opening a Request:
Example:
|
Sending the Request:
Example:
|
Handling the Response:
|
Setting Headers:
Common headers include |
Example (GET request):
|
GET Requests: Used to retrieve data from a server. Data is appended to the URL. Characteristics:
|
Using XMLHttpRequest:
|
Using Fetch API:
|
Adding Parameters to URL:
|
POST Requests: Used to send data to a server to create/update a resource. Data is sent in the request body. Characteristics:
|
Using XMLHttpRequest:
|
Using Fetch API:
|
Fetch API: A modern interface for making network requests. It provides a more powerful and flexible feature set than Basic Syntax:
|
Options:
|
Handling Responses:
|
Simple GET Request:
|
Simple POST Request:
|
JSON Formatted Requests: Sending and receiving data in JSON format is common when using APIs. Key Considerations:
|
Example (Fetch API POST with JSON):
|
Example (Fetch API GET and parse JSON):
|
Promises: Fetch API uses promises to handle asynchronous operations. URL Parameters: You can add parameters to the URL when making a GET request. |
Example (Fetch API with URL Parameters):
|
Chaining Promises:
|
Fetch API Function: Encapsulating fetch requests into reusable functions. Benefits:
|
Example (Reusable Fetch Function):
|
Async/Await: Syntactic sugar built on top of promises, making asynchronous code easier to read and write. Key Concepts:
|
Example (Async/Await with Fetch API):
|
Example (Async/Await POST Request):
|