From daebdb32305ba8a25bc25618f5d1a35f6c19a1f7 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 3 Oct 2025 21:18:24 +0530 Subject: [PATCH 1/3] Added Js Docs --- docs/javascript/_category_.json | 8 + .../all-about-variables/_category_.json | 8 + .../all-about-variables/hoisting.mdx | 144 +++++ .../variable-declarations.mdx | 187 +++++++ .../variable-naming-rules.mdx | 238 ++++++++ .../all-about-variables/variable-scopes.mdx | 176 ++++++ docs/javascript/data-types/_category_.json | 8 + .../non-primitive-types/_category_.json | 8 + .../object/_category_.json | 8 + .../object/creating-objects.mdx | 271 +++++++++ .../non-primitive-types/object/intro.mdx | 86 +++ .../primitive-types/_category_.json | 8 + .../data-types/primitive-types/bigint.mdx | 127 +++++ .../data-types/primitive-types/boolean.mdx | 156 ++++++ .../data-types/primitive-types/null.mdx | 146 +++++ .../data-types/primitive-types/number.mdx | 364 ++++++++++++ .../data-types/primitive-types/string.mdx | 161 ++++++ .../data-types/primitive-types/symbol.mdx | 132 +++++ .../data-types/primitive-types/undefined.mdx | 116 ++++ .../_category_.json | 8 + .../history-of-javascript.mdx | 55 ++ .../how-to-run-javascript.mdx | 230 ++++++++ .../introduction-to-javascript/image.png | Bin 0 -> 13822 bytes .../javascript-versions.mdx | 526 ++++++++++++++++++ .../introduction-to-javascript/what-is-js.mdx | 73 +++ 25 files changed, 3244 insertions(+) create mode 100644 docs/javascript/_category_.json create mode 100644 docs/javascript/all-about-variables/_category_.json create mode 100644 docs/javascript/all-about-variables/hoisting.mdx create mode 100644 docs/javascript/all-about-variables/variable-declarations.mdx create mode 100644 docs/javascript/all-about-variables/variable-naming-rules.mdx create mode 100644 docs/javascript/all-about-variables/variable-scopes.mdx create mode 100644 docs/javascript/data-types/_category_.json create mode 100644 docs/javascript/data-types/non-primitive-types/_category_.json create mode 100644 docs/javascript/data-types/non-primitive-types/object/_category_.json create mode 100644 docs/javascript/data-types/non-primitive-types/object/creating-objects.mdx create mode 100644 docs/javascript/data-types/non-primitive-types/object/intro.mdx create mode 100644 docs/javascript/data-types/primitive-types/_category_.json create mode 100644 docs/javascript/data-types/primitive-types/bigint.mdx create mode 100644 docs/javascript/data-types/primitive-types/boolean.mdx create mode 100644 docs/javascript/data-types/primitive-types/null.mdx create mode 100644 docs/javascript/data-types/primitive-types/number.mdx create mode 100644 docs/javascript/data-types/primitive-types/string.mdx create mode 100644 docs/javascript/data-types/primitive-types/symbol.mdx create mode 100644 docs/javascript/data-types/primitive-types/undefined.mdx create mode 100644 docs/javascript/introduction-to-javascript/_category_.json create mode 100644 docs/javascript/introduction-to-javascript/history-of-javascript.mdx create mode 100644 docs/javascript/introduction-to-javascript/how-to-run-javascript.mdx create mode 100644 docs/javascript/introduction-to-javascript/image.png create mode 100644 docs/javascript/introduction-to-javascript/javascript-versions.mdx create mode 100644 docs/javascript/introduction-to-javascript/what-is-js.mdx diff --git a/docs/javascript/_category_.json b/docs/javascript/_category_.json new file mode 100644 index 0000000..ccfdd2f --- /dev/null +++ b/docs/javascript/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "JavaScript", + "position": 4, + "link": { + "type": "generated-index", + "description": "JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. In this tutorial, you'll learn the basics of JavaScript and how to use it to create interactive web experiences." + } +} diff --git a/docs/javascript/all-about-variables/_category_.json b/docs/javascript/all-about-variables/_category_.json new file mode 100644 index 0000000..2167a5a --- /dev/null +++ b/docs/javascript/all-about-variables/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "All About Variables", + "position": 2, + "link": { + "type": "generated-index", + "description": "In this tutorial, you'll learn what is a variable, how to declare a variable, how to assign a value to a variable, and how to use variables in JavaScript." + } +} diff --git a/docs/javascript/all-about-variables/hoisting.mdx b/docs/javascript/all-about-variables/hoisting.mdx new file mode 100644 index 0000000..b62af59 --- /dev/null +++ b/docs/javascript/all-about-variables/hoisting.mdx @@ -0,0 +1,144 @@ +--- +id: hoisting-in-javascript +title: Hoisting in JavaScript +sidebar_label: Hoisting +sidebar_position: 2 +tags: [javascript, hoisting, variable hoisting] +description: "Learn about hoisting in JavaScript and how it affects variable declarations and function definitions." +hide_table_of_contents: true +--- + +Hoisting is a unique feature of JavaScript that allows you to access variables and functions before they are declared in your code. This behavior can be surprising if you're not familiar with it, so understanding how hoisting works is essential for writing reliable JavaScript code. + +In this tutorial, we'll explore what hoisting is, how it works in JavaScript, and how it affects variable declarations and function definitions. + + +
+ +## What Is Hoisting? + +Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can access variables and functions before they are declared in your code, as if they had been "hoisted" to the top of the scope. + +It's important to note that only the declarations are hoisted, not the initializations. This means that the variable or function is available for use, but its value is `undefined` until the assignment is encountered in the code. + +## How Does Hoisting Work? + +### Hoisting with Variables + +When it comes to variables, hoisting behaves differently depending on whether the variable is declared using `var`, `let`, or `const`. + +**1. Variables Declared with `var`** + +Variables declared with `var` are hoisted to the top of their containing function or global scope. This means that you can access the variable before it is declared in the code, but its value will be `undefined` until it is assigned a value. + +**Example:** + +```javascript title="app.js" +console.log(myVar); // Output: undefined +var myVar = "Hello, World!"; +console.log(myVar); // Output: Hello, World! +``` + +In this example, the variable `myVar` is hoisted to the top of the scope, so the first `console.log` statement outputs `undefined`. The value of `myVar` is assigned later in the code, so the second `console.log` statement outputs the actual value of the variable. + +**2. Variables Declared with `let` and `const`** + +Variables declared with `let` and `const` are also hoisted to the top of their containing block, but they are not initialized until the actual declaration is encountered in the code. This means that you cannot access the variable before it is declared. + +:::note Note +Variables declared with `let` and `const` are in a "temporal dead zone" **(TDZ)** until they are initialized. Accessing them before the declaration results in a `ReferenceError`. +::: + +**Example with `let`:** + +```javascript title="app.js" +console.log(myVar); // Throws a ReferenceError +let myVar = "Hello, World!"; +console.log(myVar); // Output: Hello, World! +``` + +**Example with `const`:** + +```javascript title="app.js" +console.log(myVar); // Throws a ReferenceError +const myVar = "Hello, World!"; +console.log(myVar); // Output: Hello, World! +``` + +In both examples, trying to access the variable `myVar` before its declaration results in a `ReferenceError`. This is because variables declared with `let` and `const` are not initialized until the actual declaration is encountered in the code. + + +
+ +### Hoisting with Functions + +Hoisting behaves differently for function declarations and function expressions. + +**1. Function Declarations** + +Function declarations are hoisted to the top of their containing scope, similar to variables declared with `var`. This means that you can call the function before it is declared in the code. + +**Example:** + +```javascript title="app.js" +sayHello(); // Output: Hello, World! + +function sayHello() { + console.log("Hello, World!"); +} +``` + +In this example, the function `sayHello` is hoisted to the top of the scope, so you can call it before its actual declaration in the code. + +**2. Function Expressions** + +Function expressions are not hoisted in the same way as function declarations. Only the variable declaration is hoisted, not the function assignment. + +**Example:** + +```javascript title="app.js" +sayHello(); // Throws a TypeError + +var sayHello = function () { + console.log("Hello, World!"); +}; +``` + +In this example, the variable `sayHello` is hoisted to the top of the scope, but the function assignment is not. Trying to call `sayHello` before the function assignment results in a `TypeError`. + + +
+ +### Summary of Hoisting Behavior + +Here's a summary of how hoisting works in JavaScript: + +- Variables declared with `var` are hoisted to the top of their containing function or global scope. They are accessible before they are declared, but their value is `undefined` until the assignment is encountered. +- Variables declared with `let` and `const` are hoisted to the top of their containing block but are not initialized until the actual declaration is encountered. Accessing them before the declaration results in a `ReferenceError`. They are in the "temporal dead zone" until they are initialized. +- Function declarations are hoisted to the top of their containing scope, so you can call them before they are declared in the code. +- Function expressions are not hoisted in the same way as function declarations. Only the variable declaration is hoisted, not the function assignment. +- Hoisting can lead to unexpected behavior if you're not aware of how it works. It's important to understand hoisting to write reliable and predictable JavaScript code. + +By understanding how hoisting works, you can avoid common pitfalls and write more robust JavaScript code. + + +
+ +:::tip + +To avoid confusion and potential issues related to hoisting, it's a good practice to declare your variables and functions at the beginning of their containing scope. This makes your code more readable and predictable. + +**Remember:** + +- Use `let` and `const` for variable declarations to avoid hoisting-related bugs. +- Declare functions before calling them to ensure they are hoisted correctly. +- Be mindful of the TDZ when using `let` and `const` to prevent `ReferenceError` issues. +- Write clean and readable code by declaring variables and functions at the beginning of their containing scope. +- Take advantage of function declaration hoisting to organize your code in a way that is logical and easy to follow. + +Hoisting can feel like magic, but understanding how it works will help you write better JavaScript code. +::: + +## Conclusion + +Hoisting is a unique feature of JavaScript that allows you to access variables and functions before they are declared in your code. By hoisting declarations to the top of their containing scope, JavaScript enables you to write code that might seem out of order but still works as expected. \ No newline at end of file diff --git a/docs/javascript/all-about-variables/variable-declarations.mdx b/docs/javascript/all-about-variables/variable-declarations.mdx new file mode 100644 index 0000000..83105a6 --- /dev/null +++ b/docs/javascript/all-about-variables/variable-declarations.mdx @@ -0,0 +1,187 @@ +--- +id: variable-declarations +title: Variable Declarations +sidebar_label: Variable Declarations +sidebar_position: 1 +tags: [javascript, variables, variable declarations, var, let, const] +description: "Learn how to declare variables in JavaScript using the var, let, and const keywords." +hide_table_of_contents: true +--- + +Variables are an essential part of any programming language, allowing you to store and manipulate data in your code. In JavaScript, variables are declared using the `var`, `let`, or `const` keywords. Each of these keywords has its own characteristics and best practices for usage. In this tutorial, we'll explore how to declare variables in JavaScript and discuss the differences between `var`, `let`, and `const`. + + +
+ +## What Are Variables? + +Variables are named containers that store data values in memory. They allow you to reference and manipulate data throughout your code. In JavaScript, variables can hold various types of data, such as numbers, strings, objects, arrays, functions, and more. You can assign a value to a variable using the assignment operator (`=`) and update the value as needed. + +:::note Better Understanding +Think of variables as containers that hold data. Just like a box where you can store items, a variable holds a piece of information that you can use and modify throughout your program. +::: + +**Example:** + +Imagine you're working on a to-do list app. You might need to store the user's name, the tasks they want to complete, and the status of each task. Variables allow you to store these pieces of information: + + ```javascript title="app.js" + // Declare variables to store user information + let userName = "Ajay"; + + // Declare variables to store tasks + let task = "Complete JavaScript tutorial"; + + // Declare variables to store task status + let isTaskCompleted = false; + ``` + +In this example: + +- The `userName` variable stores the user's name as a string. +- The `task` variable stores the task description as a string. +- The `isTaskCompleted` variable stores the completion status of the task as a boolean value. +- You can update these variables as needed throughout your program. + +Now that you understand the concept of variables, let's explore how to declare them using the `var`, `let`, and `const` keywords. + + +
+ +## Declaring Variables with `var`, `let`, and `const` + +In JavaScript, you can declare variables using the `var`, `let`, or `const` keywords. Each keyword has its own scope, hoisting behavior, and mutability characteristics. Let's examine the differences between `var`, `let`, and `const` and when to use each one. + +### 1. The `var` Keyword + +The `var` keyword was the original way to declare variables in JavaScript. Variables declared with `var` have function-level scope, meaning they are accessible within the function in which they are defined. If a variable is declared outside a function, it becomes a global variable. + +:::note Note +Before ES6 (ECMAScript 2015), `var` was the only way to declare variables in JavaScript. However, `var` has some peculiar behaviors that can lead to bugs if not used carefully. +::: + +**Syntax:** + +```javascript title="app.js" +var variableName = value; +``` + +**Example:** + +```javascript title="app.js" +var age = 25; +console.log(age); // Outputs: 25 +``` + +**Key Characteristics of `var`:** + +- **Function Scope:** Variables declared with `var` are function-scoped. They are accessible within the function in which they are defined. +- **Hoisting:** Variables declared with `var` are hoisted to the top of their function or global scope. This means you can access the variable before it is declared. +- **Re-declaration:** Variables declared with `var` can be reassigned and updated throughout the program. You can also redeclare a variable without any errors. + +**Example of Hoisting with `var`:** + +```javascript title="app.js" +console.log(name); // Outputs: undefined +var name = "Alice"; +``` + +- **Imagination:** Imagine `var` as a mischievous magician that pulls your variable declarations to the top, even if you didn’t expect it! + +### 2. The `let` Keyword + +The `let` keyword was introduced in ES6 (ECMAScript 2015) to address some of the issues associated with `var`. Variables declared with `let` have block-level scope, meaning they are accessible within the block (enclosed by curly braces) in which they are defined. This makes `let` more predictable and less error-prone than `var`. + +**Syntax:** + +```javascript title="app.js" +let variableName = value; +``` + +**Example:** + +```javascript title="app.js" +let count = 0; +console.log(count); // Outputs: 0 +``` + +**Key Characteristics of `let`:** + +- **Block Scope:** Variables declared with `let` are block-scoped. They are accessible within the block (e.g., if statement, loop, or function) in which they are defined. +- **No Hoisting:** Variables declared with `let` are not hoisted to the top of their block. You cannot access the variable before it is declared. +- **Re-declaration:** Variables declared with `let` cannot be redeclared in the same scope. Attempting to redeclare a variable with `let` will result in a syntax error. + +**Example of Block Scope with `let`:** + +```javascript title="app.js" +if (true) { + let x = 10; + console.log(x); // Outputs: 10 +} + +console.log(x); // Error: x is not defined +``` + +- **Imagination:** Imagine `let` as a security guard that only allows access to variables within its defined block, keeping things well-organized and predictable. + +### 3. The `const` Keyword + +The `const` keyword was also introduced in ES6 (ECMAScript 2015) to declare constants in JavaScript. Variables declared with `const` are block-scoped and cannot be reassigned once they are initialized. This makes `const` ideal for declaring values that should not change throughout the program. + +**Syntax:** + +```javascript title="app.js" +const variableName = value; +``` + +**Example:** + +```javascript title="app.js" +const birthYear = 2001; +console.log(birthYear); // Outputs: 2001 +``` + +**Key Characteristics of `const`:** + +- **Block Scope:** Variables declared with `const` are block-scoped, similar to `let`. +- **No Hoisting:** Variables declared with `const` are not hoisted to the top of their block. +- **Immutable:** Variables declared with `const` cannot be reassigned or updated after initialization. Attempting to reassign a `const` variable will result in a syntax error. + +**Example of Immutability with `const`:** + +```javascript title="app.js" +const PI = 3.14159; +PI = 3.14; // Error: Assignment to constant variable. +``` + +- **Imagination:** Imagine `const` as a stone tablet with an inscription that cannot be changed once it's been carved. It's a constant reminder of the value it holds. + + +
+ +## When to Use `var`, `let`, or `const`? + +Here are some guidelines on when to use `var`, `let`, or `const` in your JavaScript code: + +- Use `var` when you need variables with function-level scope or global scope. However, it's recommended to use `let` or `const` instead of `var` to avoid hoisting issues and potential bugs. +- Use `let` when you need variables with block-level scope that can be reassigned or updated. +- Use `const` when you need variables with block-level scope that should not be reassigned after initialization. This is useful for declaring constants or values that should remain unchanged. +- As a best practice, prefer using `const` for variables that do not need to be reassigned. This helps prevent accidental reassignments and makes your code more predictable. + +By understanding the differences between `var`, `let`, and `const`, you can choose the appropriate keyword based on the scope and mutability requirements of your variables. + +## Quick Comparison Table + +Here's a quick comparison of the key characteristics of `var`, `let`, and `const`: + +| No. | Feature | `var` | `let` | `const` | +| :-- | :------------- | :------------- | :---------- | :---------- | +| 1. | Scope | Function-level | Block-level | Block-level | +| 2. | Hoisting | Yes | No | No | +| 3. | Re-declaration | Allowed | Not allowed | Not allowed | +| 4. | Reassignment | Allowed | Allowed | Not allowed | +| 5. | Initialization | Optional | Optional | Required | + +## Conclusion + +In this tutorial, you learned how to declare variables in JavaScript using the `var`, `let`, and `const` keywords. Each keyword has its own scope, hoisting behavior, and mutability characteristics. By understanding the differences between `var`, `let`, and `const`, you can choose the appropriate keyword based on the requirements of your variables. \ No newline at end of file diff --git a/docs/javascript/all-about-variables/variable-naming-rules.mdx b/docs/javascript/all-about-variables/variable-naming-rules.mdx new file mode 100644 index 0000000..ebd2ba6 --- /dev/null +++ b/docs/javascript/all-about-variables/variable-naming-rules.mdx @@ -0,0 +1,238 @@ +--- +id: variable-naming-rules +title: Variable Naming Rules +sidebar_label: Variable Naming Rules +sidebar_position: 3 +tags: [javascript, variables, variable naming, naming conventions] +description: "Learn about the rules and best practices for naming variables in JavaScript, including naming conventions, reserved words, and case sensitivity." +hide_table_of_contents: true +--- + +When writing JavaScript code, it's essential to follow consistent naming conventions for variables to improve code readability and maintainability. Variable names should be descriptive, meaningful, and follow certain rules to ensure clarity and avoid conflicts. + +In this tutorial, we'll cover the essential rules for naming variables in JavaScript, along with examples and tips to help you avoid common mistakes. + + +
+ +## What Are Variables? + +Variables are named containers that store data values in memory. They allow you to reference and manipulate data throughout your code. In JavaScript, variables can hold various types of data, such as numbers, strings, objects, arrays, functions, and more. You can assign a value to a variable using the assignment operator (`=`) and update the value as needed. + +:::tip Imagination: +Imagine you have a set of boxes, each labeled with a unique name. Inside each box, you store different items (data). The name on the box is the variable name, and the item inside is the variable’s value. Just as you wouldn’t want two boxes with the same label (it would be confusing), you need to follow specific rules to ensure your variables are correctly named and easy to understand. +::: + +## Why Are Variable Names Important? + +Choosing meaningful and descriptive variable names is crucial for writing clean and maintainable code. Here are some reasons why variable names are important: + +- **Readability**: Descriptive variable names make your code easier to read and understand, especially for other developers who may work on the codebase. +- **Maintainability**: Well-named variables help you remember the purpose of each variable and make it easier to update or modify the code in the future. +- **Debugging**: Clear variable names can help you identify and fix issues in your code more quickly. +- **Avoiding Conflicts**: Properly named variables reduce the chances of naming conflicts and unintended side effects in your code. +- **Consistency**: Following a consistent naming convention across your codebase improves code consistency and makes it easier to collaborate with other developers. +- **Documentation**: Meaningful variable names serve as self-documentation, reducing the need for additional comments to explain the purpose of each variable. +- **Code Refactoring**: When refactoring your code, descriptive variable names help you understand the context and purpose of each variable, making the process smoother and less error-prone. +- **Best Practices**: Adhering to naming conventions and best practices ensures that your code is more professional, maintainable, and scalable. +- **Code Reviews**: Clear and consistent variable names facilitate code reviews and make it easier for reviewers to understand your code changes. +- **Learning**: Following naming conventions helps you learn and understand best practices in programming, improving your skills as a developer. +- **Career Growth**: Writing clean and well-structured code with meaningful variable names can enhance your reputation as a developer and open up new opportunities for career growth. +- **Code Quality**: Good variable names contribute to overall code quality, making your codebase more robust, reliable, and efficient. + +By following the rules and best practices for naming variables, you can write better code that is easier to maintain, understand, and share with others. + + +
+ +## Rules for Naming Variables + +When naming variables in JavaScript, you need to follow certain rules and conventions to ensure consistency and readability. Here are the essential rules for naming variables: + +### 1. Variable Names Must Begin with a Letter, Underscore (\_), or Dollar Sign ($) + +A variable name can start with any of these three characters: + +- **Letter**: The first character of a variable name must be a letter (a-z, A-Z) or an uppercase or lowercase letter. +- Underscore (\_): You can use an underscore as the first character of a variable name. It is commonly used to indicate a private or internal variable. +- Dollar Sign ($): While the dollar sign can be used in variable names, it is less common and not recommended due to its use in certain JavaScript libraries and frameworks. + +**Example:** + +```javascript title="app.js" +let name = "Alice"; +let _count = 10; +let $price = 25.99; +``` + +### 2. Variable Names Can Contain Letters, Numbers, Underscores, and Dollar Signs + +After the first character, variable names can include: + +- Letters (a-z, A-Z) +- Numbers (0-9) +- Underscores (\_) +- Dollar Signs ($) + +**Examples:** + +```javascript title="app.js" +let user1 = "Alice"; +let totalAmount = 150; +let _count = 42; +let $discountRate = 0.1; +``` + + +
+ +### 3. Variable Names Are Case-Sensitive + +JavaScript variable names are case-sensitive, meaning that `name`, `Name`, and `NAME` are considered different variables. It's essential to be consistent with the casing of variable names to avoid confusion and errors in your code. + +**Example:** + +```javascript title="app.js" +let firstName = "Alice"; +let FirstName = "Bob"; +let FIRSTNAME = "Charlie"; + +console.log(firstName); // Output: Alice +console.log(FirstName); // Output: Bob +console.log(FIRSTNAME); // Output: Charlie +``` + +### 4. Reserved Words Cannot Be Used as Variable Names + +JavaScript has a list of reserved keywords that cannot be used as variable names. These keywords have specific purposes in the language, such as `let`, `const`, `var`, `if`, `else`, `function`, `return`, etc. Attempting to use a reserved word as a variable name will result in a syntax error. + +**Example:** + +```javascript title="app.js" +let let = "variable"; // SyntaxError: Unexpected token 'let' + +let function = "myFunction"; // SyntaxError: Unexpected token 'function' +``` + +### 5. Variable Names Should Be Descriptive and Meaningful + +While this isn’t a strict rule, it’s a best practice to make your variable names descriptive. A good variable name should clearly indicate the data it holds. This improves code readability and makes your code easier to understand and maintain. + +**Example:** + +```javascript title="app.js" +let firstName = "Alice"; +let age = 25; +let isUserLoggedIn = true; +``` + +### 6. Avoid Single-Letter Variable Names (Except in Specific Cases) + +Single-letter variable names like `x`, `y`, or `i` can be ambiguous and should generally be avoided, except in specific contexts like loops or mathematical operations where their meaning is clear. + +**Example:** + +```javascript title="app.js" +// Avoid +let x = 10; + +// Better +let coordinateX = 10; + +// Acceptable in loops +for (let i = 0; i < 10; i++) { + console.log(i); +} +``` + + +
+ +### 7. Use CamelCase for Multi-Word Variable Names + +When a variable name consists of multiple words, it's common to use CamelCase to improve readability. In CamelCase, the first word is lowercase, and subsequent words are capitalized. This convention makes variable names easier to read and understand. + +**Example:** + +```javascript title="app.js" +let firstName = "Alice"; +let totalAmount = 150; +let isUserLoggedIn = true; +``` + +### 8. Choose Consistent Naming Conventions + +Consistency is key when naming variables in JavaScript. Pick a naming convention that works for you or your team and stick to it throughout your codebase. Whether you prefer CamelCase, snake_case, or another convention, the most important thing is to be consistent. + +**Example:** + +```javascript title="app.js" +// CamelCase +let firstName = "Alice"; +let totalAmount = 150; + +// snake_case +let first_name = "Alice"; +let total_amount = 150; +``` + +### 9. Avoid Abbreviations and Acronyms (Unless Commonly Accepted) + +While abbreviations and acronyms can save typing time, they may reduce code readability. Avoid using cryptic abbreviations unless they are widely accepted and well-known in the context of your codebase. + +**Example:** + +```javascript title="app.js" +// Avoid +let usr = "Alice"; +let amt = 150; + +// Better +let user = "Alice"; +let amount = 150; +``` + +### 10. Use Meaningful Prefixes or Suffixes for Special Variables + +For special types of variables, such as constants, private variables, or global variables, consider using meaningful prefixes or suffixes to distinguish them from regular variables. This practice helps identify the purpose and scope of each variable. + +**Example:** + +```javascript title="app.js" +// Constants +const MAX_LENGTH = 100; +const PI_VALUE = 3.14159; + +// Private variables +let _count = 10; +let _isHidden = false; + +// Global variables +let g_totalAmount = 150; +let g_userName = "Alice"; +``` + +By following these rules and best practices for naming variables in JavaScript, you can write clean, readable, and maintainable code that is easy to understand and work with. + + +
+ +:::note + +Naming variables is a fundamental aspect of writing clean and maintainable JavaScript code. By following the rules and best practices outlined in this tutorial, you can improve the readability, consistency, and quality of your codebase. Here's a quick summary of the key points covered: + +- **Start with:** A letter, underscore, or dollar sign. +- **Use:** Letters, numbers, underscores, and dollar signs in variable names. +- **Contain:** Descriptive and meaningful names. +- **Be Case-Sensitive:** Remember that variable names are case-sensitive. for example, `name`, `Name`, and `NAME` are considered different variables. +- **Avoid Reserved Words:** Do not use reserved keywords as variable names. for example, `let`, `const`, `var`, `if`, `else`, `function`, `return`, etc. +- **Be Descriptive:** Choose variable names that clearly indicate the data they hold. +- **CamelCase:** Use CamelCase for multi-word variable names. for example, `firstName`, `totalAmount`, `isUserLoggedIn`. + +By following these guidelines, you can create well-structured, readable, and maintainable JavaScript code that is easy to understand and work with. + +::: + +## Conclusion + +In this tutorial, you learned about the rules and best practices for naming variables in JavaScript. By following these guidelines, you can write clean, consistent, and readable code that is easier to maintain and understand. Remember that choosing meaningful and descriptive variable names is essential for improving code quality, readability, and maintainability. diff --git a/docs/javascript/all-about-variables/variable-scopes.mdx b/docs/javascript/all-about-variables/variable-scopes.mdx new file mode 100644 index 0000000..974e872 --- /dev/null +++ b/docs/javascript/all-about-variables/variable-scopes.mdx @@ -0,0 +1,176 @@ +--- +id: variable-scopes +title: Variable Scopes in JavaScript +sidebar_label: Variable Scopes +sidebar_position: 4 +tags: [javascript, variable, scope, global, local, block, function] +description: "Learn about variable scopes in JavaScript, including global, local, and block scopes, and how they affect variable accessibility." +hide_table_of_contents: true +--- + +Understanding variable scope in JavaScript is essential for writing effective and bug-free code. The scope of a variable determines where in your code a particular variable can be accessed or modified. Knowing how scopes work will help you prevent errors and make your code more predictable and maintainable. + +In this tutorial, we'll explore the different types of scopes in JavaScript, how they work, and how you can use them to control the accessibility of your variables. + + +
+ +## What Is Scope? + +In JavaScript, scope refers to the current context of code execution. It determines which variables and functions are accessible at a given point in your code. Think of scope as the set of rules that govern where and how variables and functions can be accessed or referenced. + +:::info Imagination: +Imagine you’re in a house with several rooms. Some items (variables) are available in all rooms (global scope), while others are only accessible in specific rooms (local scope). The doors between the rooms represent the boundaries of scope, and crossing them determines whether you can access a particular item. +::: + +## Types of Scopes in JavaScript + +JavaScript primarily has three types of scopes: + +1. [Global Scope](#1-global-scope) +2. [Local Scope (Function Scope)](#2-local-scope-function-scope) +3. [Block Scope](#3-block-scope) + +Let's look at each of these scopes in detail. + +### 1. Global Scope + +The global scope is the outermost scope in JavaScript. Variables declared outside of any function or block have global scope. These variables are accessible from anywhere in your code, regardless of the context. + +Here's an example of a variable declared in the global scope: + +```javascript title="app.js" showLineNumbers +let globalVar = "I am a global variable"; + +function accessGlobalVar() { + console.log(globalVar); // Accessible here +} + +accessGlobalVar(); // Outputs: I am a global variable + +console.log(globalVar); // Accessible here too, Outputs: I am a global variable +``` + +In the example above, the `globalVar` variable is declared outside any function, making it a global variable. It can be accessed from both the `accessGlobalVar` function and the global scope. + +Global variables are accessible from any part of your code, but they can also lead to naming conflicts and make your code harder to maintain. It's generally recommended to avoid using global variables unless necessary. + +### 2. Local Scope (Function Scope) + +Local scope refers to the scope within a function. Variables declared inside a function are local to that function and are not accessible outside of it. This is known as function scope. + +Here's an example of a variable declared in a local scope: + +```javascript title="app.js" showLineNumbers +function myFunction() { + let localVar = "I am a local variable"; + console.log(localVar); // Accessible here +} + +myFunction(); // Outputs: I am a local variable + +console.log(localVar); // Error: localVar is not defined +``` + +`localVar` is declared inside the `myFunction` function, making it a local variable. It can only be accessed within the function and not outside of it. Attempting to access `localVar` outside the function will result in a `ReferenceError`. + +Local scope helps prevent naming conflicts and allows you to encapsulate variables within specific functions, making your code more modular and easier to manage. + + +
+ +### 3. Block Scope + +Block scope refers to the scope within a block of code enclosed by curly braces `{}`. Blocks can be found within functions, loops, conditional statements, and other code structures. Variables declared with `let` and `const` inside a block are only accessible within that block. + +Here's an example of a variable declared in a block scope: + +```javascript title="app.js" showLineNumbers +if (true) { + let blockVar = "I am a block-scoped variable"; + console.log(blockVar); // Accessible here +} + +console.log(blockVar); // Error: blockVar is not defined +``` + +In the example above, `blockVar` is declared inside an `if` block, making it a block-scoped variable. It can only be accessed within the block where it's defined. Attempting to access `blockVar` outside the block will result in a `ReferenceError`. + +Block scope helps you control the visibility and lifetime of variables within specific code blocks, reducing the chances of unintended side effects and making your code more predictable. + + +
+ +## Shadowing and Variable Scope + +Shadowing occurs when a variable declared in an inner scope has the same name as a variable in an outer scope. In such cases, the inner variable "shadows" the outer variable, making the outer variable inaccessible within the inner scope. + +Here's an example of variable shadowing: + +```javascript title="app.js" showLineNumbers +let name = "Global Name"; + +function displayName() { + let name = "Local Name"; // Shadows the global variable + console.log(name); // Outputs: Local Name +} + +displayName(); + +console.log(name); // Outputs: Global Name +``` + +`name` is declared as a global variable, and another variable with the same name is declared inside the `displayName` function. The inner `name` variable shadows the global `name` variable within the function, and the global variable remains unaffected. + +Shadowing can lead to confusion and bugs if not used carefully. It's generally recommended to avoid shadowing variables with the same name to maintain code clarity and prevent unexpected behavior. + +## The `var` Keyword and Function Scope + +Before the introduction of `let` and `const` in ES6, JavaScript used the `var` keyword to declare variables. Variables declared with `var` have function scope rather than block scope. This means that `var` variables are accessible throughout the function in which they are declared, regardless of block boundaries. + +Here's an example illustrating function scope with `var`: + +```javascript title="app.js" showLineNumbers +function myFunction() { + if (true) { + var varVariable = "I am a var variable"; + } + + console.log(varVariable); // Accessible here +} + +myFunction(); // Outputs: I am a var variable + +console.log(varVariable); // Outputs: I am a var variable +``` + +In the example above, `varVariable` is declared inside an `if` block but is still accessible outside the block due to function scope. This behavior can lead to unexpected results and make it harder to reason about your code. + +It's generally recommended to use `let` and `const` instead of `var` to avoid issues related to function scope and improve code readability and maintainability. + +## The `let` and `const` Keywords and Block Scope + +The `let` and `const` keywords introduced in ES6 provide block scope for variables, making them more predictable and easier to manage. Variables declared with `let` and `const` are only accessible within the block in which they are defined, helping to prevent unintended side effects and naming conflicts. + +Here's an example illustrating block scope with `let`: + +```javascript title="app.js" showLineNumbers +if (true) { + let letVariable = "I am a let variable"; + const constVariable = "I am a const variable"; + + console.log(letVariable); // Accessible here + console.log(constVariable); // Accessible here +} + +console.log(letVariable); // Error: letVariable is not defined +console.log(constVariable); // Error: constVariable is not defined +``` + +In the example above, `letVariable` and `constVariable` are declared inside an `if` block and are only accessible within that block. Attempting to access them outside the block will result in a `ReferenceError`. + +Using `let` and `const` for variable declarations helps you write more robust and maintainable code by limiting the scope of variables to specific blocks, reducing the chances of bugs and making your code easier to understand. + +## Conclusion + +Understanding variable scopes in JavaScript is crucial for writing clean, maintainable code. By knowing how global, local, and block scopes work, you can control the visibility and accessibility of variables in your code, prevent naming conflicts, and reduce the chances of bugs. diff --git a/docs/javascript/data-types/_category_.json b/docs/javascript/data-types/_category_.json new file mode 100644 index 0000000..d99a54e --- /dev/null +++ b/docs/javascript/data-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Data Types", + "position": 3, + "link": { + "type": "generated-index", + "description": "In this tutorial, you'll learn about the different data types in JavaScript, such as string, number, boolean, null, undefined, object, and symbol." + } +} diff --git a/docs/javascript/data-types/non-primitive-types/_category_.json b/docs/javascript/data-types/non-primitive-types/_category_.json new file mode 100644 index 0000000..76d53af --- /dev/null +++ b/docs/javascript/data-types/non-primitive-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Non Primitive Types", + "position": 2, + "link": { + "type": "generated-index", + "description": "Non-primitive types are more complex data types in JavaScript. In this tutorial, you'll learn about non-primitive types in JavaScript, such as object, array, function, and more." + } +} diff --git a/docs/javascript/data-types/non-primitive-types/object/_category_.json b/docs/javascript/data-types/non-primitive-types/object/_category_.json new file mode 100644 index 0000000..943c0da --- /dev/null +++ b/docs/javascript/data-types/non-primitive-types/object/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Object", + "position": 1, + "link": { + "type": "generated-index", + "description": "Objects are complex data types in JavaScript. In this tutorial, you'll learn about objects in JavaScript, how to create objects, and how to access object properties." + } +} diff --git a/docs/javascript/data-types/non-primitive-types/object/creating-objects.mdx b/docs/javascript/data-types/non-primitive-types/object/creating-objects.mdx new file mode 100644 index 0000000..47dc23f --- /dev/null +++ b/docs/javascript/data-types/non-primitive-types/object/creating-objects.mdx @@ -0,0 +1,271 @@ +--- +id: creating-objects +title: "Creating Objects in JavaScript" +sidebar_label: "Creating Objects" +sidebar_position: 2 +tags: [javascript, data type, non-primitive type, object] +description: "Learn how to create objects in JavaScript using object literals, constructors, and classes." +hide_table_of_contents: true +--- + +In JavaScript, objects are a fundamental part of the language and are used to represent complex data structures. There are multiple ways to create objects in JavaScript, including using object literals, constructors, and classes. In this tutorial, you will learn how to create objects using these different methods. + +## Using Object Literals + +One of the simplest ways to create an object in JavaScript is by using an **object literal**. An object literal is a comma-separated list of key-value pairs enclosed in curly braces `{}`. Each key-value pair in an object literal represents a property of the object. + + +
+ +### Syntax: + +```javascript title="app.js" +let objectName = { + key1: value1, + key2: value2, + // ... +}; +``` + +### Example: + +```javascript title="app.js" +// Create an object using an object literal +let person = { + firstName: "John", + lastName: "Doe", + age: 30, + isEmployed: true, +}; + +console.log(person); +``` + +In the example above, the `person` object is created using an object literal with four properties: `firstName`, `lastName`, `age`, and `isEmployed`. Each property is separated by a comma, and the entire object is enclosed in curly braces `{}`. + +### Advantages: + +- **Simplicity:** Object literals are easy to write and understand. +- **Flexibility:** Properties can be added or removed dynamically. +- **Readability:** Object literals provide a clear structure for defining objects. + +### When to Use: + +- For creating simple objects with a fixed set of properties. +- Useful for configuration objects, static data, and small, simple objects. + + +
+ +## Using Constructors + +The `object`constructor is a built-in function that allows you to create new objects programmatically. It's more flexible than object literals but is less commonly used for creating basic objects. + +### Syntax: + +```javascript title="app.js" +let objectName = new Object(); +objectName.key1 = value1; +objectName.key2 = value2; +// ... +``` + +### Example: + +```javascript title="app.js" +// Create an object using the Object constructor +let person = new Object(); +person.firstName = "John"; +person.lastName = "Doe"; +person.age = 30; +person.isEmployed = true; + +console.log(person); +``` + +In the example above, the `person` object is created using the `Object` constructor, and properties are added to the object using dot notation. + +### Advantages: + +- **Flexibility:** You can create `objects` and then define properties dynamically. +- **Compatibility:** The `Object` constructor is well-supported and can be useful in certain contexts where object literals might not be suitable. + +### When to Use: + +- Less frequently used for creating basic objects; better suited for situations where objects need to be constructed dynamically. +- Useful when creating objects from external data sources or when the object's structure is not predefined. + + +
+ +## Constructor Functions + +In JavaScript, you can define your own **constructor functions** to create objects with a predefined structure. Constructor functions are like regular functions but are used with the `new` keyword to create instances of objects. + +### Syntax: + +```javascript title="app.js" +function ConstructorName(param1, param2, ...) { + this.key1 = param1; + this.key2 = param2; + // ... +} + +let objectName = new ConstructorName(value1, value2, ...); +``` + +### Example: + +```javascript title="app.js" +// Define a constructor function for creating Person objects +function Person(firstName, lastName, age, profession) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + this.profession = profession; +} + +// Create a new Person object using the constructor function +let person1 = new Person("Alice", "Smith", 28, "Engineer"); +let person2 = new Person("Bob", "Jones", 35, "Designer"); + +console.log(person1); +console.log(person2); +``` + +In the example above, the `Person` constructor function is defined with parameters for `firstName`, `lastName`, `age`, and `profession`. Two `Person` objects (`person1` and `person2`) are created using the constructor function. + +### Advantages: + +- **Reusability:** Constructor functions allow you to create multiple instances of objects with the same structure. +- **Encapsulation:** Constructor functions can encapsulate object creation logic and behavior. + +### When to Use: + +- When you need to create multiple objects with the same structure. +- Useful for defining custom object types with specific properties and methods. + + +
+ +## Using ES6 Classes + +With the introduction of ES6 (ECMAScript 2015), JavaScript introduced a more modern way to create objects using **classes**. Classes provide a cleaner syntax for defining object blueprints and are more similar to class-based languages like Java or C#. + +### Syntax: + +```javascript title="app.js" +class ClassName { + constructor(param1, param2, ...) { + this.key1 = param1; + this.key2 = param2; + // ... + } +} + +let objectName = new ClassName(value1, value2, ...); +``` + +### Example: + +```javascript title="app.js" +// Define a class for creating Person objects +class Person { + constructor(firstName, lastName, age, profession) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + this.profession = profession; + } +} + +// Create a new Person object using the class +let person1 = new Person("Alice", "Smith", 28, "Engineer"); +let person2 = new Person("Bob", "Jones", 35, "Designer"); + +console.log(person1); +console.log(person2); +``` + +In the example above, the `Person` class is defined with a constructor method that initializes the object's properties. Two `Person` objects (`person1` and `person2`) are created using the class. + +### Advantages: + +- **Simplicity:** Classes provide a cleaner and more structured way to define object blueprints. +- **Inheritance:** Classes support inheritance, allowing you to create subclasses with shared properties and methods. +- **Encapsulation:** Classes encapsulate object creation logic and behavior. +- **Modern Syntax:** Classes are a more modern approach to object-oriented programming in JavaScript. +- **Constructor Method:** The `constructor` method is used to initialize object properties. + +### When to Use: + +- When working with modern JavaScript applications or frameworks. +- Useful for defining object blueprints with a clear structure and behavior. +- Supports inheritance and other object-oriented programming concepts. + + +
+ +## `Object.create()` Method + +The `Object.create()` method is another way to create objects in JavaScript. It allows you to create a new object with a specified prototype object. This method is useful when you want to create objects that inherit properties from a shared prototype. + +### Syntax: + +```javascript title="app.js" +let objectName = Object.create(prototypeObject, { + key1: { + value: value1, + writable: true, + enumerable: true, + configurable: true, + }, + key2: { + value: value2, + writable: true, + enumerable: true, + configurable: true, + }, + // ... +}); +``` + +### Example: + +```javascript title="app.js" +// Create a prototype object +let personPrototype = { + greet: function () { + return `Hello, my name is ${this.firstName} ${this.lastName}.`; + }, +}; + +// Create a new object using the prototype +let person = Object.create(personPrototype, { + firstName: { value: "John" }, + lastName: { value: "Doe" }, + age: { value: 30 }, +}); + +console.log(person.greet()); +``` + +In the example above, the `personPrototype` object defines a `greet` method that returns a greeting message. A new `person` object is created using `Object.create()` with the `personPrototype` as the prototype object. + +### Advantages: + +- **Prototype Inheritance:** Objects created with `Object.create()` inherit properties and methods from a shared prototype. +- **Flexible Property Definition:** Properties can be defined with configurable options like `writable`, `enumerable`, and `configurable`. +- **Separation of Concerns:** Allows you to separate object creation from property definition. +- **Prototype-Based Programming:** Useful for prototype-based programming in JavaScript. + +### When to Use: + +- When you need to create objects that inherit properties from a shared prototype. +- Useful for prototype-based programming and separating object creation from property definition. +- Provides more control over property configuration and inheritance. +- Can be used to implement inheritance patterns in JavaScript. + +## Conclusion + +In this tutorial, you learned how to create objects in JavaScript using object literals, constructors, classes, and the `Object.create()` method. Each method has its advantages and use cases, depending on the complexity and structure of the objects you need to create. Understanding these different methods will help you work with objects effectively in JavaScript. \ No newline at end of file diff --git a/docs/javascript/data-types/non-primitive-types/object/intro.mdx b/docs/javascript/data-types/non-primitive-types/object/intro.mdx new file mode 100644 index 0000000..498b626 --- /dev/null +++ b/docs/javascript/data-types/non-primitive-types/object/intro.mdx @@ -0,0 +1,86 @@ +--- +id: introduction-to-objects +title: "Introduction to Objects in JavaScript" +sidebar_label: "Introduction to Objects" +sidebar_position: 1 +tags: [javascript, data type, non-primitive type, object] +description: "Learn about objects in JavaScript, how to create objects, and common operations with objects." +hide_table_of_contents: true +--- + +In this tutorial, you will learn about objects in JavaScript, how to create objects, and common operations with objects. + + +
+ +## What is an Object in JavaScript? + +In JavaScript, an **object** is a non-primitive data type that represents a collection of key-value pairs. Objects are used to store and organize data in a structured way. Each key-value pair in an object is called a property, where the key is a string (or symbol) that identifies the property, and the value can be any data type, including other objects. + +Objects in JavaScript are dynamic, meaning you can add, update, or delete properties from an object at any time. Objects are commonly used to represent complex data structures, such as user profiles, products, or configurations. + +Objects in JavaScript are fundamental to how the language works. Many built-in features and APIs in JavaScript are implemented using objects, making them an essential part of the language. + +**Example of a Basic Object:** + +Here is an example of a basic object in JavaScript: + +```javascript title="app.js" +// Create an object representing a person +let person = { + firstName: "John", + lastName: "Doe", + age: 30, + isEmployed: true, +}; + +console.log(person); +``` + +In this example, `person` is an object with four properties: + +- `firstName` is a property with the value `"John"`. +- `lastName` is a property with the value `"Doe"`. +- `age` is a property with the value `30`. +- `isEmployed` is a property with the value `true`. + +Each property is composed of a key (e.g., `firstName`) and a value (e.g., `"John"`). The properties are separated by commas, and the entire object is enclosed in curly braces `{}`. + + +
+ +## Importance of Objects in JavaScript + +Objects are everywhere in JavaScript. They are used to create, manipulate, and manage complex data structures. Whether you're handling user information, managing configurations, or even dealing with the Document Object Model (DOM) in a web page, objects are integral. + +### Key Features of Objects + +- **Dynamic nature:** Objects can have properties added, modified, or removed dynamically at runtime. +- **Reference type:** Objects are reference types, meaning that when you assign an object to another variable, you're assigning a reference to the same object, not a copy of it. +- **Collection of key-value pairs:** Objects store data in key-value pairs, making them highly flexible for modeling real-world entities. + + +
+ +## Real-World Example + +Consider an online shopping cart. You might represent a shopping cart as an object where each property is an item, and the value is the quantity of that item: + +```javascript title="app.js" +// Create a shopping cart object +let shoppingCart = { + apple: 2, + banana: 3, + orange: 1, +}; + +console.log(shoppingCart); +``` + +In this example, `shoppingCart` is an object representing a shopping cart with three items: `apple`, `banana`, and `orange`. The quantity of each item is stored as the value of the corresponding property. + +Objects are versatile and can be used to model a wide range of real-world entities and data structures. + +## Conclusion + +In this tutorial, you learned about objects in JavaScript, how to create objects, and the importance of objects in JavaScript programming. Objects are a fundamental part of JavaScript and are used to represent complex data structures in a flexible and dynamic way. \ No newline at end of file diff --git a/docs/javascript/data-types/primitive-types/_category_.json b/docs/javascript/data-types/primitive-types/_category_.json new file mode 100644 index 0000000..25c38b8 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Primitive Types", + "position": 1, + "link": { + "type": "generated-index", + "description": "Primitive types are the most basic data types in JavaScript. In this tutorial, you'll learn about the primitive types in JavaScript, such as string, number, boolean, null, undefined, and symbol." + } +} diff --git a/docs/javascript/data-types/primitive-types/bigint.mdx b/docs/javascript/data-types/primitive-types/bigint.mdx new file mode 100644 index 0000000..0435040 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/bigint.mdx @@ -0,0 +1,127 @@ +--- +id: bigint +title: BigInt Data Type in JavaScript +sidebar_label: BigInt +sidebar_position: 4 +tags: [javascript, data type, primitive type, bigint] +description: "Learn about the BigInt data type in JavaScript, how to create BigInt values, and common operations with BigInt values." +hide_table_of_contents: true +--- + +In JavaScript, `BigInt` is a built-in object that provides a way to represent whole numbers larger than `Number.MAX_SAFE_INTEGER`. It allows you to work with integers of arbitrary length, overcoming the limitations of the `Number` data type. + + +
+ +## Creating BigInt Values + +You can create `BigInt` values in JavaScript by appending the letter `n` to an integer literal or by using the `BigInt()` constructor. Here are examples of both methods: + +### Using Integer Literals + +You can create `BigInt` values using integer literals by appending the letter `n` to the end of the number. This tells JavaScript to treat the number as a `BigInt` value: + +```javascript title="app.js" +let bigIntLiteral = 1234567890123456789012345678901234567890n; + +console.log(bigIntLiteral); // Output: 1234567890123456789012345678901234567890n +``` + +### Using the `BigInt()` Constructor + +You can also create `BigInt` values using the `BigInt()` constructor. The `BigInt()` function converts a value to a `BigInt` number: + +```javascript title="app.js" +let bigIntConstructor = BigInt("1234567890123456789012345678901234567890"); + +console.log(bigIntConstructor); // Output: 1234567890123456789012345678901234567890n +``` + + +
+ +## Common Operations with BigInt Values + +### Arithmetic Operations + +You can perform arithmetic operations on `BigInt` values just like you would with regular numbers. The following operators are supported for `BigInt` values: + +- Addition (`+`) +- Subtraction (`-`) +- Multiplication (`*`) +- Division (`/`) +- Modulus (`%`) +- Exponentiation (`**`) +- Bitwise operations (`&`, `|`, `^`, `~`, `<<`, `>>`, `>>>`) +- Comparison operators (`<`, `>`, `<=`, `>=`, `==`, `===`, `!=`, `!==`) +- Logical operators (`&&`, `||`, `!`) +- Increment (`++`) and decrement (`--`) +- Assignment operators (`+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, `>>>=`) + +Here's an example of performing arithmetic operations with `BigInt` values: + +```javascript title="app.js" +let a = 1234567890123456789012345678901234567890n; +let b = 9876543210987654321098765432109876543210n; + +let sum = a + b; +let difference = a - b; +let product = a * b; +let quotient = a / b; +let remainder = a % b; + +console.log(sum); // Output: 11111111101111111110111111110111111111100n +console.log(difference); // Output: -8641975310864197531086419753086419755320n +console.log(product); // Output: 12193263111263526912193263111263526912100n +console.log(quotient); // Output: 0n +console.log(remainder); // Output: 1234567890123456789012345678901234567890n +``` + +### Comparison Operations + +You can compare `BigInt` values using comparison operators like `<`, `>`, `<=`, `>=`, `==`, `===`, `!=`, and `!==`. Here's an example of comparing `BigInt` values: + +```javascript title="app.js" +let a = 1234567890123456789012345678901234567890n; +let b = 9876543210987654321098765432109876543210n; + +console.log(a < b); // Output: true +console.log(a === b); // Output: false +``` + +### Converting to Number + +You can convert a `BigInt` value to a regular number using the `Number()` function. Be aware that converting a `BigInt` value to a number may result in a loss of precision if the `BigInt` value is larger than `Number.MAX_SAFE_INTEGER`: + +```javascript title="app.js" +let bigIntValue = 1234567890123456789012345678901234567890n; +let numberValue = Number(bigIntValue); + +console.log(numberValue); // Output: 1.2345678901234568e+39 +``` + +### Converting to String + +You can convert a `BigInt` value to a string using the `toString()` method. The `toString()` method converts a `BigInt` value to a string representation: + +```javascript title="app.js" +let bigIntValue = 1234567890123456789012345678901234567890n; +let stringValue = bigIntValue.toString(); + +console.log(stringValue); // Output: 1234567890123456789012345678901234567890 +``` + + +
+ +:::tip ES2020 (ECMAScript 2020) + +The `BigInt` data type was introduced in ECMAScript 2020 (ES11) to provide a way to work with arbitrarily large integers in JavaScript. + +**Browser Support:** The `BigInt` data type is supported in modern browsers, including Chrome, Firefox, Safari, and Edge. Internet Explorer does not support `BigInt`. + +::: + +## Conclusion + +The `BigInt` data type in JavaScript provides a way to work with integers of arbitrary length, overcoming the limitations of the `Number` data type for very large numbers. By using `BigInt` values, you can perform precise integer arithmetic and handle calculations that exceed the maximum safe integer value in JavaScript. \ No newline at end of file diff --git a/docs/javascript/data-types/primitive-types/boolean.mdx b/docs/javascript/data-types/primitive-types/boolean.mdx new file mode 100644 index 0000000..8d25aa0 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/boolean.mdx @@ -0,0 +1,156 @@ +--- +id: boolean +title: Boolean Data Type in JavaScript +sidebar_label: Boolean +sidebar_position: 5 +tags: [javascript, data type, primitive type, boolean] +description: "Learn about the Boolean data type in JavaScript, how to create Boolean values, and common operations with Boolean values." +hide_table_of_contents: true +--- + +In JavaScript, `Boolean` is a built-in data type that represents a logical value. It can have one of two values: `true` or `false`. The `Boolean` data type is used to store the result of logical operations and comparisons. + + +
+ +## Creating Boolean Values + +You can create `Boolean` values in JavaScript using the `true` and `false` literals. Here are examples of both values: + +### Using `true` and `false` Literals + +You can create `Boolean` values using the `true` and `false` literals. These are case-sensitive and must be written in lowercase: + +```javascript title="app.js" +let isTrue = true; +let isFalse = false; + +console.log(isTrue); // Output: true +console.log(isFalse); // Output: false +``` + +### Using Logical Expressions + +You can also create `Boolean` values using logical expressions that evaluate to `true` or `false`. For example: + +```javascript title="app.js" +let greaterThan = 10 > 5; // true +let lessThan = 5 < 2; // false + +console.log(greaterThan); // Output: true +console.log(lessThan); // Output: false +``` + + +
+ +## Common Operations with Boolean Values + +### Logical Operators + +You can perform logical operations on `Boolean` values using logical operators. The following logical operators are supported in JavaScript: + +- Logical AND (`&&`): Returns `true` if both operands are `true`, otherwise returns `false`. +- Logical OR (`||`): Returns `true` if at least one of the operands is `true`, otherwise returns `false`. +- Logical NOT (`!`): Returns `true` if the operand is `false`, and `false` if the operand is `true`. +- Logical XOR (exclusive OR) (`^`): Returns `true` if exactly one of the operands is `true`, otherwise returns `false`. + +Here are examples of using logical operators with `Boolean` values: + +```javascript title="app.js" +let a = true; +let b = false; + +console.log(a && b); // Output: false +console.log(a || b); // Output: true +console.log(!a); // Output: false +console.log(a ^ b); // Output: true +``` + +### Comparison Operators + +You can compare `Boolean` values using comparison operators. The following comparison operators are supported in JavaScript: + +- Equal to (`==` or `===`): Returns `true` if the operands are equal, otherwise returns `false`. +- Not equal to (`!=` or `!==`): Returns `true` if the operands are not equal, otherwise returns `false`. +- Greater than (`>`): Returns `true` if the left operand is greater than the right operand, otherwise returns `false`. +- Less than (`<`): Returns `true` if the left operand is less than the right operand, otherwise returns `false`. +- Greater than or equal to (`>=`): Returns `true` if the left operand is greater than or equal to the right operand, otherwise returns `false`. +- Less than or equal to (`<=`): Returns `true` if the left operand is less than or equal to the right operand, otherwise returns `false`. +- Strict equality (`===`): Returns `true` if the operands are equal and of the same type, otherwise returns `false`. +- Strict inequality (`!==`): Returns `true` if the operands are not equal and/or not of the same type, otherwise returns `false`. +- Logical AND (`&&`): Returns `true` if both operands are `true`, otherwise returns `false`. +- Logical OR (`||`): Returns `true` if at least one of the operands is `true`, otherwise returns `false`. + +Here are examples of using comparison operators with `Boolean` values: + +```javascript title="app.js" +let a = true; +let b = false; + +console.log(a === b); // Output: false +console.log(a !== b); // Output: true +console.log(a > b); // Output: true +console.log(a < b); // Output: false +console.log(a >= b); // Output: true +console.log(a <= b); // Output: false +``` + +### Conditional (Ternary) Operator + +You can use the conditional (ternary) operator to assign values based on a condition. The syntax of the conditional operator is as follows: + +```javascript +condition ? valueIfTrue : valueIfFalse; +``` + +Here's an example of using the conditional operator with `Boolean` values: + +```javascript title="app.js" +let a = true; +let b = false; + +let result = a ? "It's true" : "It's false"; +console.log(result); // Output: It's true + +result = b ? "It's true" : "It's false"; +console.log(result); // Output: It's false +``` + +The conditional operator evaluates the condition (`a` or `b` in this case) and returns the value specified after `?` if the condition is `true`, and the value specified after `:` if the condition is `false`. + + +
+ +## Converting Values to Boolean + +You can convert values to `Boolean` using the `Boolean()` function. The `Boolean()` function converts a value to a `Boolean` value based on the truthy or falsy nature of the value. Here's how it works: + +- If the value is falsy (e.g., `0`, `null`, `undefined`, `NaN`, `false`, or an empty string `""`), it returns `false`. +- If the value is truthy (e.g., non-zero numbers, non-empty strings, objects, arrays, functions), it returns `true`. +- For `Boolean` values, it returns the value as is. + +Here are examples of converting values to `Boolean` using the `Boolean()` function: + +```javascript title="app.js" +console.log(Boolean(0)); // Output: false +console.log(Boolean(1)); // Output: true +console.log(Boolean("")); // Output: false +console.log(Boolean("Hello")); // Output: true +console.log(Boolean(null)); // Output: false +console.log(Boolean(undefined)); // Output: false +console.log(Boolean({})); // Output: true +console.log(Boolean([])); // Output: true +console.log(Boolean(function () {})); // Output: true +console.log(Boolean(true)); // Output: true +console.log(Boolean(false)); // Output: false +``` + +The `Boolean()` function is useful when you need to convert values to `Boolean` for logical operations or comparisons. + + +
+ +## Conclusion + +In this tutorial, you learned about the `Boolean` data type in JavaScript, how to create `Boolean` values using `true` and `false` literals, and common operations with `Boolean` values. You also learned how to convert values to `Boolean` using the `Boolean()` function. diff --git a/docs/javascript/data-types/primitive-types/null.mdx b/docs/javascript/data-types/primitive-types/null.mdx new file mode 100644 index 0000000..10d0641 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/null.mdx @@ -0,0 +1,146 @@ +--- +id: null-data-type +title: "Null Data Type in JavaScript" +sidebar_label: "Null" +sidebar_position: 6 +tags: [javascript, data type, primitive type, "null"] +description: "Learn about the null data type in JavaScript, how to create null values, and common operations with null values." +hide_table_of_contents: true +--- + +In JavaScript, `null` is a primitive data type that represents the intentional absence of any object value. It is used to indicate that a variable does not have a value or points to no object. The `null` value is a special keyword that is case-sensitive (`null` is not the same as `Null` or `NULL`). + + +
+ +## Creating Null Values + +You can create `null` values in JavaScript by assigning the `null` keyword to a variable. Here is an example of creating a `null` value: + +```javascript title="app.js" +let nullValue = null; + +console.log(nullValue); // Output: null +``` + +In the example above, the variable `nullValue` is assigned the `null` value, which indicates that it does not have a value. + + +
+ +## Common Operations with Null Values + +### Checking for Null Values + +You can check if a variable contains a `null` value using a strict equality comparison (`===`). The strict equality operator compares both the value and the type of the operands. Here is an example of checking for a `null` value: + +```javascript title="app.js" +let nullValue = null; + +if (nullValue === null) { + console.log("The variable contains a null value."); +} else { + console.log("The variable does not contain a null value."); +} +``` + +In the example above, the strict equality comparison (`===`) checks if the `nullValue` variable contains a `null` value and prints the appropriate message. + +### Type of Null Values + +The `typeof` operator in JavaScript returns the data type of a variable or expression. When you use the `typeof` operator with a `null` value, it returns `"object"`. This behavior is considered a historical bug in JavaScript and is unlikely to change due to backward compatibility. Here is an example of using the `typeof` operator with a `null` value: + +```javascript title="app.js" +let nullValue = null; + +console.log(typeof nullValue); // Output: object +``` + +In the example above, the `typeof` operator returns `"object"` when used with a `null` value. + +:::note + +The `typeof` operator returns `"object"` for `null` values, which is a historical quirk in JavaScript. It is not considered a bug but rather a design choice that has been preserved for backward compatibility. + +::: + + +
+ +### Converting Null Values + +You can convert a `null` value to a boolean, number, or string using type conversion. When you convert a `null` value to a boolean, it evaluates to `false`. When you convert a `null` value to a number, it evaluates to `0`. When you convert a `null` value to a string, it evaluates to `"null"`. Here are examples of converting a `null` value: + +#### Converting to Boolean + +```javascript title="app.js" +let nullValue = null; + +let booleanValue = Boolean(nullValue); + +console.log(booleanValue); // Output: false +``` + +#### Converting to Number + +```javascript title="app.js" +let nullValue = null; + +let numberValue = Number(nullValue); + +console.log(numberValue); // Output: 0 +``` + +#### Converting to String + +```javascript title="app.js" +let nullValue = null; + +let stringValue = String(nullValue); + +console.log(stringValue); // Output: "null" +``` + +In the examples above, the `null` value is converted to a boolean, number, and string using type conversion. + + +
+ +### Comparing Null Values + +You can compare `null` values using comparison operators like `<`, `>`, `<=`, `>=`, `==`, `===`, `!=`, and `!==`. Here's an example of comparing `null` values: + +```javascript title="app.js" +let nullValue1 = null; +let nullValue2 = null; + +console.log(nullValue1 === nullValue2); // Output: true +``` + +In the example above, the strict equality comparison (`===`) checks if `nullValue1` is equal to `nullValue2`, and it returns `true`. + +### Conditional (Ternary) Operator + +You can use the conditional (ternary) operator to assign values based on a condition. The syntax of the conditional operator is as follows: + +```javascript +condition ? valueIfTrue : valueIfFalse; +``` + +Here's an example of using the conditional operator with `null` values: + +```javascript title="app.js" +let nullValue = null; + +let result = nullValue ? "It's true" : "It's false"; +console.log(result); // Output: It's false +``` + +The conditional operator evaluates the condition (`nullValue` in this case) and returns the value specified after `?` if the condition is `true`, and the value specified after `:` if the condition is `false`. + + +
+ +## Conclusion + +In this tutorial, you learned about the `null` data type in JavaScript, how to create `null` values, and common operations with `null` values. You can use the `null` value to represent the intentional absence of any object value in your JavaScript programs. \ No newline at end of file diff --git a/docs/javascript/data-types/primitive-types/number.mdx b/docs/javascript/data-types/primitive-types/number.mdx new file mode 100644 index 0000000..88ff5a1 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/number.mdx @@ -0,0 +1,364 @@ +--- +id: number +title: Numbers in JavaScript +sidebar_label: Number +sidebar_position: 3 +tags: [javascript, data type, primitive type, number] +description: "Learn about the number data type in JavaScript, how to create number values, and common operations with number values." +hide_table_of_contents: true +--- + +Numbers are a crucial part of any programming language, and JavaScript is no exception. In JavaScript, numbers are used to perform calculations, manipulate data, and handle various operations. This tutorial will walk you through everything you need to know about numbers in JavaScript, from basic concepts to advanced usage. + + +
+ +## What Is a Number in JavaScript? + +In JavaScript, the `number` data type represents numeric values, including integers and floating-point numbers. Numbers in JavaScript are used to perform arithmetic operations, store numerical data, and represent quantities in various contexts. + +Here are some key points about numbers in JavaScript: + +- Numbers can be positive, negative, or zero. +- Numbers can be integers (whole numbers) or floating-point numbers (numbers with decimal points). +- JavaScript uses the `number` data type to represent all numeric values, regardless of whether they are integers or floating-point numbers. +- Numbers in JavaScript are stored as 64-bit floating-point values using the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754). +- JavaScript provides built-in functions and operators for performing arithmetic operations, comparisons, and other operations with numbers. + +**Example:** + +```javascript title="app.js" +let integerNumber = 42; // Integer number +let floatingPointNumber = 3.14; // Floating-point number + +console.log(integerNumber); // Output: 42 +console.log(floatingPointNumber); // Output: 3.14 +``` + +In the example above, `integerNumber` is an integer value (`42`), and `floatingPointNumber` is a floating-point value (`3.14`). Both values are stored as `number` data types in JavaScript. + + +
+ +## Types of Numbers in JavaScript + +### 1. Integers + +Integers are whole numbers without any decimal points. In JavaScript, integers can be positive, negative, or zero. The `number` data type in JavaScript can represent integer values within a certain range. + +**Example:** + +```javascript title="app.js" +let positiveInteger = 42; // Positive integer +let negativeInteger = -10; // Negative integer +let zero = 0; // Zero + +console.log(positiveInteger); // Output: 42 +console.log(negativeInteger); // Output: -10 +console.log(zero); // Output: 0 +``` + +### 2. Floating-Point Numbers + +Floating-point numbers are numbers with decimal points. In JavaScript, floating-point numbers can represent fractional values, scientific notation, and other real numbers. The `number` data type in JavaScript can represent floating-point values with a certain precision. + +**Example:** + +```javascript title="app.js" +let pi = 3.14159; // Pi (π) approximation + +console.log(pi); // Output: 3.14159 +``` + +### 3. Scientific Notation + +JavaScript supports scientific notation for representing very large or very small numbers. Scientific notation uses the `e` character to denote the exponent of a number. + +**Example:** + +```javascript title="app.js" +let largeNumber = 5e6; // 5 million, equivalent to 5 * 10^6 +let smallNumber = 5e-6; // 0.000005, equivalent to 5 * 10^-6 + +console.log(largeNumber); // Outputs: 5000000 +console.log(smallNumber); // Outputs: 0.000005 +``` + +In the examples above, `5e6` represents `5` multiplied by `10` raised to the power of `6` (i.e., `5,000,000`), and `5e-6` represents `5` multiplied by `10` raised to the power of `-6` (i.e., `0.000005`). + + +
+ +## Number Precision + +JavaScript numbers are precise up to 15 digits. Beyond this, precision may be lost, and the results of calculations might not be what you expect. + +**Example:** + +```javascript title="app.js" +let preciseNumber = 0.1 + 0.2; +console.log(preciseNumber); // Outputs: 0.30000000000000004 +``` + +In the example above, adding `0.1` and `0.2` results in `0.30000000000000004` due to the limited precision of JavaScript numbers. + +## Special Numeric Values + +JavaScript provides special numeric values to represent exceptional cases, such as `Infinity`, `-Infinity`, and `NaN` (Not-a-Number). + +### 1. Infinity + +The `Infinity` value represents positive infinity in JavaScript. It is used to denote a value that exceeds the upper limit of representable numbers. + +**Example:** + +```javascript title="app.js" +let positiveInfinity = Infinity; + +console.log(positiveInfinity); // Output: Infinity +console.log(positiveInfinity + 1); // Output: Infinity +``` + +### 2. -Infinity + +The `-Infinity` value represents negative infinity in JavaScript. It is used to denote a value that exceeds the lower limit of representable numbers. + +**Example:** + +```javascript title="app.js" +let negativeInfinity = -Infinity; + +console.log(negativeInfinity); // Output: -Infinity +console.log(negativeInfinity - 1); // Output: -Infinity +``` + + +
+ +### 3. NaN (Not-a-Number) + +The `NaN` value represents a special "not-a-number" value in JavaScript. It is used to denote the result of an invalid mathematical operation, such as dividing zero by zero. + +**Example:** + +```javascript title="app.js" +let notANumber = NaN; + +console.log(notANumber); // Output: NaN +console.log(0 / 0); // Output: NaN +``` + +## Number Methods + +JavaScript provides built-in methods for working with numbers. These methods can be used to perform various operations, such as rounding numbers, converting numbers to strings, and generating random numbers. + +Here are some common number methods in JavaScript: + +### 1. `toFixed()` + +The `toFixed()` method formats a number using fixed-point notation with a specified number of decimal places. + +**Example:** + +```javascript title="app.js" +let number = 3.14159; +let formattedNumber = number.toFixed(2); + +console.log(formattedNumber); // Output: 3.14 +``` + +### 2. `toString()` + +The `toString()` method converts a number to a string representation. + +**Example:** + +```javascript title="app.js" +let number = 42; + +console.log(number.toString()); // Output: "42" +``` + +### 3. `parseInt()` + +The `parseInt()` function parses a string and returns an integer. + +**Example:** + +```javascript title="app.js" +let number = parseInt("42"); + +console.log(number); // Output: 42 +``` + + +
+ +### 4. `parseFloat()` + +The `parseFloat()` function parses a string and returns a floating-point number. + +**Example:** + +```javascript title="app.js" +let number = parseFloat("3.14"); + +console.log(number); // Output: 3.14 +``` + +### 5. `Math.random()` + +The `Math.random()` function generates a random floating-point number between 0 (inclusive) and 1 (exclusive). + +**Example:** + +```javascript title="app.js" +let randomNumber = Math.random(); + +console.log(randomNumber); // Output: A random number between 0 and 1 +``` + +### 6. `toPrecision()` + +The `toPrecision()` method formats a number to a specified precision. + +**Example:** + +```javascript title="app.js" +let number = 123.456; + +console.log(number.toPrecision(2)); // Output: 1.2e+2 +``` + +### 7. `isNaN()` + +The `isNaN()` function checks if a value is `NaN` (Not-a-Number). + +**Example:** + +```javascript title="app.js" +console.log(isNaN(123)); // Outputs: false +console.log(isNaN("abc")); // Outputs: true +``` + +### 8. `isFinite()` + +The `isFinite()` function checks if a value is a finite number. + +**Example:** + +```javascript title="app.js" +console.log(isFinite(42)); // Outputs: true +console.log(isFinite(Infinity)); // Outputs: false +``` + + +
+ +### 9. `Number()` + +The `Number()` function converts a value to a number. + +**Example:** + +```javascript title="app.js" +let str = "123"; +let num = Number(str); + +console.log(num); // Outputs: 123 +``` + +## Common Arithmetic Operations with Numbers + +JavaScript provides arithmetic operators for performing basic arithmetic operations with numbers. Here are some common arithmetic operations you can perform with numbers in JavaScript: + +### 1. Addition (`+`) + +The addition operator (`+`) is used to add two numbers together. + +**Example:** + +```javascript title="app.js" +let num1 = 10; +let num2 = 20; +let sum = num1 + num2; + +console.log(sum); // Output: 30 +``` + +### 2. Subtraction (`-`) + +The subtraction operator (`-`) is used to subtract one number from another. + +**Example:** + +```javascript title="app.js" +let num1 = 20; +let num2 = 10; +let difference = num1 - num2; + +console.log(difference); // Output: 10 +``` + +### 3. Multiplication (`*`) + +The multiplication operator (`*`) is used to multiply two numbers. + +**Example:** + +```javascript title="app.js" +let num1 = 5; +let num2 = 6; +let product = num1 * num2; + +console.log(product); // Output: 30 +``` + + +
+ +### 4. Division (`/`) + +The division operator (`/`) is used to divide one number by another. + +**Example:** + +```javascript title="app.js" +let num1 = 20; +let num2 = 5; +let quotient = num1 / num2; + +console.log(quotient); // Output: 4 +``` + +### 5. Modulus (`%`) + +The modulus operator (`%`) is used to find the remainder of the division of two numbers. + +**Example:** + +```javascript title="app.js" +let num1 = 10; +let num2 = 3; +let remainder = num1 % num2; + +console.log(remainder); // Output: 1 +``` + +### 6. Exponentiation (`**`) + +The exponentiation operator (`**`) is used to raise one number to the power of another. + +**Example:** + +```javascript title="app.js" +let base = 2; +let exponent = 3; +let result = base ** exponent; + +console.log(result); // Output: 8 +``` + +## Conclusion + +Numbers are an essential part of JavaScript programming, used for calculations, data manipulation, and various operations. In this tutorial, you learned about the `number` data type in JavaScript, different types of numbers, special numeric values, number precision, number methods, and arithmetic operations with numbers. Understanding numbers in JavaScript will help you work with numeric data effectively and efficiently in your JavaScript applications. \ No newline at end of file diff --git a/docs/javascript/data-types/primitive-types/string.mdx b/docs/javascript/data-types/primitive-types/string.mdx new file mode 100644 index 0000000..b8fe06f --- /dev/null +++ b/docs/javascript/data-types/primitive-types/string.mdx @@ -0,0 +1,161 @@ +--- +id: string +title: String Data Type in JavaScript +sidebar_label: String +sidebar_position: 1 +tags: [javascript, data type, primitive type, string] +description: "Learn about the string data type in JavaScript, how to create strings, and common string operations." +hide_table_of_contents: true +--- + +In JavaScript, a string is a sequence of characters enclosed within single or double quotes. Strings are used to represent text data and are one of the primitive data types in JavaScript. + + +
+ +## Creating Strings + +You can create strings in JavaScript using single quotes (`'`), double quotes (`"`), or backticks (`` ` ``). Here are examples of each: + +```javascript title="app.js" +let singleQuoted = "Hello, World!"; +let doubleQuoted = "Hello, World!"; +let backticks = `Hello, World!`; +``` + +### Single Quotes + +Strings enclosed within single quotes are the most common way to create strings in JavaScript. You can use single quotes to represent text data: + +```javascript title="app.js" +let singleQuoted = "Hello, World!"; + +console.log(singleQuoted); // Output: Hello, World! +``` + +### Double Quotes + +Strings enclosed within double quotes are functionally equivalent to single-quoted strings. You can use double quotes to represent text data: + +```javascript title="app.js" +let doubleQuoted = "Hello, World!"; + +console.log(doubleQuoted); // Output: Hello, World! +``` + +### Backticks + +Strings enclosed within backticks are called template literals. Template literals allow you to embed expressions and multiline strings in JavaScript. You can use backticks to represent text data: + +```javascript title="app.js" +let backticks = `Hello, World!`; + +console.log(backticks); // Output: Hello, World! +``` + + +
+ +## Common String Operations + +Strings in JavaScript support various operations, such as concatenation, interpolation, and methods for manipulating string data. Here are some common string operations: + +### Concatenation + +String concatenation is the process of combining two or more strings into a single string. You can use the `+` operator or template literals for string concatenation: + +```javascript title="app.js" +let firstName = "John"; +let lastName = "Doe"; + +// Using the + operator +let fullName = firstName + " " + lastName; +console.log(fullName); // Output: John Doe + +// Using template literals +let fullNameTemplate = `${firstName} ${lastName}`; +console.log(fullNameTemplate); // Output: John Doe +``` + +### Interpolation + +String interpolation allows you to embed expressions within a string. You can use template literals to interpolate variables and expressions directly within the string: + +```javascript title="app.js" +let name = "Alice"; +let greeting = `Hello, ${name}!`; + +console.log(greeting); // Output: Hello, Alice! +``` + +### String Methods + +JavaScript provides built-in methods for working with strings. Here are some common string methods: + +- `length`: Returns the length of a string. +- `toUpperCase()`: Converts a string to uppercase. +- `toLowerCase()`: Converts a string to lowercase. +- `trim()`: Removes whitespace from the beginning and end of a string. +- `split()`: Splits a string into an array of substrings based on a delimiter. +- `indexOf()`: Returns the index of the first occurrence of a substring within a string. +- `replace()`: Replaces a substring with another substring. +- `substring()`: Extracts a substring based on start and end positions. +- `charAt()`: Returns the character at a specified index. +- `startsWith()`: Checks if a string starts with a specified substring. +- `endsWith()`: Checks if a string ends with a specified substring. +- `includes()`: Checks if a string contains a specified substring. +- `slice()`: Extracts a portion of a string based on start and end positions. +- `concat()`: Combines two or more strings. +- `repeat()`: Repeats a string a specified number of times. +- `padStart()`: Pads a string with another string until it reaches a specified length from the start. +- `padEnd()`: Pads a string with another string until it reaches a specified length from the end. +- `match()`: Searches a string for a specified pattern and returns an array of matches. +- `search()`: Searches a string for a specified pattern and returns the index of the first match. + +Here's an example using some of these string methods: + +```javascript title="app.js" +let text = "Hello, World!"; +let substring = text.substring(0, 5); // Extracts 'Hello' +let uppercaseText = text.toUpperCase(); // Converts text to uppercase +let replacedText = text.replace("World", "JavaScript"); // Replaces 'World' with 'JavaScript' +let splitText = text.split(","); // Splits text into an array ['Hello', ' World!'] +let includesText = text.includes("Hello"); // Checks if text contains 'Hello' (returns true) +let indexOfText = text.indexOf("World"); // Returns the index of 'World' (returns 7) +let length = text.length; // Returns the length of the text (returns 13) +let charAt = text.charAt(7); // Returns the character at index 7 (returns 'W') +let startsWith = text.startsWith("Hello"); // Checks if text starts with 'Hello' (returns true) +let endsWith = text.endsWith("World!"); // Checks if text ends with 'World!' (returns true) +let repeatText = text.repeat(2); // Repeats text twice ('Hello, World!Hello, World!') +let paddedText = text.padStart(20, "*"); // Pads text with '*' until it reaches a length of 20 from the start +let trimmedText = " Hello, World! ".trim(); // Removes whitespace from the beginning and end of the text + +console.log(substring); +console.log(uppercaseText); +console.log(replacedText); +console.log(splitText); +console.log(includesText); +console.log(indexOfText); +console.log(length); +console.log(charAt); +console.log(startsWith); +console.log(endsWith); +console.log(repeatText); +console.log(paddedText); +console.log(trimmedText); +``` + +These are just a few examples of the many string methods available in JavaScript. You can explore more string methods in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). + + +
+ +Strings are a fundamental part of JavaScript and are widely used to represent text data in web development. Understanding how to create and manipulate strings is essential for building interactive web applications. + +In this tutorial, you learned about the string data type in JavaScript, how to create strings using single quotes, double quotes, and backticks, and common string operations such as concatenation, interpolation, and string methods. You also explored examples of using string methods to manipulate and work with string data. + +Strings are versatile and powerful data types in JavaScript, and mastering string operations will help you build dynamic and interactive web applications. If you want to learn more about JavaScript data types, check out our [JavaScript Data Types](/docs/category/data-types-1) tutorial. + +## Conclusion + +Strings are a fundamental data type in JavaScript used to represent text data. You can create strings using single quotes, double quotes, or backticks. Strings support various operations such as concatenation, interpolation, and methods for manipulating string data. diff --git a/docs/javascript/data-types/primitive-types/symbol.mdx b/docs/javascript/data-types/primitive-types/symbol.mdx new file mode 100644 index 0000000..41f6c75 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/symbol.mdx @@ -0,0 +1,132 @@ +--- +id: symbol +title: "Symbol Data Type in JavaScript" +sidebar_label: "Symbol" +sidebar_position: 7 +tags: [javascript, data type, primitive type, symbol] +description: Learn about the symbol data type in JavaScript, how to create symbols, and common operations with symbols. +hide_table_of_contents: true +--- + +In JavaScript, `Symbol` is a primitive data type introduced in ECMAScript 6 (ES6) that represents a unique and immutable value. Symbols are used to create unique identifiers for object properties and are often used as property keys in objects. The `Symbol` type is a special data type that is used to create unique values that are guaranteed to be different from other values. + + +
+ +## Creating Symbols + +You can create symbols in JavaScript using the `Symbol()` function. The `Symbol()` function returns a new unique symbol value each time it is called. Here is an example of creating a symbol: + +```javascript title="app.js" +// Create a new symbol +let symbol1 = Symbol(); +let symbol2 = Symbol(); + +console.log(symbol1); // Output: Symbol() +console.log(symbol2); // Output: Symbol() + +// Check if the symbols are equal + +console.log(symbol1 === symbol2); // Output: false +``` + +In the example above, the `Symbol()` function is used to create two unique symbols, `symbol1` and `symbol2`. The symbols are guaranteed to be different from each other, as shown by the strict equality comparison (`===`) between `symbol1` and `symbol2`. + +You can also create symbols with a description (also known as a symbol key) to provide additional information about the symbol. The description is a string that is used to identify the symbol. Here is an example of creating a symbol with a description: + +```javascript title="app.js" +// Create a symbol with a description +let symbolWithDescription = Symbol("mySymbol"); + +console.log(symbolWithDescription); // Output: Symbol(mySymbol) +``` + +In the example above, the `Symbol("mySymbol")` function is used to create a symbol with the description `"mySymbol"`. The description is displayed when the symbol is converted to a string. + + +
+ +## Common Operations with Symbols + +### Using Symbols as Object Properties + +Symbols are often used as property keys in objects to create unique properties that are not accessible using regular property access methods. Symbols are guaranteed to be unique, which makes them useful for creating private properties or methods in objects. Here is an example of using symbols as object properties: + +```javascript title="app.js" +// Create a symbol for a property key +let firstName = Symbol("firstName"); + +// Create an object with a symbol property +let person = { + [firstName]: "John", + lastName: "Doe", + age: 30, +}; + +console.log(person[firstName]); // Output: John +``` + +In the example above, the `firstName` symbol is used as a property key in the `person` object to create a unique property that is not accessible using regular property access methods. The value associated with the `firstName` symbol can be accessed using bracket notation (`person[firstName]`). + +### Using Symbols to Avoid Property Name Collisions + +Symbols can be used to avoid property name collisions in objects. Since symbols are guaranteed to be unique, they can be used to create properties that are unlikely to clash with properties created by other code. This can be useful when working with third-party libraries or frameworks. Here is an example of using symbols to avoid property name collisions: + +```javascript title="app.js" +// Create a symbol for a property key +let logSymbol = Symbol("log"); + +// Create an object with a symbol property +let logger = { + [logSymbol]: function (message) { + console.log(message); + }, +}; + +logger[logSymbol]("Logging a message"); // Output: Logging a message +``` + +In the example above, the `logSymbol` symbol is used as a property key in the `logger` object to create a unique property that contains a logging function. The logging function can be accessed using bracket notation (`logger[logSymbol]`) and called with a message argument. + +### Using Well-Known Symbols + +JavaScript provides a set of well-known symbols that are used to define the behavior of objects in specific contexts. Well-known symbols are predefined symbols that have special meanings and are used by built-in JavaScript objects. For example, the `Symbol.iterator` symbol is used to define an iterator method for objects that can be iterated over using a `for...of` loop. Here is an example of using the `Symbol.iterator` symbol: + +```javascript title="app.js" +// Create an array +let numbers = [1, 2, 3]; + +// Get the iterator symbol +let iterator = numbers[Symbol.iterator](); + +// Iterate over the array using the iterator +for (let number of iterator) { + console.log(number); +} +``` + +In the example above, the `Symbol.iterator` symbol is used to get the iterator method of the `numbers` array. The iterator method is then used to iterate over the array elements using a `for...of` loop. + + +
+ +Symbols are a powerful feature in JavaScript that allow you to create unique identifiers for object properties and avoid property name collisions. By using symbols, you can create properties that are guaranteed to be unique and not accessible using regular property access methods. Symbols are commonly used in libraries, frameworks, and built-in JavaScript objects to define special behaviors and features. + +:::note + +- Symbols are unique and immutable values that are used to create unique identifiers for object properties. +- You can create symbols using the `Symbol()` function with an optional description. +- Symbols are often used as property keys in objects to create unique properties that are not accessible using regular property access methods. +- Symbols can be used to avoid property name collisions and define special behaviors in objects. +- JavaScript provides a set of well-known symbols that are used to define the behavior of objects in specific contexts. +- Well-known symbols are predefined symbols that have special meanings and are used by built-in JavaScript objects. +- Symbols are a powerful feature in JavaScript that allow you to create unique identifiers for object properties and avoid property name collisions. +- By using symbols, you can create properties that are guaranteed to be unique and not accessible using regular property access methods. +- Symbols are commonly used in libraries, frameworks, and built-in JavaScript objects to define special behaviors and features. +- Symbols are unique and immutable values that are used to create unique identifiers for object properties. + +::: + +## Conclusion + +In JavaScript, the `Symbol` data type is used to create unique and immutable values that can be used as property keys in objects. Symbols are guaranteed to be different from other values and are often used to create private properties, avoid property name collisions, and define special behaviors in objects. By using symbols, you can create unique identifiers that are not accessible using regular property access methods, making them a powerful tool for defining object properties and behaviors. \ No newline at end of file diff --git a/docs/javascript/data-types/primitive-types/undefined.mdx b/docs/javascript/data-types/primitive-types/undefined.mdx new file mode 100644 index 0000000..02dee65 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/undefined.mdx @@ -0,0 +1,116 @@ +--- +id: undefined +title: Undefined Data Type in JavaScript +sidebar_label: Undefined +sidebar_position: 2 +tags: [javascript, data type, primitive type, undefined] +description: "Learn about the undefined data type in JavaScript, how to create undefined values, and common operations with undefined values." +hide_table_of_contents: true +--- + +In JavaScript, `undefined` is a primitive data type that represents an undefined value. When a variable is declared but not assigned a value, it is automatically assigned the value `undefined`. + + +
+ +## Creating Undefined Values + +You can create `undefined` values in JavaScript by declaring a variable without assigning a value to it. Here's an example: + +```javascript title="app.js" +let undefinedValue; +console.log(undefinedValue); // Output: undefined +``` + +In the example above, the variable `undefinedValue` is declared but not assigned a value, so it is automatically assigned the value `undefined`. + +## Checking for Undefined Values + +You can check if a variable is `undefined` using strict equality (`===`) or the `typeof` operator. Here are examples of both methods: + +### Using Strict Equality (`===`) + +You can use the strict equality operator (`===`) to check if a variable is `undefined`. The strict equality operator compares both the value and the type of the operands: + +```javascript title="app.js" +let undefinedValue; +console.log(undefinedValue === undefined); // Output: true +``` + +### Using the `typeof` Operator + +You can also use the `typeof` operator to check if a variable is `undefined`. The `typeof` operator returns the data type of the operand: + +```javascript title="app.js" +let undefinedValue; +console.log(typeof undefinedValue === "undefined"); // Output: true +``` + + +
+ +## Common Operations with Undefined Values + +### Assigning Undefined Values + +You can assign `undefined` to a variable explicitly by using the `undefined` keyword. Here's an example: + +```javascript title="app.js" +let explicitUndefined = undefined; + +console.log(explicitUndefined); // Output: undefined +``` + +### Returning Undefined from Functions + +If a function does not explicitly return a value, it implicitly returns `undefined`. Here's an example: + +```javascript title="app.js" +function noReturnValue() { + // No return statement +} + +console.log(noReturnValue()); // Output: undefined +``` + +### Deleting Properties + +You can delete properties from an object using the `delete` operator. After deleting a property, accessing the property will return `undefined`. Here's an example: + +```javascript title="app.js" +let person = { name: "Alice", age: 30 }; + +delete person.age; + +console.log(person.age); // Output: undefined +``` + +### Checking for Undefined Properties + +You can check if an object has a property with an `undefined` value using the `in` operator. The `in` operator returns `true` if the property exists in the object, even if its value is `undefined`. Here's an example: + +```javascript title="app.js" +let person = { name: "Alice", age: undefined }; + +console.log("age" in person); // Output: true +``` + +### Passing Undefined Arguments + +If a function is called with fewer arguments than declared parameters, the missing arguments are assigned the value `undefined`. Here's an example: + +```javascript title="app.js" +function greet(name, message) { + console.log(`Hello, ${name}! ${message}`); +} + +greet("Alice"); // Output: Hello, Alice! undefined +``` + +In this example, the `greet` function is called with one argument (`'Alice'`) instead of two. The `message` parameter is assigned the value `undefined` because it is missing in the function call. + +Understanding the `undefined` data type and how it behaves in JavaScript is essential for writing robust and error-free code. By handling `undefined` values correctly, you can prevent unexpected behavior and improve the reliability of your JavaScript applications. + +## Conclusion + +In this tutorial, you learned about the `undefined` data type in JavaScript, how to create `undefined` values, and common operations with `undefined` values. You also explored various scenarios where `undefined` values are used and how to handle them effectively in your JavaScript code. \ No newline at end of file diff --git a/docs/javascript/introduction-to-javascript/_category_.json b/docs/javascript/introduction-to-javascript/_category_.json new file mode 100644 index 0000000..6275281 --- /dev/null +++ b/docs/javascript/introduction-to-javascript/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Introduction to JavaScript", + "position": 1, + "link": { + "type": "generated-index", + "description": "In this tutorial, you'll learn what is JavaScript, history of JavaScript, JavaScript versions, and how to use it to create interactive web experiences." + } +} diff --git a/docs/javascript/introduction-to-javascript/history-of-javascript.mdx b/docs/javascript/introduction-to-javascript/history-of-javascript.mdx new file mode 100644 index 0000000..10d2469 --- /dev/null +++ b/docs/javascript/introduction-to-javascript/history-of-javascript.mdx @@ -0,0 +1,55 @@ +--- +id: history-of-javascript +title: History of JavaScript +sidebar_label: History of JavaScript +sidebar_position: 2 +tags: [javascript, introduction to javascript, history of javascript] +description: "JavaScript has a rich history that dates back to the early days of the web. Learn about the origins of JavaScript, its evolution, and how it has become one of the most popular programming languages in the world." +hide_table_of_contents: true +--- + +JavaScript, the language that powers the dynamic behavior of websites today, has an interesting history that dates back to the early days of the internet. It was created in just **10 days**, but its impact on the web has been profound and long-lasting. JavaScript has evolved significantly over the years, growing from a simple scripting language to a versatile and powerful programming language that is used by millions of developers worldwide. JavaScript was initially developed by **Brendan Eich** in 1995 while he was working at Netscape Communications Corporation. + + +
+ +## The Birth of JavaScript: A 10-Day Wonder + +In 1995, Netscape Communications Corporation was in a fierce competition with Microsoft to dominate the web browser market. Netscape wanted to create a language that could run in the browser and provide dynamic behavior to web pages. Brendan Eich, a talented engineer at Netscape, was tasked with creating this new language. In just **10 days**, Eich created the first version of JavaScript, originally called **Mocha** and later renamed to **LiveScript** before settling on the name we know today: **JavaScript**. + +The initial goal of JavaScript was to provide a simple scripting language that could be embedded in HTML pages to add interactivity and dynamic behavior. JavaScript was designed to be easy to learn and use, making it accessible to web developers of all skill levels. The language quickly gained popularity due to its simplicity and versatility, allowing developers to create interactive websites and web applications with ease. + +## JavaScript vs. Java: Clearing the Confusion + +One common misconception about JavaScript is that it is related to the Java programming language. In reality, JavaScript and Java are two distinct languages with different origins and purposes. JavaScript was developed by Brendan Eich at Netscape, while Java was created by James Gosling at Sun Microsystems. The similarity in their names was a marketing decision by Netscape to capitalize on the popularity of Java at the time. + +Despite their different origins, JavaScript and Java share some similarities in their syntax and structure, which can be confusing for beginners. However, JavaScript is a much simpler and more lightweight language than Java, making it ideal for front-end web development. Java, on the other hand, is a robust, object-oriented language that is used for a wide range of applications, including server-side development. + +## The Evolution of JavaScript: From Toy to Powerhouse + +When JavaScript was first released, it was met with skepticism by some developers who saw it as a "toy" language. However, its ease of use and the growing demand for interactive web pages quickly made it popular. + +- **1996:** Microsoft introduced **JScript**, a dialect of JavaScript, in Internet Explorer 3. This move helped standardize the language across different browsers. +- **1997:** The **ECMAScript** standard was created to define the core features of the language. This standardization ensured that JavaScript would be consistent and compatible across different platforms. +- **2005:** **Ajax** (Asynchronous JavaScript and XML) was introduced, revolutionizing web development by enabling dynamic, asynchronous communication between the browser and server. +- **2009:** **Node.js** was released, allowing developers to run JavaScript on the server-side. This marked a significant shift in the way JavaScript was used, expanding its capabilities beyond the browser. +- **2015:** The release of **ECMAScript 6** (ES6) introduced new features and syntax enhancements to the language, making JavaScript more powerful and expressive. +- **2020:** JavaScript remains one of the most popular programming languages in the world, powering the majority of websites and web applications on the internet. +- **Future:** JavaScript continues to evolve, with new frameworks, libraries, and tools being developed to enhance its capabilities and simplify web development. + + +
+ +## JavaScript Today: A Ubiquitous Language + +Today, JavaScript is used by millions of developers worldwide to build a wide range of applications, from simple websites to complex web applications. It has become an essential tool for front-end web development, enabling developers to create interactive, engaging user experiences. JavaScript is also used on the server-side, thanks to technologies like Node.js, allowing developers to build full-stack applications using a single language. + +## The Future of JavaScript + +As the web continues to evolve, JavaScript will play an increasingly important role in shaping the future of web development. New features and enhancements are being added to the language to make it more powerful, expressive, and efficient. JavaScript frameworks like React, Angular, and Vue.js are driving innovation in front-end development, while Node.js is expanding the possibilities of server-side development. + +JavaScript's rich history, rapid evolution, and widespread adoption make it a language that is here to stay. Whether you're a seasoned developer or just starting out, JavaScript offers a world of possibilities for building dynamic, interactive web applications that engage users and deliver rich, immersive experiences. As the web landscape continues to change, JavaScript will remain at the forefront, powering the next generation of web development. + +## Conclusion + +JavaScript has come a long way since its humble beginnings in 1995. From a simple scripting language to a versatile and powerful programming language, JavaScript has transformed the way we interact with the web. Its rich history, rapid evolution, and widespread adoption make it one of the most popular programming languages in the world today. Whether you're a front-end developer, a full-stack developer, or just getting started with web development, JavaScript offers a world of possibilities for building dynamic, interactive web applications that engage users and deliver rich, immersive experiences. As the web continues to evolve, JavaScript will continue to play a central role in shaping the future of web development, driving innovation and enabling developers to create cutting-edge applications that push the boundaries of what is possible on the web. diff --git a/docs/javascript/introduction-to-javascript/how-to-run-javascript.mdx b/docs/javascript/introduction-to-javascript/how-to-run-javascript.mdx new file mode 100644 index 0000000..e4f4545 --- /dev/null +++ b/docs/javascript/introduction-to-javascript/how-to-run-javascript.mdx @@ -0,0 +1,230 @@ +--- +id: how-to-run-javascript +title: How to Run JavaScript +sidebar_label: How to Run JavaScript +sidebar_position: 4 +tags: [javascript, introduction to javascript, running javascript] +description: "Learn the various ways to run JavaScript, from using the browser console to server-side execution with Node.js. This guide covers different environments and tools for executing JavaScript code effectively." +hide_table_of_contents: true +--- + +JavaScript is a versatile language that can be run in various environments. Whether you're creating interactive web pages, building server-side applications, or scripting automation tasks, JavaScript has you covered. In this chapter, we'll explore different ways to run JavaScript, from your browser to the server and beyond. + + +
+ +## 1. Running JavaScript in the Browser + +### The Browser Console + +The simplest way to run JavaScript in the browser is through the developer console. You can open the console by right-clicking on a web page and selecting "Inspect" or pressing `Ctrl+Shift+I` (or `Cmd+Option+I` on macOS). Then, navigate to the "Console" tab. + +Here, you can type JavaScript code directly into the console and press `Enter` to execute it. For example, you can run the following code to display a message: + +```javascript +console.log("Hello, world!"); +``` + +### Inline Script Tags + +Another way to run JavaScript in the browser is by embedding it directly into an HTML document using ` + + +``` + +### External Script Files + +For larger JavaScript codebases, it's common to store the code in external script files with a `.js` extension. You can then include these files in your HTML document using the ` + + +``` + + +```javascript title="script.js" +console.log('Hello, world!'); +``` + + + + +When the HTML file is loaded in the browser, it will execute the JavaScript code from the `script.js` file and display the message in the console. + + +
+ +## 2. Running JavaScript on the Server with Node.js + +JavaScript is not limited to the browser; you can also run it on the server using Node.js. This allows you to build back-end services, APIs, and even full-stack applications using JavaScript. + +### Installing Node.js + +1. **Download Node.js:** Visit the [Node.js website](https://nodejs.org/) and download the latest LTS (Long-Term Support) version for your operating system. Node.js comes with npm (Node Package Manager) to install additional packages. +2. **Install Node.js:** Follow the installation instructions for your platform (Windows, macOS, or Linux). +3. **Verify Installation:** Open a terminal or command prompt and run the following commands to check if Node.js and npm are installed: + + + +```bash +node -v +``` + + +```bash +npm -v +``` + + + +If you see version numbers for Node.js and npm, you've successfully installed Node.js on your system. + +### Running JavaScript with Node.js + +Once Node.js is installed, you can create JavaScript files with Node.js code and run them from the command line. Here's an example of a simple Node.js script that displays a message: + +```javascript title="hello.js" +console.log("Hello, Node.js!"); +``` + +To run this script, save it as `hello.js` and open a terminal or command prompt. Navigate to the directory where the script is saved and run the following command: + +```bash +node hello.js +``` + +You should see the message `Hello, Node.js!` printed to the console, indicating that the script ran successfully. + + +
+ +### Node.js as a JavaScript Runtime + +Picture Node.js as a powerful engine that can take your JavaScript code and run it outside the browser. This opens up possibilities like building web servers, interacting with databases, handling file systems, and much more—all using JavaScript! + +**For example:** You can create a simple web server using Node.js with just a few lines of code: + +```javascript title="server.js" +// Load the HTTP module +const http = require("http"); + +// Create an HTTP server that responds with a message +const server = http.createServer((req, res) => { + res.writeHead(200, { "Content-Type": "text/plain" }); + res.end("Hello, Node.js Server!"); +}); + +// Listen on port 3000 +server.listen(3000, () => { + console.log("Server running at http://localhost:3000/"); +}); +``` + +Save this code as `server.js` and run it with Node.js using the following command: + +```bash +node server.js +``` + +You've now created a simple web server that listens on port 3000 and responds with the message `Hello, Node.js Server!` when accessed in a browser. + + +
+ +## 3. Running JavaScript in Online Editors + +If you want to experiment with JavaScript without setting up a local development environment, you can use online code editors that support JavaScript. These editors provide a browser-based environment where you can write, run, and share JavaScript code snippets. + +### Popular Online Editors: + +1. **[CodePen](https://codepen.io/):** A social development environment for front-end designers and developers. +2. **[JSFiddle](https://jsfiddle.net/):** An online playground for web development, testing, and sharing HTML, CSS, and JavaScript code snippets. +3. **[Repl.it](https://repl.it/):** An online IDE that supports multiple programming languages, including JavaScript. +4. **[StackBlitz](https://stackblitz.com/):** An online IDE for web applications powered by Visual Studio Code. + +These online editors provide a convenient way to write and run JavaScript code without the need for local setup. You can experiment with different features, test libraries, and share your code with others in real-time. + +:::note Example Using CodePen: + +- **Imagination:** Imagine you're working on a quick project or trying out a new idea. You open CodePen, type your JavaScript code, and instantly see the results on the screen—no setup required! + +1. **[Open CodePen](https://codepen.io/pen/):** Create a new pen. +2. **Write JavaScript:** Add your JavaScript code in the JavaScript editor. + + ```javascript + console.log("Hello, CodePen!"); + ``` + +3. **Run Code:** Click the "Run" button to execute the code and see the output in the console. +4. **Share Your Pen:** You can share your pen with others by copying the URL or embedding it in a webpage. +5. **Explore More:** CodePen offers additional features like HTML, CSS, preprocessors, and frameworks to enhance your projects. + ::: + +:::tip +When using online editors, remember that your code runs in a sandboxed environment, so you may encounter limitations compared to running JavaScript locally on your machine. +::: + + +## 4. Running JavaScript in Integrated Development Environments (IDEs) + +For more advanced JavaScript development, you can use Integrated Development Environments (IDEs) that provide powerful tools, debugging capabilities, and project management features. IDEs offer a comprehensive environment for writing, testing, and deploying JavaScript applications. + +### Popular JavaScript IDEs: + +1. **[Visual Studio Code](https://code.visualstudio.com/):** A lightweight, open-source code editor with built-in support for JavaScript, debugging, and extensions. +2. **[WebStorm](https://www.jetbrains.com/webstorm/):** A professional IDE for web development with advanced JavaScript features, debugging, and integration with popular frameworks. +3. **[Sublime Text](https://www.sublimetext.com/):** A versatile code editor with a rich ecosystem of plugins and packages for JavaScript development. +4. **[Atom](https://atom.io/):** A hackable text editor for the 21st century with built-in package manager and support for JavaScript development. + +These IDEs offer features like code completion, syntax highlighting, version control, and project management tools to streamline your JavaScript development workflow. You can customize the editor to suit your preferences and enhance your productivity when working on JavaScript projects. + + +
+ +:::note Example Using Visual Studio Code: + +- **Imagination:** Imagine you're building a complex web application with multiple files, dependencies, and configurations. You open Visual Studio Code, create a new project, write your JavaScript code, and run the application with live debugging and testing. + +1. **[Download Visual Studio Code](https://code.visualstudio.com/):** Install the editor on your machine. +2. **Create a New Project:** Open Visual Studio Code and create a new folder for your project. +3. **Write JavaScript Code:** Add your JavaScript code to a new file in the project folder. + + ```javascript + console.log("Hello, Visual Studio Code!"); + ``` + +4. **Run Code:** Use the built-in terminal to run your JavaScript code and see the output in the console. + + ![Visual Studio Code](image.png) + +::: + +## Conclusion + +JavaScript is a versatile language that can be run in various environments, from the browser to the server and online editors. By mastering the different ways to run JavaScript, you can build interactive web pages, server-side applications, and full-stack projects with ease. Experiment with running JavaScript in different environments, explore new features, and discover the endless possibilities of this powerful language. diff --git a/docs/javascript/introduction-to-javascript/image.png b/docs/javascript/introduction-to-javascript/image.png new file mode 100644 index 0000000000000000000000000000000000000000..6e8b80c01d25c19ae4c71280ea6d286b58ef95db GIT binary patch literal 13822 zcmeHtcT|&E*Do`UqA-XIy@k;zARPf|0dyz<6%c9CMXGeEp=K-y1|b4UF9HHe?;SFL zAtKFy0qGKIs0p1wlKX`5eecZs-S=DHUF)v<$GzW^1MK~|K79~CIUHUd~_}R z7#PlW(*J(Ic)xRGU{GMt)4FZ~8(W)ne`z-VNW`c3j^D$AIu+qNkGWvn&c8_C?n-Gl z`0%^d?dZmjd~CnnHYyaReu ze7#|Mqf0uyz0`zcUsSNyNl>R`ELu<9M0xLx6Awo=PPB~p^@s9h!Lt`L_TI^1#0s+` zx>7H&EAQG@CL?Z52*u`!7&_%DQMTojBn0PCnrw#^UvFx2u+o2QnksCe@1yZKus5*% zjoUvHv{v&kAQ*vPRCM@V;5$P8#RBJFDn7zL{E35ARgr<=vloJqf#D4dUBkAZ;$>3l>?FJ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>PZf=10qES@W~XRbIGxS zJvsq>oXE176|?-4V6{ewvLZNb|5bkqQ@YNT`l40&ZSs(u%a&^!CeIYGy=nzn5S;Uj(Ff$+3HE2rYezSZ@|cnUY_MdgC|6WQeQ@nkG>8B za3TjXzT@^oVI5e94lJi=86O{r{IXQ;hI^fk&dSQoM4fUC@t)~EKf@!M!SV}N`qD13 zj2Kc7DObS69($DV+`ijghg(-NqumbHK2#6`HQ&9a<$s0V+uai#%nQ4{qXKVCMD}UkG zskw4K=C9Wu=%G%!=LMjS%r2oS^EO4>s zlE3y{e@APf}6?qdGSrr8t6FxNy ZIr!f<2-U5x1sX8uX&Y#j{dVv1{{SJ +
+ +## ECMAScript 1 (ES1) - The Beginning (1997) + +The first official version of JavaScript was standardized as **ECMAScript 1 (ES1)** in 1997. This version established the core concepts of JavaScript, including basic syntax, types, and structures like functions, loops, and conditionals. Although primitive compared to today’s standards, ES1 laid the groundwork for all future developments. + +## ECMAScript 2 (ES2) - Minor Improvements (1998) + +**ECMAScript 2 (ES2)** was released in 1998 and mostly included minor changes to align the standard with the international ISO/IEC standard. It didn’t introduce any significant new features, but it helped solidify the language’s foundational elements. ES2 was a stepping stone towards more substantial updates in the future. + +## ECMAScript 3 (ES3) - The Game Changer (1999) + +**ECMAScript 3 (ES3)**, released in 1999, was a major update that brought significant improvements and new features to the language. It introduced: + +- **Regular expressions:** A powerful tool for matching patterns in strings, essential for tasks like form validation and text parsing. +- **Exception handling:** The `try-catch` statement for handling errors and exceptions in code. This feature improved code reliability and error handling. +- **New methods:** Several new methods for arrays and strings, such as `forEach`, `map`, `filter`, `replace`, `split`, `substring`, and `reduce`, which made working with data more efficient. +- **Better Control over Global Objects:** Enhancements to the global `Object` and `Array` prototypes, making JavaScript more flexible. + +ES3 was a significant milestone in JavaScript’s evolution, laying the foundation for modern web development practices. Many of the features introduced in ES3 are still widely used today. + + +
+ +## ECMAScript 4 (ES4) - The Unreleased Visionary + +**ECMAScript 4 (ES4)** was an ambitious update that aimed to introduce many advanced features, including classes, modules, and strong typing. However, due to disagreements within the committee and concerns over the complexity of the proposed changes, ES4 was never officially released. Many of its ideas would later influence future versions of JavaScript. + +## ECMAScript 5 (ES5) - The Modern Foundation (2009) + +After a long gap, **ECMAScript 5 (ES5)** was released in 2009 and is considered a modern foundation for JavaScript. ES5 brought a host of new features and improvements, including: + +- **Strict Mode:** A way to enforce stricter parsing and error handling in your code, helping to catch common mistakes. +- **JSON Support:** Native support for JSON (JavaScript Object Notation), making it easier to work with data formats commonly used in APIs. +- **Array Methods:** New methods like `forEach`, `map`, `filter`, `reduce`, and more, making array manipulation much more powerful and expressive. +- **Property Attributes:** The ability to define properties with attributes like `writable`, `enumerable`, and `configurable`, providing more control over object properties. +- **Object Methods:** New methods like `Object.keys`, `Object.create`, and `Object.defineProperty` for working with objects more efficiently. + +ES5 was a significant step forward, making JavaScript more reliable, maintainable, and easier to work with. + + +
+ +## ECMAScript 6 (ES6) / ECMAScript 2015 - The Big Leap Forward + +**ECMAScript 6 (ES6)**, also known as **ECMAScript 2015**, was a revolutionary update that transformed JavaScript into a more mature and feature-rich language. Released in 2015, ES6 introduced many new concepts that are now integral to modern JavaScript development: + +- **Arrow Functions:** A shorthand syntax for writing functions, which also lexically binds the `this` value, solving many issues with function scope. + + ```js title="index.js" + const add = (a, b) => a + b; + ``` + +- **Classes:** A more structured way to define objects and create reusable code, making JavaScript more object-oriented. + + ```js title="index.js" + class Person { + constructor(name) { + this.name = name; + } + + greet() { + return `Hello, my name is ${this.name}`; + } + } + ``` + +- **Template Literals:** A new way to create strings using backticks, allowing for string interpolation and multi-line strings. + + ```js title="index.js" + const name = "Alice"; + console.log(`Hello, ${name}!`); + ``` + +- **Destructuring Assignment:** A concise way to extract values from arrays or objects and assign them to variables. + + ```js title="index.js" + const [a, b] = [1, 2]; + console.log(a); // Output: 1 + console.log(b); // Output: 2 + ``` + +- **Modules:** A standardized way to organize and share code across multiple files, improving code maintainability and reusability. + + + + + ```js title="app/index.js" + import { greet } from "./utils.js"; + + console.log(greet("Alice")); + ``` + + + + ```js title="app/utils.js" + export function greet(name) { + return `Hello, ${name}!`; + } + ``` + + + + +- **Promises:** A more robust way to handle asynchronous operations, replacing callback functions with a cleaner and more readable syntax. + + ```js title="index.js" + function fetchData() { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve("Data fetched successfully!"); + }, 2000); + }); + } + + fetchData().then((data) => { + console.log(data); + }); + ``` + +- **And Much More:** ES6 introduced many other features like `let` and `const` for variable declarations, default parameters, rest parameters, the `...` spread operator, and more. + +ES6 was a game changer, introducing many features that are now considered essential in modern JavaScript development. + + +
+ +## ECMAScript 2016 (ES7) - Simplicity and Power + +**ECMAScript 2016 (ES7)**, released in 2016, was a smaller update but still added some valuable features: + +- **Array.prototype.includes:** A new method for arrays that checks if an array includes a specific element, returning `true` or `false`. + + ```js title="index.js" + const numbers = [1, 2, 3, 4, 5]; + console.log(numbers.includes(3)); // Output: true + console.log(numbers.includes(10)); // Output: false + ``` + +- **Exponentiation Operator (`**`):\*\* A new operator for exponentiation, providing a more concise way to calculate powers. + + ```js title="index.js" + console.log(2 ** 3); // Output: 8 + ``` + +ES7 focused on simplicity and power, adding features that made common tasks easier and more intuitive. + +## ECMAScript 2017 (ES8) - Async/Await and More + +ECMAScript 2017 (ES8), released in 2017, introduced several key features that further enhanced the language’s capabilities: + +- **Async/Await:** A new way to write asynchronous code that is easier to read and understand than traditional Promise-based code. + + ```js title="index.js" + async function fetchData() { + const response = await fetch("https://jsonplaceholder.org/users"); + const users = await response.json(); + return users; + } + + fetchData().then((users) => { + console.log(users); + }); + ``` + +- **Object.values/Object.entries:** New methods for objects that return an array of values or key-value pairs, respectively. + + ```js title="index.js" + const person = { name: "Alice", age: 30 }; + console.log(Object.values(person)); // Output: ["Alice", 30] + console.log(Object.entries(person)); // Output: [["name", "Alice"], ["age", 30]] + ``` + +- **String Padding:** New methods like `padStart` and `padEnd` for padding strings with spaces to a specified length. + + ```js title="index.js" + const str = "Hello"; + console.log(str.padStart(10, ".")); // Output: ".....Hello" + console.log(str.padEnd(10, ".")); // Output: "Hello....." + ``` + +ES8 continued the trend of making JavaScript more powerful and expressive, with features that simplified common tasks and improved code readability. + + +
+ +## ECMAScript 2018 (ES9) - Rest/Spread Properties and More + +**ECMAScript 2018 (ES9)**, released in 2018, continued to build on JavaScript’s versatility with several enhancements: + +- **Rest/Spread Properties:** The rest and spread operators can now be used with object properties, allowing for more flexible object manipulation. + + ```js title="index.js" + const person = { name: "Alice", age: 30, city: "New York" }; + const { name, ...details } = person; + console.log(name); // Output: "Alice" + console.log(details); // Output: { age: 30, city: "New York" } + ``` + +- **Promise.finally:** A new method for promises that allows you to run code after a promise is settled, whether it’s resolved or rejected. + + ```js title="index.js" + fetchData() + .then((data) => { + console.log(data); + }) + .catch((error) => { + console.error(error); + }) + .finally(() => { + console.log("Request completed."); + }); + ``` + +- **Asynchronous Iteration:** The `for-await-of` loop for asynchronous iteration over async iterators, making it easier to work with asynchronous data streams. + + ```js title="index.js" + async function fetchUsers() { + const response = await fetch("https://jsonplaceholder.org/users"); + const users = await response.json(); + return users; + } + + (async () => { + for await (const user of fetchUsers()) { + console.log(user); + } + })(); + ``` + +ES9 further refined JavaScript’s capabilities, making it easier to work with complex data structures and asynchronous operations. + + +
+ +## ECMAScript 2019 (ES10) - Refinements and Improvements + +**ECMAScript 2019 (ES10)**, released in 2019, added useful refinements to JavaScript: + +- **Array.prototype.flat/flatMap:** New methods for arrays that flatten nested arrays and map over them, respectively. + + ```js title="index.js" + const numbers = [1, [2, 3], [4, [5]]]; + console.log(numbers.flat()); // Output: [1, 2, 3, 4, [5]] + console.log(numbers.flatMap((num) => num * 2)); // Output: [2, 4, 6, 8, 10] + ``` + +- **String.trimStart/trimEnd:** New methods for strings that remove whitespace from the start or end of a string. + + ```js title="index.js" + const str = " Hello "; + console.log(str.trimStart()); // Output: "Hello " + console.log(str.trimEnd()); // Output: " Hello" + ``` + +- **Object.fromEntries:** A method that transforms a list of key-value pairs into an object. + + ```js title="index.js" + const entries = [ + ["name", "Alice"], + ["age", 30], + ]; + const person = Object.fromEntries(entries); + console.log(person); // Output: { name: "Alice", age: 30 } + ``` + +ES10 focused on refining existing features and making JavaScript more concise and expressive. + +## ECMAScript 2020 (ES11) - Dynamic Import and GlobalThis + +**ECMAScript 2020 (ES11)**, released in 2020, introduced several new features to enhance JavaScript: + +- **Dynamic Import:** A new way to import modules dynamically, allowing you to load modules on-demand. + + ```js title="index.js" + import("./utils.js") + .then((module) => { + console.log(module.greet("Alice")); + }) + .catch((error) => { + console.error(error); + }); + ``` + +- **BigInt:** A new primitive type for representing arbitrarily large integers, useful for applications that require working with large numbers. + + ```js title="index.js" + const bigNumber = 1234567890123456789012345678901234567890n; + console.log(bigNumber); // Output: 1234567890123456789012345678901234567890n + ``` + +- **GlobalThis:** A new global object that provides a consistent way to access the global object across different environments (e.g., browsers, Node.js). + + ```js title="index.js" + console.log(globalThis); + ``` + +- **Nullish Coalescing Operator (`??`):** A new operator that returns the right-hand operand when the left-hand operand is `null` or `undefined`, helping to handle default values more effectively. + + ```js title="index.js" + const name = null; + console.log(name ?? "Anonymous"); // Output: "Anonymous" + ``` + +- **Optional Chaining Operator (`?.`):** A new operator that allows you to safely access nested properties of an object without worrying about `null` or `undefined` values. + + ```js title="index.js" + const person = { name: "Alice" }; + console.log(person.address?.city); // Output: undefined + ``` + +ES11 introduced features that improved code readability, maintainability, and performance. + + +
+ +## ECMAScript 2021 (ES12) - More Quality-of-Life Improvements + +**ECMAScript 2021 (ES12)**, released in 2021, continued to refine the language: + +- **String.prototype.replaceAll:** A new method for strings that replaces all occurrences of a substring with another substring. + + ```js title="index.js" + const str = "Hello, World!"; + console.log(str.replaceAll("o", "*")); // Output: Hell*, W*rld! + ``` + +- **Logical Assignment Operators (`||=`, `&&=`, `??=`):** New operators that combine logical operations with assignment, providing a more concise way to update variables. + + ```js title="index.js" + let count = 0; + count ||= 10; + console.log(count); // Output: 10 + ``` + +- **Numeric Separators:** A new syntax that allows you to use underscores as separators in numeric literals for improved readability. + + ```js title="index.js" + const billion = 1_000_000_000; + console.log(billion); // Output: 1000000000 + ``` + +- **Promise.any:** A new method for promises that resolves when any of the input promises are fulfilled, useful for scenarios where you want to handle the first successful promise. + + ```js title="index.js" + Promise.any([fetchData1(), fetchData2(), fetchData3()]) + .then((data) => { + console.log(data); + }) + .catch((error) => { + console.error(error); + }); + ``` + +ES12 focused on quality-of-life improvements and developer productivity, making JavaScript code more concise and readable. + + +
+ +## ECMAScript 2022 (ES13) - Even More Enhancements + +**ECMAScript 2022 (ES13**), released in 2022, continued the trend of enhancing JavaScript with new features that improve code readability, performance, and ease of use. The additions in ES13 are subtle but impactful, particularly for developers working with large, complex applications. + +1. **Class Fields and Static Initialization Blocks:** + + - **Public and Private Class Fields:** ES13 introduced a more straightforward way to define properties directly within class definitions. Public fields can be declared without the need for a constructor, while private fields are prefixed with a `#`. + + ```js title="index.js" + class Person { + name = "John"; // Public field + #age = 30; // Private field + + getAge() { + return this.#age; + } + } + const person = new Person(); + console.log(person.name); // 'John' + console.log(person.getAge()); // 30 + ``` + + - **Static Initialization Blocks:** Static initialization blocks allow complex initialization logic within a class. This is particularly useful for initializing static properties that require more than a simple assignment. + + ```js title="index.js" + class Config { + static API_URL; + static { + Config.API_URL = + process.env.NODE_ENV === "production" + ? "https://api.example.com" + : "http://localhost:3000"; + } + } + console.log(Config.API_URL); // URL based on the environment + ``` + +2. **Top-Level** `await`: + + - **Top-Level** `await` allows you to use the `await` keyword outside of an `async` function, making it easier to work with asynchronous operations at the top level of your code. + + ```js title="index.js" + const data = await fetchData(); + console.log(data); + ``` + + This feature makes it easier to write cleaner and more straightforward code in modules, particularly when dealing with asynchronous operations. + +3. **New Array Methods**: + + - **`Array.prototype.at(index)`**: The `at()` method allows you to access an element in an array at a specific index, similar to using bracket notation (`[]`), but with additional features like negative indexing and handling out-of-bounds indices. + + ```js title="index.js" + const colors = ["red", "green", "blue"]; + console.log(colors.at(1)); // 'green' + console.log(colors.at(-1)); // 'blue' + console.log(colors.at(3)); // undefined + ``` + + This method is particularly useful for accessing elements from the end of an array without needing to know its length. + +4. **Error Cause**: + + - The `Error` object now includes a `cause` property that allows you to associate an error with its underlying cause. This can be useful for tracking the root cause of an error in complex error-handling scenarios. + + ```js title="index.js" + try { + throw new Error("Something went wrong", { cause: originalError }); + } catch (err) { + console.error(err.cause); // Logs the original error + } + ``` + + This feature enhances error handling by making it easier to trace the root cause of an error. + +## ECMAScript 2023 (ES14) - Focus on Consistency and Usability + +**ECMAScript 2023 (ES14)**, released in 2023, continues to build on the language's strengths by introducing features aimed at consistency, usability, and improving developer experience. + +1. **Array `findLast()` and `findLastIndex()`** + + - **Array `findLast()` Method:** This method is similar to `find()`, but it starts searching from the end of the array instead of the beginning. + + ```js title="index.js" + const arr = [1, 2, 3, 4, 5]; + const lastEven = arr.findLast((num) => num % 2 === 0); + console.log(lastEven); // 4 + ``` + + - **Array `findLastIndex()` Method:** Similarly, `findLastIndex()` returns the index of the last element that satisfies the condition. + + ```js title="index.js" + const arr = [1, 2, 3, 4, 5]; + const lastIndex = arr.findLastIndex((num) => num % 2 === 0); + console.log(lastIndex); // 3 + ``` + + These methods provide a convenient way to search for elements from the end of an array. + +2. **Hashbang Grammar** + + - **Hashbang (`#!`) Support:** ES14 introduces support for hashbang (`#!`) comments in JavaScript files. This feature allows you to specify the path to the Node.js interpreter directly in your JavaScript file. + + ```js title="index.js" + #!/usr/bin/env node + console.log("Hello, World!"); + ``` + + This feature simplifies the execution of JavaScript files as standalone scripts using Node.js. + +3. **Symbol `keyFor()` Method** + + - **Symbol `keyFor()` Method:** The `keyFor()` method allows you to retrieve the key of a symbol from the global symbol registry. This can be useful when you need to access the key associated with a symbol. + + ```js title="index.js" + const sym = Symbol.for("mySymbol"); + console.log(Symbol.keyFor(sym)); // 'mySymbol' + ``` + + This method provides a way to retrieve the key associated with a symbol, making it easier to work with symbols in certain scenarios. + +4. **RegExp Match Indices** + + - **RegExp Match Indices:** ES14 introduces a new property, `indices`, to the result of `RegExp.prototype.exec()`. This property provides the start and end indices of the matched substring within the input string. + + ```js title="index.js" + const str = "Hello, World!"; + const regex = /World/; + const match = regex.exec(str); + console.log(match.indices); // [[7, 12]] + ``` + + This feature enhances regular expression handling by providing more detailed information about matched substrings. + + +
+ +### Conclusion + +JavaScript has come a long way since its inception in 1995. Each new version of the language has introduced innovative features and improvements that have transformed the way developers write code. Understanding the evolution of JavaScript and the features introduced in each version is essential for mastering the language and staying up-to-date with the latest trends in web development. By learning about the different ECMAScript versions and their capabilities, you can enhance your skills as a JavaScript developer and build more robust, efficient, and maintainable applications. \ No newline at end of file diff --git a/docs/javascript/introduction-to-javascript/what-is-js.mdx b/docs/javascript/introduction-to-javascript/what-is-js.mdx new file mode 100644 index 0000000..4455322 --- /dev/null +++ b/docs/javascript/introduction-to-javascript/what-is-js.mdx @@ -0,0 +1,73 @@ +--- +id: what-is-javascript +title: What is JavaScript? +sidebar_label: What is JavaScript? +sidebar_position: 1 +tags: [javascript, introduction to javascript, what is javascript] +description: "JavaScript is a high-level, interpreted programming language that is widely used for front-end web development. It is a versatile language that can be used for a variety of purposes, including building interactive websites, web applications, and server-side applications." +hide_table_of_contents: true +--- + +JavaScript is a powerful and versatile programming language that is widely used for front-end web development. It is a high-level, interpreted language that can be used to create interactive websites, web applications, and server-side applications. If you've ever interacted with a website—whether it's clicking a button, filling out a form, or watching content update dynamically—JavaScript was likely at work behind the scenes, making it all happen. JavaScript is the "magic" that brings web pages to life, allowing them to respond to user actions and create engaging experiences. + + +
+ +:::tip Imagine JavaScript as the "Magician" of Web Pages + +Think of a static web page as a plain book. It has text and images, but you can't interact with it beyond reading. Now, imagine a magician who can make the pictures move, allow you to turn the pages with a click, or even chat with you through the book. JavaScript is that magician—it turns a static page into an interactive, engaging experience. +::: + +## A Simple Example: The Magic of JavaScript + +Let’s say you visit a web page to check the current time. Without JavaScript, you’d just see a static number, maybe updated each minute. But with JavaScript, the time can tick in real-time, changing every second as if the page is alive. + +```html title="index.html" + + + + Real-Time Clock + + +

Current Time:

+

+ + + + +``` + +In this example, the `updateTime` function grabs the current time, formats it, and then displays it on the page. The `setInterval` function ensures this happens every second, creating a live clock. Without JavaScript, you'd have to refresh the page to see the updated time! + +## The Role of JavaScript in the Web Ecosystem + +JavaScript is one of the three core technologies of the web: + +1. **HTML (HyperText Markup Language):** This is the structure or skeleton of a web page. It defines elements like headings, paragraphs, images, and links. +2. **CSS (Cascading Style Sheets):** CSS is the design or the skin of the web page. It styles the HTML elements, adding colors, layouts, and fonts to make the page visually appealing. +3. **JavaScript:** JavaScript is the brain that brings the page to life, allowing it to respond to user actions, perform calculations, manipulate content, and much more. + + +
+ +## Why is JavaScript Important? + +- **Interactivity:** JavaScript allows users to interact with web pages in ways that were previously impossible. Hovering over menus, filling out forms, dragging and dropping items—all these actions are powered by JavaScript. +- **Web Applications:** Beyond simple interactivity, JavaScript is the foundation for complex web applications like Google Maps, where you can zoom in, drag the map, and get directions—all without leaving the page. +- **Server-Side Capabilities:** With the advent of Node.js, JavaScript isn’t just for the browser anymore. It can also run on servers, powering the backend of web applications. + +:::tip Imagine JavaScript in Everyday Life +Imagine you walk into a smart home where everything responds to your commands. You say, "Turn on the lights," and the lights come on. You ask for your favorite music, and it starts playing. JavaScript is like the software controlling that smart home—it listens, understands, and responds, making your environment interactive and personalized. +::: + +### Conclusion + +JavaScript is a versatile and powerful programming language that plays a crucial role in web development. It allows developers to create interactive websites, web applications, and server-side applications, making the web more engaging and dynamic. Learning JavaScript opens up a world of possibilities, enabling you to build exciting projects and create engaging user experiences. Let's dive deeper into the world of JavaScript and explore its features, capabilities, and best practices. From 819c6bcd3b76dadc57ae3eef90b3b65de39132e3 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 3 Oct 2025 21:29:13 +0530 Subject: [PATCH 2/3] Fix issue --- docs/javascript/data-types/primitive-types/string.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/javascript/data-types/primitive-types/string.mdx b/docs/javascript/data-types/primitive-types/string.mdx index b8fe06f..d2e2a09 100644 --- a/docs/javascript/data-types/primitive-types/string.mdx +++ b/docs/javascript/data-types/primitive-types/string.mdx @@ -154,7 +154,7 @@ Strings are a fundamental part of JavaScript and are widely used to represent te In this tutorial, you learned about the string data type in JavaScript, how to create strings using single quotes, double quotes, and backticks, and common string operations such as concatenation, interpolation, and string methods. You also explored examples of using string methods to manipulate and work with string data. -Strings are versatile and powerful data types in JavaScript, and mastering string operations will help you build dynamic and interactive web applications. If you want to learn more about JavaScript data types, check out our [JavaScript Data Types](/docs/category/data-types-1) tutorial. +Strings are versatile and powerful data types in JavaScript, and mastering string operations will help you build dynamic and interactive web applications. If you want to learn more about JavaScript data types, check out our [JavaScript Data Types](/tutorial/category/data-types-1) tutorial. ## Conclusion From fb364b0dc3afbf6e5353502c7932e1c4799b5e64 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 3 Oct 2025 21:31:12 +0530 Subject: [PATCH 3/3] Fix issue --- docs/javascript/data-types/primitive-types/string.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/javascript/data-types/primitive-types/string.mdx b/docs/javascript/data-types/primitive-types/string.mdx index d2e2a09..88b7e68 100644 --- a/docs/javascript/data-types/primitive-types/string.mdx +++ b/docs/javascript/data-types/primitive-types/string.mdx @@ -154,7 +154,7 @@ Strings are a fundamental part of JavaScript and are widely used to represent te In this tutorial, you learned about the string data type in JavaScript, how to create strings using single quotes, double quotes, and backticks, and common string operations such as concatenation, interpolation, and string methods. You also explored examples of using string methods to manipulate and work with string data. -Strings are versatile and powerful data types in JavaScript, and mastering string operations will help you build dynamic and interactive web applications. If you want to learn more about JavaScript data types, check out our [JavaScript Data Types](/tutorial/category/data-types-1) tutorial. +Strings are versatile and powerful data types in JavaScript, and mastering string operations will help you build dynamic and interactive web applications. If you want to learn more about JavaScript data types, check out our [JavaScript Data Types](/tutorial/category/data-types) tutorial. ## Conclusion