js/quiz: data types in JavaScript (#458)

This commit is contained in:
Vikas yadav 2024-06-05 14:24:43 +05:30 committed by GitHub
parent cf1356bc8b
commit db51fca38c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 330 additions and 0 deletions

View File

@ -0,0 +1,133 @@
---
title: What are `Symbols` used for ?
---
## TL;DR
`Symbols` in JavaScript are a new `primitive` data type introduced in `ES6 (ECMAScript 2015)`. They are unique and immutable identifiers that is primarily for object property keys to avoid name collisions. These values can be created using `Symbol(...)` function, and each `Symbol` value is guaranteed to be unique, even if they have the same description. `Symbol` properties are not enumerable in `for...in` loops or `Object.keys()`, making them suitable for creating private/internal object state.
```js
let sym1 = Symbol();
let sym2 = Symbol('description');
console.log(typeof sym1); // "symbol"
console.log(sym1 === sym2); // false, because each symbol is unique
let obj = {};
let sym = Symbol('uniqueKey');
obj[sym] = 'value';
console.log(obj[sym]); // "value"
```
> The `Symbol(..)` function must be called without the `new` keyword.
---
## `Symbols` in JavaScript
Symbols in JavaScript are a unique and immutable data type used primarily for object property keys to avoid name collisions.
### Key Characteristics
- **Uniqueness**: Each Symbol value is unique, even if they have the same description.
- **Immutability**: Symbol values are immutable, meaning their value cannot be changed.
- **Non-Enumerable**: Symbol properties are not included in for...in loops or Object.keys().
### Creating `Symbol`
You can create a `Symbol` using the `Symbol()` function:
```js
let sym1 = Symbol();
let sym2 = Symbol('description');
console.log(typeof sym1); // "symbol"
console.log(sym1 === sym2); // false, because each symbol is unique
```
> The `Symbol(..)` function must be called without the `new` keyword.
### Using `Symbols` as `object` property keys
`Symbols` can be used to add properties to an object without risk of name collision:
```js
let obj = {};
let sym = Symbol('uniqueKey');
obj[sym] = 'value';
console.log(obj[sym]); // "value"
```
### `Symbol` are not enumerable
- `Symbol` properties are not included in `for...in` loops or` Object.keys()`.
- This makes them suitable for creating private/internal object state.
- You can use` Object.getOwnPropertySymbols(obj)` to get all symbol properties of an object
### Global `Symbol` registry
You can create global `symbols` using `Symbol.for('key')`, which creates a new `symbol` in the global registry if it doesn't exist, or returns the existing on. This allows you to reuse `symbols` across different parts of your codebase or even across different code bases.
```js
let globalSym1 = Symbol.for('globalKey');
let globalSym2 = Symbol.for('globalKey');
console.log(globalSym1 === globalSym2); // true
let key = Symbol.keyFor(globalSym1);
console.log(key); // "globalKey"
```
## Well-known `Symbol`
JavaScript includes several built-in `symbols`, referred as `well-known symbols`.
- **Symbol.iterator**: Defines the default `iterator` for an `object`.
- **Symbol.toStringTag**: Used to create a string description for an `object`.
- **Symbol.hasInstance**: Used to determine if an `object` is an instance of a `constructor`.
**`Symbol.iterator`**:
```js
let iterable = {
[Symbol.iterator]() {
let step = 0;
return {
next() {
step++;
if (step <= 5) {
return { value: step, done: false };
}
return { done: true };
},
};
},
};
for (let value of iterable) {
console.log(value); // 1, 2, 3, 4, 5
}
```
**`Symbol.toStringTag`**:
```js
let myObj = {
[Symbol.toStringTag]: 'MyCustomObject',
};
console.log(Object.prototype.toString.call(myObj)); // "[object MyCustomObject]"
```
## Summary
Symbols are a powerful feature in JavaScript, especially useful for creating unique object properties and customizing object behavior. They provide a means to create hidden properties, preventing accidental access or modification, which is particularly beneficial in large-scale applications and libraries.
## Further reading
- [Symbol- MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)
- [Symbol type](https://javascript.info/symbol)
- [A quick overview of JavaScript symbols](https://www.freecodecamp.org/news/how-did-i-miss-javascript-symbols-c1f1c0e1874a/)
- [Symbol Values - You Don't Know JS Yet](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch1.md#symbol-values)

View File

@ -0,0 +1,11 @@
{
"slug": "what-are-symbols-used-for",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": ["javascript"],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,175 @@
---
title: What are the various data types in javascript ?
---
## TL;DR
In JavaScript, data types can be categorized into `primitive` and `non-primitive` types:
**Primitive data type**
- **Number**: Represents both integers and floating-point numbers.
- **String**: Represents sequences of characters.
- **Boolean**: Represents `true` or `false` values.
- **Undefined**: A variable that has been declared but not assigned a value.
- **Null**: Represents the intentional absence of any object value.
- **Symbol**: A unique and immutable value used as object property keys.
- **BigInt**: Represents integers with arbitrary precision.
**Non-Primitive (Reference) Data Types**
- **Object**: Used to store collections of data.
- **Array**: An ordered collection of data.
- **Function**: A callable object.
- **Date**: Represents dates and times.
- **RegExp**: Represents regular expressions.
- **Map**: A collection of keyed data items.
- **Set**: A collection of unique values.
The `primitive` types store a single value, while `non-primitive` types can store collections of data or complex entities.
---
## Data types in JavaScript
JavaScript, like many programming languages, has a variety of data types to represent different kinds of data. The main data types in JavaScript can be divided into two categories: `primitive` and `non-primitive (reference)` types.
### Primitive data types
1. **Number**: Represents both integer and floating-point numbers. JavaScript only has one type of number.
```js
let age = 25;
let price = 99.99;
```
2. **String**: Represents sequences of characters. `Strings` can be enclosed in single quotes, double quotes, or backticks (for template literals).
```js
let name = 'John Doe';
let greeting = 'Hello, world!';
let message = `Welcome, ${name}!`;
```
3. **Boolean**: Represents logical entities and can have two values: `true` or `false`.
```js
let isActive = true;
let isOver18 = false;
```
4. **Undefined**: A variable that has been declared but not assigned a value is of type `undefined`.
```js
let user;
console.log(user); // undefined
```
5. **Null**: Represents the intentional absence of any object value. It is a primitive value and is treated as a falsy value.
```js
let user = null;
```
6. **Symbol**: A unique and immutable `primitive` value, typically used as the key of an object property.
```js
let sym1 = Symbol();
let sym2 = Symbol('description');
```
7. **BigInt**: Used for representing integers with arbitrary precision, useful for working with very large numbers.
```js
let bigNumber = BigInt(9007199254740991);
let anotherBigNumber = 1234567890123456789012345678901234567890n;
```
### `Non-primitive` (reference) data types
1. **Object**: It is used to store collections of data and more complex entities. `Objects` are created using curly braces `{}`.
```js
let person = {
name: 'Alice',
age: 30,
};
```
2. **Array**: A special type of object used for storing ordered collections of data. `Arrays` are created using square brackets `[]`.
```js
let numbers = [1, 2, 3, 4, 5];
```
3. **Function**: `Functions` in JavaScript are `objects`. They can be defined using function declarations or expressions.
```js
function greet() {
console.log('Hello!');
}
let add = function (a, b) {
return a + b;
};
```
4. **Date**: Represents dates and times. The `Date` object is used to work with dates.
```js
let today = new Date();
```
5. **RegExp**: Represents regular expressions, which are patterns used to match character combinations in strings.
```js
let pattern = /abc/;
```
6. **Map**: A collection of keyed data items, similar to an `object` but allows keys of any type.
```js
let map = new Map();
map.set('key1', 'value1');
```
7. **Set**: A collection of unique values.
```js
let set = new Set();
set.add(1);
set.add(2);
```
## Pitfalls
### Type coercion:
JavaScript often performs type coercion, converting values from one type to another, which can lead to unexpected results.
```js
let result = '5' + 5; // '55' (string concatenation)
let sum = '5' - 2; // 3 (numeric subtraction)
```
JavaScript is a `dynamically-typed` language, which means variables can hold values of different data types over time. The `typeof` operator can be used to determine the data type of a value or variable.
```js
console.log(typeof 42); // "number"
console.log(typeof 'hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a historical bug in JavaScript)
console.log(typeof Symbol()); // "symbol"
console.log(typeof BigInt(123)); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function () {}); // "function"
```
## Further reading
- [JavaScript data types and data structures - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)
- [JavaScript guide: Data types](https://www.linkedin.com/pulse/javascript-guide-data-types-mila-mirovi%C4%87-jykmf)
- [JavaScript data types](https://www.programiz.com/javascript/data-types)
- [Data types - javascript.info](https://javascript.info/types)

View File

@ -0,0 +1,11 @@
{
"slug": "what-are-the-various-data-types-in-javascript",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": ["javascript"],
"importance": "low",
"difficulty": "easy"
}