diff --git a/docs/javascript/Client-side-Frameworks.md b/docs/javascript/Client-side-Frameworks.md new file mode 100644 index 000000000..186a94aad --- /dev/null +++ b/docs/javascript/Client-side-Frameworks.md @@ -0,0 +1,75 @@ +--- +id: Client-side-frameworks +title: Client side Frameworks of js +sidebar_label: Client-side Frameworks +sidebar_position: 42 +tags: + [ JavaScript, Framework,React , Ember , Angular , Web-Framework , Component , js-components , JS, js-frameworks ] +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." +--- +# Introduction to Client-side Frameworks + +Client-side frameworks have revolutionized web development, providing developers with powerful tools to build interactive and dynamic web applications. This comprehensive guide offers an in-depth overview of the history of JavaScript and frameworks, the major frameworks available, their purposes, considerations for choosing the right one, and alternatives to client-side frameworks. + +## Prerequisites +Before diving into client-side frameworks, it's essential to have a solid understanding of the core web technologies, including HTML, CSS, and JavaScript. Familiarity with programming concepts and principles will also be beneficial. + +## Objective +The objective of this guide is to equip developers with a thorough understanding of client-side frameworks, enabling them to make informed decisions about which framework to use for their projects. By the end of this guide, developers should feel confident in their ability to navigate the landscape of client-side frameworks and select the most suitable option for their needs. + +## A Brief History + +JavaScript, introduced in 1996, marked a pivotal moment in web development by enabling interactivity in web pages. As web applications became more complex, developers sought ways to manage the growing complexity. This led to the emergence of frameworks, which provided structured solutions to common development challenges. + +Over the years, JavaScript frameworks have evolved significantly, with new frameworks emerging and existing ones undergoing major updates. Today, there are numerous client-side frameworks available, each with its own unique features, advantages, and use cases. + +## Major Frameworks + +### Ember +- **Release:** December 2011 +- **Description:** Ember is a mature framework derived from the SproutCore project. While it may have fewer users compared to newer alternatives, it offers stability, extensive community support, and follows clever coding principles. Ember's convention over configuration approach simplifies development by providing a predefined structure for applications. + +### Angular +- **Release:** September 14, 2016 +- **Description:** Angular, developed by Google, is a comprehensive web application framework. It emphasizes component-based architecture, declarative HTML templates, and uses TypeScript to enhance developer productivity. Angular's dependency injection system and built-in features such as routing and form validation make it suitable for building large-scale applications. + +### Vue +- **Release:** 2014 +- **Description:** Vue, created by Evan You, has gained popularity for its simplicity and flexibility. It extends HTML with modern JavaScript features and provides reactive data binding and component-based architecture. Vue's progressive nature allows developers to incrementally adopt its features, making it suitable for both small projects and large-scale applications. + +### React +- **Release:** 2013 +- **Description:** React, developed by Facebook, is a library for building user interfaces. While technically not a framework, it is commonly used with ReactDOM to create dynamic web and mobile applications. React's component-based architecture and virtual DOM abstraction enable efficient rendering and seamless updates to the UI. React's ecosystem, including tools like Redux and React Router, provides comprehensive solutions for building complex applications. + +![Frameworks Image](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSYitYe9CV_iVxq_yOMgLEGv7uV-755TXgLVA&s) + +## Why Frameworks Exist + +Frameworks address the challenges of modern software development by providing structure, conventions, and reusable components. They enable developers to manage application state, handle data flow, and update the UI efficiently. + +### The Verbosity of DOM Changes +Manipulating the Document Object Model (DOM) to reflect changes in application state often results in verbose code. Frameworks abstract away DOM manipulation, simplifying the development process and reducing boilerplate code. By providing abstractions for common tasks such as state management, routing, and data fetching, frameworks enable developers to focus on building features rather than writing repetitive code. + +## How to Choose a Framework + +Selecting the right framework requires careful consideration of various factors, including project requirements, team expertise, and community support. Here are some key questions to consider: + +1. **Browser Support:** Ensure the framework supports the browsers targeted for your application. Consider compatibility with older browsers if your audience includes users with diverse browser preferences. + +2. **Languages:** Evaluate the framework's use of domain-specific languages such as TypeScript and its impact on development workflow. TypeScript offers static typing and other features that can enhance code quality and maintainability but may require additional learning for developers unfamiliar with the language. + +3. **Community and Documentation:** Assess the strength of the framework's community support, availability of documentation, and additional resources. A vibrant community can provide valuable support, resources, and contributions to the framework's ecosystem, making it easier for developers to troubleshoot issues, learn new concepts, and stay updated on best practices. + +## Alternatives to Client-side Frameworks + +While client-side frameworks offer powerful capabilities, they may not be suitable for every project. Consider alternative approaches to web development, such as: + +- **Content Management Systems (CMS):** Utilize platforms like WordPress or Joomla for content-driven websites. CMS platforms provide pre-built solutions for managing content, user authentication, and other common website features, reducing the need for custom development. + +- **Server-side Rendering (SSR):** Improve initial page load times by rendering HTML on the server. SSR frameworks like Next.js and Nuxt.js enable developers to build server-rendered applications with JavaScript, offering the benefits of client-side interactivity while ensuring fast initial page loads and improved SEO. + +- **Static Site Generators (SSG):** Generate static HTML files for simple, fast-loading websites. SSG tools like Gatsby and Hugo enable developers to build websites using modern web development techniques such as React and Vue, while generating static HTML files that can be served efficiently from a content delivery network (CDN). + +## Summary + +Client-side frameworks have transformed web development, providing efficient solutions for building dynamic and interactive applications. By understanding the history, purpose, and available options of frameworks, developers can make informed decisions and leverage the right tools for their projects. Dive into the world of frameworks with enthusiasm, prepared to explore, learn, and innovate! Whether you choose Ember, Angular, Vue, React, or explore alternative approaches, the possibilities for web development are limitless. \ No newline at end of file diff --git a/docs/javascript/array-methods.md b/docs/javascript/array-methods.md new file mode 100644 index 000000000..5a9047bd7 --- /dev/null +++ b/docs/javascript/array-methods.md @@ -0,0 +1,167 @@ +--- +id: array-methods +title: Array methods in JavaScript +sidebar_label: Array-methods +sidebar_position: 18 +tags: [JavaScript, Arrays, Array Methods,Array length, Array Slice ] +description: "This tutorial demonstrates how to use Array methods in JavaScript with Example" +--- + +# JavaScript Array Methods + +JavaScript provides a variety of methods to manipulate and work with arrays efficiently. Here is a comprehensive overview of some basic and essential array methods. + +## Basic Array Methods + +### Array `length` + +The `length` property returns the length (size) of an array. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +let size = fruits.length; +console.log(size); // Output: 4 +``` + +### Array `toString()` + +The `toString()` method converts an array to a string of comma-separated array values. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +console.log(fruits.toString()); // Output: "Banana,Orange,Apple,Mango" +``` + +### Array `at()` + +The `at()` method returns the element at the specified index. It also supports negative indexing. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +let fruit = fruits.at(2); +console.log(fruit); // Output: "Apple" +``` + +**Note:** +Many languages allow negative bracket indexing like `[-1]` to access elements from the end of an array. This is not possible in JavaScript using `[]` because `[]` is used for accessing both arrays and objects. The `at()` method, introduced in ES2022, solves this problem. + +### Array `join()` + +The `join()` method joins all array elements into a string. You can specify a separator. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +console.log(fruits.join(" * ")); // Output: "Banana * Orange * Apple * Mango" +``` + +## Popping and Pushing + +When you work with arrays, it is easy to remove elements and add new elements. + +### JavaScript Array `pop()` + +The `pop()` method removes the last element from an array and returns it. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +let fruit = fruits.pop(); +console.log(fruit); // Output: "Mango" +console.log(fruits); // Output: ["Banana", "Orange", "Apple"] +``` + +### JavaScript Array `push()` + +The `push()` method adds a new element to an array (at the end). + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +fruits.push("Kiwi"); +console.log(fruits); // Output: ["Banana", "Orange", "Apple", "Mango", "Kiwi"] +``` + +## Shifting Elements + +Shifting is equivalent to popping, but working on the first element instead of the last. + +### JavaScript Array `shift()` + +The `shift()` method removes the first array element and "shifts" all other elements to a lower index. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +fruits.shift(); +console.log(fruits); // Output: ["Orange", "Apple", "Mango"] +``` + +### JavaScript Array `unshift()` + +The `unshift()` method adds a new element to an array (at the beginning), and "unshifts" older elements. + +**Example:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +fruits.unshift("Lemon"); +console.log(fruits); // Output: ["Lemon", "Banana", "Orange", "Apple", "Mango"] +``` + +## JavaScript Array `delete` + +**Warning!** Using `delete` leaves `undefined` holes in the array. Use `pop()` or `shift()` instead. + +## Merging Arrays (Concatenating) + +In programming languages, concatenation means joining strings end-to-end. Concatenating arrays means joining arrays end-to-end. + +### JavaScript Array `concat()` + +The `concat()` method creates a new array by merging (concatenating) existing arrays. + +**Example (Merging Two Arrays):** +```javascript +const myGirls = ["Cecilie", "Lone"]; +const myBoys = ["Emil", "Tobias", "Linus"]; +const myChildren = myGirls.concat(myBoys); +console.log(myChildren); // Output: ["Cecilie", "Lone", "Emil", "Tobias", "Linus"] +``` +:::info Note + +The `concat()` method does not change the existing arrays. It always returns a new array and can take any number of array arguments. + +::: + +**Example (Merging Three Arrays):** +```javascript +const arr1 = ["Cecilie", "Lone"]; +const arr2 = ["Emil", "Tobias", "Linus"]; +const arr3 = ["Robin", "Morgan"]; +const myChildren = arr1.concat(arr2, arr3); +console.log(myChildren); // Output: ["Cecilie", "Lone", "Emil", "Tobias", "Linus", "Robin", "Morgan"] +``` + +### Array `copyWithin()` + +The `copyWithin()` method copies array elements to another position in an array. + +**Example: Copy to index 2, all elements from index 0:** +```javascript +const fruits = ["Banana", "Orange", "Apple", "Mango"]; +fruits.copyWithin(2, 0); +console.log(fruits); // Output: ["Banana", "Orange", "Banana", "Orange"] +``` + + +Additional methods and their usage: + +- Array `slice()` +- Array `splice()` +- Array `toSpliced()` +- Array `flat()` + +These methods provide additional flexibility and functionality when working with arrays in JavaScript. \ No newline at end of file diff --git a/docs/javascript/do-while.md b/docs/javascript/do-while.md new file mode 100644 index 000000000..4172aa806 --- /dev/null +++ b/docs/javascript/do-while.md @@ -0,0 +1,165 @@ +--- +id: do-while loop +title: do...while loop +sidebar_label: do...while loop +sidebar_position: 23 +tags : [JavaScript,do...while , Loops, js-loops,js-fundamentals] +description: "this tutorial demonstrates how to use do-while with example and description about loops and javascript" +--- + +# `do...while` Statement + +The `do...while` statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once. + +A `do…while` loop in JavaScript is a control statement in which the code is allowed to execute continuously based on a given boolean condition. It is like a repeating `if` statement. + +The `do…while` loop can be used to execute a specific block of code at least once. + +## Types of Loops + +There are mainly two types of loops: + +1. **Entry Controlled Loops**: In this type of loop, the test condition is tested before entering the loop body. `For` Loop and `While` Loops are entry-controlled loops. +2. **Exit Controlled Loops**: In this type of loop, the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The `do...while` loop is an exit controlled loop. + +### Example + +```javascript +let result = ''; +let i = 0; + +do { + i = i + 1; + result = result + i; +} while (i < 5); + +console.log(result); +// Expected output: "12345" +``` + +**Output:** +``` +"12345" +``` + +## Syntax + +```javascript +do + statement +while (condition); +``` + +- **statement**: A statement that is executed at least once and re-executed as long as the condition evaluates to true. You can use a block statement to execute multiple statements. +- **condition**: An expression evaluated after each pass through the loop. If this condition evaluates to true, the statement is re-executed. When the condition evaluates to false, execution continues with the statement after the `do...while` loop. + +## Description + +Like other looping statements, you can use control flow statements inside the statement: + +- `break` stops statement execution and goes to the first statement after the loop. +- `continue` stops statement execution and re-evaluates the condition. + +The `do...while` statement syntax requires a semicolon at the end, but the automatic semicolon insertion process may insert one for you if the lack of a semicolon results in invalid syntax. + +## Examples + +### Using `do...while` + +In the following example, the `do...while` loop iterates at least once and reiterates until `i` is no longer less than 5. + +```javascript +let result = ""; +let i = 0; +do { + i += 1; + result += `${i} `; +} while (i > 0 && i < 5); + +console.log(result); +// Despite i === 0 this will still loop as it starts off without the test +``` + +### Using `false` as `do...while` Condition + +Because the statement is always executed once, `do...while (false)` is the same as executing the statement itself. This is a common idiom in C-like languages, which allows you to use `break` to break out of branching logic early. + +```javascript +do { + if (!user.loggedIn) { + console.log("You are not logged in"); + break; + } + const friends = user.getFriends(); + if (!friends.length) { + console.log("No friends found"); + break; + } + for (const friend of friends) { + handleFriend(friend); + } +} while (false); +// The rest of the code +``` + +In JavaScript, there are some alternatives, such as using a labeled block statement with `break`: + +```javascript +handleFriends: { + if (!user.loggedIn) { + console.log("You are not logged in"); + break handleFriends; + } + const friends = user.getFriends(); + if (!friends.length) { + console.log("No friends found"); + break handleFriends; + } + for (const friend of friends) { + handleFriend(friend); + } +} +``` + +Or using a function: + +```javascript +function handleFriends() { + if (!user.loggedIn) { + console.log("You are not logged in"); + return; + } + const friends = user.getFriends(); + if (!friends.length) { + console.log("No friends found"); + return; + } + for (const friend of friends) { + handleFriend(friend); + } +} +``` + +### Using an Assignment as a Condition + +In some cases, it can make sense to use an assignment as a condition, such as this: + +```javascript +do { + // … +} while ((match = regexp.exec(str))); +``` + +But when you do, there are readability trade-offs. The `while` documentation has a Using an assignment as a condition section with recommendations. + +![JavaScript Loops](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQN3DMIcoe0Mv5o_NPcGvgIxgXxDpiNHS3uV1o_Z2XuLkBBBj19o30c1T6wH1AYm4iP29c&usqp=CAU) + +:::info Note + +> If you use a variable in the condition, you must initialize it before the loop, and increment it within the loop. Otherwise, the loop will never end. This will crash your browser. +> If the condition is always true, the loop will never end. This will also crash your browser. + +::: +## Parameters + +- **condition** (Required): The condition for running the code block. If true, the loop will start over again, otherwise it ends. diff --git a/docs/javascript/object-constructor.md b/docs/javascript/object-constructor.md new file mode 100644 index 000000000..30492469b --- /dev/null +++ b/docs/javascript/object-constructor.md @@ -0,0 +1,282 @@ +--- +id: 0bject Constructor +title: JavaScript Object Constructor +sidebar_label: Object Constructor +sidebar_position: 17 +tags : [JavaScript,Object,OOP,constructor,constructor-function,function ] +description: "this tutorial demonstrates how to use constructors in javascript , types of constructors and methods" +--- + +# Object Constructor Functions + +Sometimes we need to create many objects of the same type. To create an object type, we use an object constructor function. It is considered good practice to name constructor functions with an upper-case first letter. + +## Object Type: Person + +```javascript +function Person(first, last, age, eye) { + this.firstName = first; + this.lastName = last; + this.age = age; + this.eyeColor = eye; +} +``` +:::info Note + +> In the constructor function, `this` has no value. The value of `this` will become the new object when a new object is created. + +::: +### Creating New Person Objects + +Now we can use `new Person()` to create many new Person objects: + +```javascript +const myFather = new Person("John", "Doe", 50, "blue"); +const myMother = new Person("Sally", "Rally", 48, "green"); +const mySister = new Person("Anna", "Rally", 18, "green"); +``` + +## Property Default Values + +A value given to a property will be a default value for all objects created by the constructor: + +```javascript +function Person(first, last, age, eyecolor) { + this.firstName = first; + this.lastName = last; + this.age = age; + this.eyeColor = eyecolor; + this.nationality = "English"; +} +``` + +### Adding a Property to an Object + +Adding a property to a created object is easy: + +```javascript +myFather.nationality = "English"; +``` + +:::info Note + +> The property will be added to `myFather`. Not to any other Person objects. + +::: +### Adding a Property to a Constructor + +You cannot add a new property directly to an object constructor. To add a new property, you must add it to the constructor function prototype: + +```javascript +Person.prototype.nationality = "English"; +``` + +## Adding a Method to a Constructor + +You cannot add a new method directly to an object constructor function. This code will produce a TypeError: + +```javascript +Person.changeName = function (name) { + this.lastName = name; +} + +myMother.changeName("Doe"); +// TypeError: myMother.changeName is not a function +``` + +## Built-in JavaScript Constructors + +JavaScript has built-in constructors for all native objects: + +```javascript +new Object(); // A new Object object +new Array(); // A new Array object +new Map(); // A new Map object +new Set(); // A new Set object +new Date(); // A new Date object +new RegExp(); // A new RegExp object +new Function(); // A new Function object +``` + +## Best Practices + +- Use object literals `{}` instead of `new Object()`. +- Use array literals `[]` instead of `new Array()`. +- Use pattern literals `/()/` instead of `new RegExp()`. +- Use function expressions `() {}` instead of `new Function()`. + +### Examples + +```javascript +""; // primitive string +0; // primitive number +false; // primitive boolean + +{}; // object object +[]; // array object +/()/; // regexp object +function(){}; // function +``` + +### Creating Another Person Object + +```javascript +const mySelf = new Person("Johnny", "Rally", 22, "green"); +``` + +![JavaScript Constructors](https://miro.medium.com/v2/resize:fit:804/1*oREMGa3m7L4j1DzdNJc6GA.jpeg) + +## Constructor Functions in Detail + +### Constructor + +A constructor is a function that initializes an object. In JavaScript, constructors are more similar to normal Java constructors. + +### Object Constructor + +In JavaScript, there is a special constructor function known as `Object()` that is used to create and initialize an object. The return value of the `Object()` constructor is assigned to a variable. The variable contains a reference to the new object. We need an object constructor to create an object “type” that can be used multiple times without redefining the object every time. + +#Example + +```javascript +class Car { + constructor(brand, model, year) { + this.brand = brand; + this.model = model; + this.year = year; + } +} +``` + +In this example, `Car` is the class name, and `brand`, `model`, and `year` are the parameters of the constructor. +### Instantiating an Object Constructor + +There are two ways to instantiate an object constructor: + +1. + ```javascript + var object_name = new Object(); + var object_name = new Object("java", "JavaScript", "C#"); + ``` +2. + ```javascript + var object_name = { }; + ``` + +In the first method, the object is created by using the `new` keyword like in normal OOP languages, and `"Java"`, `"JavaScript"`, `"C#"` are the arguments passed when the constructor is invoked. In the second method, the object is created using curly braces `{ }`. + +### Assigning Properties to the Objects + +There are two ways to assign properties to objects: + +#### Using Dot (.) Operator + +```javascript +objectName.propertyName = value; +``` + +#### Using Bracket Notation + +```javascript +objectName['propertyName'] = value; +``` + +#### Example 1: Using `new` Keyword and Dot Operator + +```javascript +// Creating object using "new" keyword +var myObject = new Object(); + +// Assigning properties to the object using dot (.) operator +myObject.subject = "JavaScript"; +myObject.author = "John Doe"; + +console.log("Subject: " + myObject.subject); +console.log("Author: " + myObject.author); +``` +**Output:** +``` +Subject: JavaScript +Author: John Doe +``` + +#### Example 2: Using Curly Braces and Bracket Notation + +```javascript +// Creating an object using "{ }" bracket +var myObject = { }; + +// Assigning properties to the object using bracket notation +myObject['subject'] = "JavaScript"; +myObject['author'] = "Jane Smith"; + +console.log("Subject: " + myObject.subject); +console.log("Author: " + myObject.author); +``` +**Output:** +``` +Subject: JavaScript +Author: Jane Smith +``` + +#### Example 3: Using Function with Object Constructor + +```javascript +// Creating object +var myObject = new Object(); + +// Assigning properties to the object +myObject.subject = "JavaScript"; +myObject.author = "James Brown"; + +// Use function() +myObject.displayInfo = function () { + return (myObject.subject + " " + myObject.author); +}; + +console.log("Subject: " + myObject.subject); +console.log("Author: " + myObject.author); + +// Call function with object constructor +console.log("Adding the strings: " + myObject.displayInfo()); +``` +**Output:** +``` +Subject: JavaScript +Author: James Brown +Adding the strings: JavaScript James Brown +``` + +#### Example: Another Way to Create a Function Using Function Name + +```javascript +// Creating object using "{ }" bracket +var myObject = { }; + +// Assigning properties to the object +myObject.subject = "JavaScript"; +myObject.author = "Jessica Green"; + +// Use function() +myObject.displayInfo = add; + +// Declare function add() +function add() { + return (myObject.subject + " " + myObject.author); +}; + +console.log("Subject: " + myObject.subject); +console.log("Author: " + myObject.author); + +// Call function with object constructor +console.log("Adding the strings: " + myObject.displayInfo()); +``` +**Output:** +``` +Subject: JavaScript +Author: Jessica Green +Adding the strings: JavaScript Jessica Green +``` +## Conclusion + +Object constructor functions in JavaScript provide a powerful way to create and manage objects of the same type. By following best practices, such as using prototypes and understanding the limitations of constructors, you can write more efficient and maintainable code. \ No newline at end of file diff --git a/docs/javascript/web-apis.md b/docs/javascript/web-apis.md new file mode 100644 index 000000000..75e1ac7f3 --- /dev/null +++ b/docs/javascript/web-apis.md @@ -0,0 +1,132 @@ +--- +id: Web-APIs +title: Client-side Web APIs +sidebar_label: Web APIs +sidebar_position: 30 +tags : [JavaScript,APIs, Web-APIs , client-side Apis , javascript apis , audio apis, apis tutorial ] +description: "this tutorial shows how to create a web apis for clients and how to use it with example of audio APIs." +--- +# Introduction to Web APIs + +Web APIs are a powerful feature in modern web development that allow developers to perform complex tasks with simpler syntax. This guide provides an overview of what APIs are, how they work, their uses, and how to use them in your code. + +## Prerequisites +A basic understanding of HTML, CSS, and JavaScript basics (see first steps, building blocks, JavaScript objects). + +## Objective +To gain familiarity with APIs, understand their capabilities, and learn how to integrate them into your code. + +## What are APIs? + +Application Programming Interfaces (APIs) are constructs provided in programming languages that allow developers to create complex functionality more easily. They abstract complex code away from the developer, providing simpler syntax to achieve the same tasks. + +**Real-world Example:** +Think of the electricity supply in your house. To use an appliance, you plug it into a socket instead of wiring it directly to the power supply. Similarly, APIs provide a higher-level interface to interact with complex systems. + +![Plug Socket Example](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction/plug-socket.png) + +If you want to program 3D graphics, it's easier to use an API written in a high-level language like JavaScript rather than directly writing low-level code that controls the computer's GPU. + +## APIs in Client-side JavaScript + +Client-side JavaScript has many APIs available that are built on top of the core JavaScript language, providing extra functionality. + +### Browser APIs +These are built into your web browser and can expose data from the browser and the computer environment. For example, the Web Audio API allows you to manipulate audio in the browser. + +### Third-party APIs +These are not built into the browser by default and usually need to be retrieved from the web. For example, the Google Maps API allows you to display interactive maps on your website. + +![Browser Example](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction/browser.png) + +## Relationship between JavaScript, APIs, and Other JavaScript Tools + +### JavaScript +A high-level scripting language built into browsers for implementing functionality on web pages/apps. JavaScript is also available in other environments, such as Node.js. + +### Browser APIs +Constructs built into the browser that allow for easier implementation of functionality. + +### Third-party APIs +Constructs built into third-party platforms (e.g., Facebook) that allow you to use some of their functionality in your web pages. + +### JavaScript Libraries +JavaScript files containing custom functions to speed up or enable writing common functionality (e.g., jQuery, React). + +### JavaScript Frameworks +Packages of HTML, CSS, JavaScript, and other technologies for writing entire web applications (e.g., Angular, Ember). Frameworks differ from libraries in that they call the developer's code, whereas developers call library methods. + +## What Can APIs Do? + +There are many APIs available in modern browsers for various tasks. Common categories include: +![Working of APIs](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data/traditional-loading.svg) + +### Manipulating Documents +APIs like the DOM (Document Object Model) allow manipulation of HTML and CSS, creating dynamic web pages. + +### Fetching Data +APIs like the Fetch API and XMLHttpRequest allow fetching data from servers to update parts of a webpage without reloading the entire page. + +### Drawing and Manipulating Graphics +APIs like Canvas and WebGL allow creating 2D and 3D graphics programmatically. + +### Audio and Video +APIs like HTMLMediaElement, Web Audio API, and WebRTC allow manipulation of multimedia, such as playing audio and video or handling web conferencing. + +### Device APIs +APIs like Geolocation allow interaction with device hardware, such as accessing the GPS. + +### Client-side Storage +APIs like Web Storage and IndexedDB allow storing data on the client-side for offline functionality. + +### Common Third-party APIs +- **Map APIs**: Google Maps API, Mapquest +- **Social Media APIs**: Facebook API, Twitter API, Telegram API +- **Video and Audio APIs**: YouTube API, Twilio API +- **Commenting Systems**: Disqus API +- **Automation APIs**: IFTTT API + +## How Do APIs Work? + +### Based on Objects +APIs are typically based on JavaScript objects, which serve as containers for the data and functionality the API provides. + +### Using Events +APIs often use events to handle changes in state. Event handlers can be used to execute code in response to these events. + +**Example: Web Audio API** +```javascript +const AudioContext = window.AudioContext || window.webkitAudioContext; +const audioCtx = new AudioContext(); + +const audioElement = document.querySelector("audio"); +const playBtn = document.querySelector("button"); +const volumeSlider = document.querySelector(".volume"); + +const audioSource = audioCtx.createMediaElementSource(audioElement); + +playBtn.addEventListener("click", () => { + if (audioCtx.state === "suspended") { + audioCtx.resume(); + } + + if (playBtn.getAttribute("class") === "paused") { + audioElement.play(); + playBtn.setAttribute("class", "playing"); + playBtn.textContent = "Pause"; + } else if (playBtn.getAttribute("class") === "playing") { + audioElement.pause(); + playBtn.setAttribute("class", "paused"); + playBtn.textContent = "Play"; + } +}); + +audioElement.addEventListener("ended", () => { + playBtn.setAttribute("class", "paused"); + playBtn.textContent = "Play"; +}); +``` + +## Summary + +You should now have a good understanding of what APIs are, how they work, and how to use them in your JavaScript code. You can now explore specific APIs and start integrating them into your projects. Next, we'll look at manipulating documents with the Document Object Model (DOM). \ No newline at end of file