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 000000000..76d53afe7 --- /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 000000000..943c0daf9 --- /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.md b/docs/javascript/data-types/non-primitive-types/object/creating-objects.md new file mode 100644 index 000000000..a956384f4 --- /dev/null +++ b/docs/javascript/data-types/non-primitive-types/object/creating-objects.md @@ -0,0 +1,279 @@ +--- +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. +--- + + + +
+ +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. diff --git a/docs/javascript/data-types/non-primitive-types/object/intro.md b/docs/javascript/data-types/non-primitive-types/object/intro.md new file mode 100644 index 000000000..655eb943c --- /dev/null +++ b/docs/javascript/data-types/non-primitive-types/object/intro.md @@ -0,0 +1,88 @@ +--- +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. +--- + + + +
+ +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. diff --git a/docs/javascript/data-types/primitive-types/bigint.md b/docs/javascript/data-types/primitive-types/bigint.md index e69de29bb..a34a463f7 100644 --- a/docs/javascript/data-types/primitive-types/bigint.md +++ b/docs/javascript/data-types/primitive-types/bigint.md @@ -0,0 +1,129 @@ +--- +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. +--- + + + +
+ +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. diff --git a/docs/javascript/data-types/primitive-types/boolean.md b/docs/javascript/data-types/primitive-types/boolean.md index e69de29bb..7560d0419 100644 --- a/docs/javascript/data-types/primitive-types/boolean.md +++ b/docs/javascript/data-types/primitive-types/boolean.md @@ -0,0 +1,159 @@ +--- +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. +--- + + + +
+ +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.md b/docs/javascript/data-types/primitive-types/null.md new file mode 100644 index 000000000..95a9c4803 --- /dev/null +++ b/docs/javascript/data-types/primitive-types/null.md @@ -0,0 +1,150 @@ +--- +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. +--- + + + +
+ +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. diff --git a/docs/javascript/data-types/primitive-types/symbol.md b/docs/javascript/data-types/primitive-types/symbol.md index e69de29bb..1ba969f19 100644 --- a/docs/javascript/data-types/primitive-types/symbol.md +++ b/docs/javascript/data-types/primitive-types/symbol.md @@ -0,0 +1,134 @@ +--- +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. +--- + + + +
+ +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.