├── EN
├── 01-basic.md
├── 02-intermediate.md
├── 03-advance.md
├── 04-ES5-2009.md
├── 05-ES6-2015.md
├── 06-ES7-2016.md
├── 07-ES8-2017.md
├── 08-ES9-2018.md
├── 09-ES10-2019.md
├── 10-ES11-2020.md
├── 11-ES12-2021.md
├── 12-ES13-2022.md
├── 13-ES14-2023.md
└── 14-ES15-2024.md
├── FA
├── 01-basic.md
├── 02-intermediate.md
├── 03-advance.md
├── 04-ES5-2009.md
├── 05-ES6-2015.md
├── 06-ES7-2016.md
├── 07-ES8-2017.md
├── 08-ES9-2018.md
├── 09-ES10-2019.md
├── 10-ES11-2020.md
├── 11-ES12-2021.md
├── 12-ES13-2022.md
├── 13-ES14-2023.md
└── 14-ES15-2024.md
├── README-FA.md
└── README.md
/EN/01-basic.md:
--------------------------------------------------------------------------------
1 | # Basic JavaScript Questions
2 |
3 | ## Variables and Data Types
4 |
5 | ### 1. What's the difference between `let`, `const`, and `var`?
6 | > The main difference is that `var` is function-scoped, while `let` and `const` are block-scoped. `let` lets you update a variable but not re-declare it, whereas `const` doesn’t allow you to do either. It’s more strict.
7 |
8 | ### 2. What are the different data types in JavaScript?
9 | > In JavaScript, we have primitive data types like `Number`, `String`, `Boolean`, `Undefined`, `Null`, `Symbol`, and `BigInt`. And then there’s non-primitive types like `Object`, which include things like `Array`, `Function`, etc.
10 |
11 | ### 3. How do you check if a variable is an array?
12 | > You can check by using the method `Array.isArray(variable)`. Simple as that.
13 |
14 | ### 4. What does the `typeof` operator do?
15 | > The `typeof` operator gives back a string that tells you the type of the value it’s checking.
16 |
17 | ## Operators and Control Structures
18 |
19 | ### 5. What's the difference between `==` and `===`?
20 | > `==` checks for value equality but allows type coercion (so it might convert types to make a match), while `===` is more strict—it checks for both value and type equality. No type conversion happens here.
21 |
22 | ### 6. How do you handle exceptions in JavaScript?
23 | > To handle exceptions, you use `try`, `catch`, and `finally` blocks. The `try` block tests a piece of code for errors, `catch` takes care of the error if there’s one, and `finally` runs some code after the try/catch, no matter what.
24 |
25 | ## Functions
26 |
27 | ### 7. What is a callback function?
28 | > A callback function is basically a function that you pass into another function as an argument, and then it gets executed inside that function to complete a task. Handy for asynchronous stuff.
29 |
30 | ### 8. Can you explain the `this` keyword in JavaScript?
31 | > The `this` keyword refers to something different depending on the context. In a method, `this` refers to the object the method belongs to. In a function, `this` points to the global object (or undefined in strict mode). In an event handler, `this` refers to the element that got the event.
32 |
33 | ### 9. What's the `arguments` object?
34 | > The `arguments` object is like an array, available inside functions, that contains all the arguments passed to the function. It’s old school, kinda replaced by modern rest parameters.
35 |
36 | ### 10. What are default parameters in JavaScript?
37 | > Default parameters let you set default values for function parameters if no value or `undefined` is passed when calling the function.
38 | > ```javascript
39 | > function greet(name = 'Guest') { console.log(`Hello, ${name}`); }
40 | > ```
41 |
42 | ## Arrays and Objects
43 |
44 | ### 11. How do you create an object in JavaScript?
45 | > You can create objects using object literals, constructors, or even the `Object.create` method. There’s more than one way to do it!
46 |
47 | ### 12. How do you merge two objects in JavaScript?
48 | > Merging two objects can be done with `Object.assign` or using the spread operator. Both works.
49 | > ```javascript
50 | > const merged = Object.assign({}, obj1, obj2);
51 | > const merged = {...obj1, ...obj2};
52 | > ```
53 |
54 | ### 13. How do you add an element to the start of an array?
55 | > To add an element to the beginning of an array, use the `unshift` method.
56 | > ```javascript
57 | > array.unshift(element);
58 | > ```
59 |
60 | ### 14. How do you remove the last element from an array?
61 | > You can remove the last element from an array using the `pop` method.
62 | > ```javascript
63 | > array.pop();
64 | > ```
65 |
66 | ### 15. How do you make a shallow copy of an array?
67 | > Making a shallow copy is easy with the `slice` method or the spread operator.
68 | > ```javascript
69 | > const copy = array.slice();
70 | > const copy = [...array];
71 | > ```
72 |
73 | ### 16. How do you turn an array-like object into a real array?
74 | > You can turn an array-like object into an actual array using `Array.from` or the spread operator.
75 | > ```javascript
76 | > const array = Array.from(arrayLike);
77 | > const array = [...arrayLike];
78 | > ```
79 |
80 | ## Strings
81 |
82 | ### 17. What are template literals and how do you use them?
83 | > Template literals allow for embedded expressions, multi-line strings, and string interpolation. They’re wrapped in backticks (`` ` ``) instead of regular quotes.
84 | > ```javascript
85 | > const name = 'John';
86 | > const message = `Hello, ${name}`;
87 | > ```
88 |
89 | ### 18. How do you convert a string to a number in JavaScript?
90 | > You can convert a string to a number using `parseInt(string)`, `parseFloat(string)`, `Number(string)`, or even the unary `+` operator.
91 |
92 | ## DOM Manipulation
93 |
94 | ### 19. What's the difference between `innerHTML` and `innerText`?
95 | > `innerHTML` returns all the content including HTML tags, while `innerText` only gives you the plain text without any HTML.
96 |
97 | ### 20. How can you prevent the default behavior in an event handler?
98 | > To prevent the default behavior, you just call `event.preventDefault()` inside the event handler.
99 |
100 | ## Events
101 |
102 | ### 21. What is event delegation?
103 | > Event delegation is a technique that lets you handle events for multiple elements with a single event listener, taking advantage of event bubbling in the DOM.
104 |
105 | ### 22. What is event bubbling?
106 | > Event bubbling is when an event starts from the target element and bubbles up through the parent elements up to the root of the document.
107 |
108 | ## Miscellaneous
109 |
110 | ### 23. What's `NaN` in JavaScript?
111 | > `NaN` stands for "Not-a-Number" and represents a value that comes from a mathematical operation that doesn't result in a valid number.
112 |
113 | ### 24. What does `"use strict"` do?
114 | > `"use strict"` turns on strict mode, which helps catch common coding mistakes and prevents certain actions. Makes your JavaScript safer and sometimes faster.
115 |
116 | ### 25. What is a polyfill?
117 | > A polyfill is code that adds a feature to browsers that don’t support that feature natively, ensuring compatibility across different browsers.
118 |
119 | ### 26. What is CORS?
120 | > CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources on a webpage to be requested from another domain outside the one the resource originated from.
121 |
122 | ### 27. What is hoisting in JavaScript?
123 | > Hoisting is JavaScript's behavior of moving declarations to the top of the current scope. So, variable declarations (with `var`) and function declarations are hoisted, but their initializations aren't.
124 |
125 | ### 28. How do you check if an object is empty in JavaScript?
126 | > You can check if an object is empty by checking the length of its keys:
127 | > ```javascript
128 | > Object.keys(obj).length === 0;
129 | > ```
130 |
131 | ### 29. What's the purpose of `JSON.stringify`?
132 | > `JSON.stringify` is used to convert a JavaScript object into a JSON string.
133 |
134 | ### 30. What's the purpose of `JSON.parse`?
135 | > `JSON.parse` is used to convert a JSON string back into a JavaScript object.
--------------------------------------------------------------------------------
/EN/02-intermediate.md:
--------------------------------------------------------------------------------
1 | # Intermediate JavaScript Questions
2 |
3 | ## Advanced Variables and Scopes
4 |
5 | ### 1. What's the difference between function scope and block scope?
6 | > Function scope means variables are accessible inside a function, but block scope means variables are only accessible within the block where they’re defined, like inside an `if` or `for` loop.
7 |
8 | ### 2. How does Hoisting work in JavaScript?
9 | > Hoisting means JavaScript moves declarations to the top of the current scope. Variable declarations (with `var`) and function declarations are hoisted, but not their initializations.
10 |
11 | ## Functions and Closures
12 |
13 | ### 3. What’s a Closure in JavaScript?
14 | > A Closure is a function that has access to its own lexical scope even when the function is executed outside of that scope.
15 |
16 | ### 4. What are arrow functions, and how are they different from regular functions?
17 | > Arrow functions have shorter syntax and bind `this` lexically, meaning from the surrounding scope. These functions don’t have their own `this`, `arguments`, `super`, or `new.target`.
18 |
19 | ### 5. What's the difference between `call`, `apply`, and `bind` methods?
20 | > The `call` method invokes a function with a specific `this` value and arguments one by one. `apply` also invokes a function with a specific `this` but takes an array of arguments. `bind` returns a new function with a specific `this` value and optional arguments.
21 |
22 | ## Objects and Prototypes
23 |
24 | ### 6. Explain the prototype chain in JavaScript.
25 | > The prototype chain is a series of links between objects created using `new` or `Object.create`. When a property on an object is accessed, the JavaScript engine traverses the prototype chain to find it.
26 |
27 | ### 7. What is the `__proto__` property?
28 | > The `__proto__` property is a reference to the prototype object of the current object. It's used to access the prototype of an object and is part of the prototype chain.
29 |
30 | ### 8. How can you create an object using a constructor function?
31 | > You can create an object by defining a function and using the `new` keyword to create instances:
32 | > ```javascript
33 | > function Person(name) {
34 | > this.name = name;
35 | > }
36 | > const john = new Person('John');
37 | > ```
38 |
39 | ## Asynchronous JavaScript
40 |
41 | ### 9. What is a promise, and how do you use it?
42 | > A promise is an object representing the eventual completion or failure of an asynchronous operation. You use `then` and `catch` methods to handle resolved and rejected states.
43 |
44 | ### 10. What does `async/await` mean in JavaScript?
45 | > `async` functions return a promise and allow you to use `await` inside them to pause execution until the promise is either resolved or rejected. This makes async code look and behave more like synchronous code.
46 |
47 | ### 11. What is the event loop in JavaScript?
48 | > The event loop is a mechanism that allows JavaScript to perform non-blocking operations by delegating tasks to the system kernel. It continuously checks the call stack and the callback queue, moving tasks to the call stack if it’s empty.
49 |
50 | ## Advanced Arrays and Objects
51 |
52 | ### 12. What's the difference between `map` and `forEach`?
53 | > The difference is that `map` creates a new array with the results of calling a provided function on every element in the original array. `forEach` executes a provided function once for each array element but doesn’t return a new array.
54 |
55 | ### 13. How do you create a deep copy of an object?
56 | > To create a deep copy, you can use a recursive function or use JSON methods:
57 | > ```javascript
58 | > const deepCopy = JSON.parse(JSON.stringify(original));
59 | > ```
60 |
61 | ### 14. What is the spread operator, and how do you use it?
62 | > The spread operator (`...`) allows an iterable, like an array or string, to be expanded.
63 | > ```javascript
64 | > const arr = [1, 2, 3];
65 | > const newArr = [...arr, 4, 5];
66 | > ```
67 |
68 | ### 15. What does destructuring mean in JavaScript?
69 | > Destructuring is a syntax that lets you unpack values from arrays or properties from objects into separate variables.
70 | > ```javascript
71 | > const { a, b } = { a: 1, b: 2 };
72 | > const [x, y] = [1, 2];
73 | > ```
74 |
75 | ## DOM Manipulation and Events
76 |
77 | ### 16. Explain event delegation.
78 | > Event delegation allows you to use a single event listener to manage similar events on multiple elements by leveraging event propagation in the DOM tree.
79 |
80 | ### 17. How do you create a custom event in JavaScript?
81 | > To create a custom event, you can use the `CustomEvent` constructor:
82 | > ```javascript
83 | > const event = new CustomEvent('eventName', { detail: { key: 'value' } });
84 | > ```
85 |
86 | ### 18. What's the difference between `window.onload` and `document.ready`?
87 | > `window.onload` triggers when the whole page has fully loaded, including all dependent resources like stylesheets and images. `document.ready` triggers when the DOM is fully loaded, meaning the document structure is ready, but external resources might still be loading.
88 |
89 | ## Error Handling
90 |
91 | ### 19. How do you handle errors in a promise chain?
92 | > To handle errors in a promise chain, you can use the `catch` method.
93 |
94 | ## Modules
95 |
96 | ### 20. What is a JavaScript module?
97 | > A JavaScript module is a file that allows code to be imported and exported between different parts of an application using `import` and `export` statements. Modules help in organizing and encapsulating code.
98 |
99 | ## Miscellaneous Topics
100 |
101 | ### 21. What is a higher-order function in JavaScript?
102 | > Higher-order functions are functions that can take other functions as arguments or return functions as results. Examples include `map`, `filter`, and `reduce`.
103 |
104 | ### 22. What does immutability mean in JavaScript?
105 | > Immutability refers to the inability to change an object or data structure once it has been created. Instead of modifying the existing object, new objects with updated values are created.
106 |
107 | ### 23. What is currying in JavaScript?
108 | > Currying is the process of transforming a function that takes multiple arguments into a series of functions that each take a single argument. This allows partial application of functions.
109 |
110 | ### 24. What is a Polyfill?
111 | > A polyfill is code that implements a feature on web browsers that don’t natively support that feature, ensuring compatibility across different browsers.
112 |
113 | ### 25. What's the purpose of `Object.keys`?
114 | > `Object.keys` returns an array of a given object's own enumerable property names.
115 |
116 | ### 26. What's the purpose of `Object.values`?
117 | > `Object.values` returns an array of a given object's own enumerable property values.
118 |
119 | ### 27. What's the purpose of `Object.entries`?
120 | > `Object.entries` converts an object into an array of key-value pairs.
121 |
122 | ### 28. What’s the difference between `slice` and `splice` methods?
123 | > `slice` returns a shallow copy of a portion of an array into a new array. `splice` changes the contents of an array by removing or replacing existing elements and/or adding new elements.
--------------------------------------------------------------------------------
/EN/03-advance.md:
--------------------------------------------------------------------------------
1 | # Advanced JavaScript Questions
2 |
3 | ## JavaScript Fundamentals
4 |
5 | ### 1. What is a JavaScript engine?
6 | > A JavaScript engine is a program that executes JavaScript code. Examples include Google’s V8, Mozilla’s SpiderMonkey, and Microsoft’s Chakra.
7 |
8 | ### 2. Explain the concept of execution context and call stack in JavaScript.
9 | > To explain, the execution context is the environment where JavaScript code is executed. This environment includes `this` binding, variables, objects, and functions. The call stack is a data structure called a stack that keeps track of function calls and helps the JavaScript engine know where to return after executing each function.
10 |
11 | ### 3. What is the event loop, and how does it work?
12 | > The event loop allows JavaScript to perform non-blocking operations by delegating tasks to the system kernel whenever possible. It continuously checks the call stack and the callback queue and adds the first task from the queue to the call stack if the stack is empty.
13 |
14 | ## Advanced Functions and Closures
15 |
16 | ### 4. Explain the concept of higher-order functions and give an example.
17 | > Higher-order functions are functions that can take other functions as arguments or return functions as results. Example:
18 | > ```javascript
19 | > function higherOrder(fn) {
20 | > // Returns a new function that takes a value and applies the input function to it
21 | > return function(value) {
22 | > return fn(value);
23 | > };
24 | > }
25 | > // Create a function called 'double' that doubles its input using the higherOrder function
26 | > const double = higherOrder((x) => x * 2);
27 | > console.log(double(5)); // 10
28 | > ```
29 |
30 | ### 5. What are generators, and how do you use them?
31 | > Generators are functions that can be paused in the middle and then resumed later. To define a generator, use the `function*` syntax and the `yield` keyword. Example:
32 | > ```javascript
33 | > function* generator() {
34 | > yield 1; // Pause and return 1
35 | > yield 2; // Pause and return 2
36 | > yield 3; // Pause and return 3
37 | > }
38 | > const gen = generator();
39 | > console.log(gen.next().value); // 1
40 | > console.log(gen.next().value); // 2
41 | > console.log(gen.next().value); // 3
42 | > ```
43 |
44 | ### 6. Explain the concept of memoization in JavaScript.
45 | > Memoization is an optimization technique used to speed up function calls by caching the results of expensive function calls and returning the cached result when the same inputs occur again.
46 |
47 | ## Objects and Prototypes
48 |
49 | ### 7. What's the difference between `Object.create()` and `Object.assign()`?
50 | > To explain, `Object.create()` creates a new object with a specified prototype and properties, while `Object.assign()` copies properties from one or more source objects to a target object.
51 |
52 | ### 8. What is a `Proxy` object, and how do you use it?
53 | > A `Proxy` object is used to define custom behavior for fundamental operations (like property lookup, assignment, enumeration, and function invocation). Example:
54 | > ```javascript
55 | > const target = {};
56 | > const handler = {
57 | > get: function(obj, prop) {
58 | > // Return the property's value if it exists, otherwise return 42
59 | > return prop in obj ? obj[prop] : 42;
60 | > }
61 | > };
62 | > const proxy = new Proxy(target, handler);
63 | > console.log(proxy.answer); // 42
64 | > ```
65 |
66 | ## Asynchrony and Performance Optimization
67 |
68 | ### 9. What's the difference between microtasks and macrotasks in the event loop?
69 | > To explain, microtasks are tasks that execute after the current operation completes but before rendering. Examples include promises and `MutationObserver` callbacks. On the other hand, macrotasks are tasks that execute after rendering, such as `setTimeout`, `setInterval`, and I/O tasks.
70 |
71 | ### 10. What are Web Workers, and how do they improve performance?
72 | > Web Workers allow you to run JavaScript code in the background, on a separate thread from the main thread. This makes it possible to perform heavy computations without blocking the user interface (UI).
73 |
74 | ## Advanced DOM Manipulation
75 |
76 | ### 11. What is Shadow DOM, and how do you use it?
77 | > To explain, Shadow DOM is a web standard that allows you to encapsulate a DOM tree and CSS styles, hiding and separating them from the main document's DOM. This is useful for creating web components.
78 |
79 | ### 12. How can you effectively update the DOM to minimize reflows and repaints?
80 | > To effectively update the DOM, batch DOM changes together, use `DocumentFragment`, minimize layout thrashing, and use `requestAnimationFrame` for animations.
81 |
82 | ## Memory Management
83 |
84 | ### 13. What is garbage collection in JavaScript?
85 | > Garbage collection is the process that automatically frees up memory that's no longer in use. This means objects that are no longer needed or accessible are removed.
86 |
87 | ### 14. What are memory leaks, and how can you prevent them?
88 | > Memory leaks occur when memory that has been allocated to something is not properly freed, causing memory usage to increase over time. To prevent this, you should remove references to objects that are no longer needed, avoid excessive use of global variables, and use tools like Chrome DevTools to monitor memory usage.
89 |
90 | ## Advanced Error Handling
91 |
92 | ### 15. What are custom errors, and how can you create them in JavaScript?
93 | > Custom errors are user-defined errors that inherit from the built-in `Error` class. Example:
94 | > ```javascript
95 | > class CustomError extends Error {
96 | > constructor(message) {
97 | > super(message);
98 | > this.name = 'CustomError';
99 | > }
100 | > }
101 | > throw new CustomError('This is a custom error');
102 | > ```
103 |
104 | ## Modules and Build Tools
105 |
106 | ### 16. What is the difference between ES6 modules and CommonJS modules?
107 | > ES6 modules use `import` and `export` statements and are statically analyzed, allowing for tree shaking. CommonJS modules use `require` and `module.exports` and are dynamically loaded.
108 |
109 | ### 17. What are bundlers like Webpack, and why are they used?
110 | > Bundlers like Webpack are tools that transform JavaScript modules into one or more optimized files for the browser. These tools help manage dependencies, perform code splitting, and optimize output for production.
111 |
112 | ## Security
113 |
114 | ### 18. What are the most common security vulnerabilities in JavaScript, and how can you mitigate them?
115 | > Common vulnerabilities include XSS (Cross-Site Scripting), CSRF (Cross-Site Request Forgery), and code injection. You can mitigate these by validating and sanitizing user inputs, using Content Security Policy (CSP), and implementing proper authentication and authorization mechanisms.
116 |
117 | ## Advanced API and Browser Features
118 |
119 | ### 19. What are service workers, and how do they enable Progressive Web Apps (PWAs)?
120 | > Service workers are scripts that run in the background and provide features like caching, push notifications, and background sync. These capabilities allow for offline usage and improved performance for Progressive Web Apps (PWAs).
121 |
122 | ### 20. Explain the use of IndexedDB in web applications.
123 | > To explain, IndexedDB is a low-level API for storing large amounts of structured data in the browser. It provides asynchronous access to data and supports transactions, making it suitable for offline storage and complex data needs.
124 |
125 | ### 21. What is WebAssembly, and how does it interact with JavaScript?
126 | > WebAssembly is a binary format for a stack-based virtual machine designed for compiling high-level languages like C, C++, and Rust. It allows code to run at near-native speed in the browser and can interact with JavaScript through APIs.
127 |
128 | ## Advanced Patterns and Practices
129 |
130 | ### 22. Explain the concept of functional programming and how it relates to JavaScript.
131 | > Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. JavaScript supports functional programming through first-class functions, higher-order functions, and methods like `map`, `reduce`, and `filter`.
132 |
133 | ### 23. What is the observer pattern, and how is it implemented in JavaScript?
134 | > The observer pattern is a design pattern where an object (subject) maintains a list of dependencies (observers) and notifies them of state changes. This pattern can be implemented using event listeners or libraries like RxJS for reactive programming.
135 |
136 | ### 24. How can you implement debouncing and throttling in JavaScript?
137 | > To explain, debouncing ensures that a function is only executed after a specified delay has passed since the last invocation. Throttling ensures that a function is executed at most once in a specified time period. Example:
138 | > ```javascript
139 | > function debounce(fn, delay) {
140 | > let timer;
141 | > return function(...args) {
142 | > // Clear the previous timer if it exists, and set a new timer
143 | > clearTimeout(timer);
144 | > timer = setTimeout(() => fn.apply(this, args), delay);
145 | > };
146 | > }
147 | > function throttle(fn, limit) {
148 | > let lastCall = 0;
149 | > return function(...args) {
150 | > const now = Date.now();
151 | > // If enough time has passed since the last call, execute the function
152 | > if (now - lastCall >= limit) {
153 | > lastCall = now;
154 | > fn.apply(this, args);
155 | > }
156 | > };
157 | > }
158 | > ```
159 |
160 | ### 25. What is the concept of duck typing in JavaScript?
161 | > To explain, Duck typing is a concept where the usability of an object is determined based on the presence of certain methods and properties rather than its actual type. It's often described with the phrase
162 |
163 | , "If it looks like a duck and quacks like a duck, then it's a duck."
164 |
165 | ### 26. What is tail call optimization, and how does it work in JavaScript?
166 | > Tail call optimization is a feature in some JavaScript engines that optimizes recursive calls that are in tail position (the last operation in a function). This results in more efficient memory usage and can prevent stack overflow errors.
--------------------------------------------------------------------------------
/EN/04-ES5-2009.md:
--------------------------------------------------------------------------------
1 | # ES5-2009 Questions
2 |
3 | ## "use strict" in JavaScript
4 |
5 | ### 1. Why do we use "use strict," and what are its benefits?
6 | Using "use strict" makes JavaScript code run in "strict mode." This mode helps you write cleaner code with fewer errors, like preventing the use of undeclared variables. "use strict" is just a string expression, and if the browser doesn't recognize it, it won't throw an error.
7 |
8 | ```javascript
9 | "use strict";
10 | x = 3.14; // ReferenceError: x is not defined
11 | ```
12 |
13 | In this example, because we used "use strict," if a variable is defined without `var`, `let`, or `const`, it throws an error. This helps prevent common mistakes.
14 |
15 | ## Accessing String Characters Using Indexes
16 |
17 | ### 2. How can we access characters of a string using indexes?
18 | Besides the `charAt` method, which was used to access string characters, you can also access string characters using indexes, similar to how you access elements in an array.
19 |
20 | ```javascript
21 | var str = "HELLO WORLD";
22 | console.log(str.charAt(0)); // 'H'
23 | console.log(str[0]); // 'H'
24 | ```
25 |
26 | This method of accessing characters might not work correctly in some older browsers, but it works fine in modern browsers.
27 |
28 | ## Multi-line Strings
29 |
30 | ### 3. How can we write multi-line strings?
31 | You can create multi-line strings using a backslash `\`.
32 |
33 | ```javascript
34 | var str = "Hello \
35 | Dolly!";
36 | ```
37 |
38 | This method might not work properly in all browsers. A safer way to write multi-line strings is by using string concatenation.
39 |
40 | ```javascript
41 | var str = "Hello " +
42 | "Dolly!";
43 | ```
44 |
45 | ## Using Reserved Words as Property Names
46 |
47 | ### 4. Can we use reserved words as property names?
48 | Yes, in ES5, you are allowed to use reserved words as property names.
49 |
50 | ```javascript
51 | var obj = {name: "John", new: "yes"};
52 | ```
53 |
54 | This feature lets you use more words as property names.
55 |
56 | ## String.trim Method
57 |
58 | ### 5. How does the trim method work?
59 | The `trim` method removes whitespace from both sides of a string.
60 |
61 | ```javascript
62 | var str = " Hello World! ";
63 | console.log(str.trim()); // 'Hello World!'
64 | ```
65 |
66 | This method helps you remove unnecessary whitespace from strings.
67 |
68 | ## Array.isArray Method
69 |
70 | ### 6. How can we check if an object is an array?
71 | The `Array.isArray` method checks whether an object is an array or not.
72 |
73 | ```javascript
74 | var fruits = ["Banana", "Orange", "Apple", "Mango"];
75 | console.log(Array.isArray(fruits)); // true
76 | ```
77 |
78 | This method is particularly useful when you need to know the type of data you are working with.
79 |
80 | ## Array.forEach Method
81 |
82 | ### 7. How does the forEach method work?
83 | The `forEach` method calls a function for each element in an array.
84 |
85 | ```javascript
86 | var txt = "";
87 | var numbers = [45, 4, 9, 16, 25];
88 | numbers.forEach(function(value) {
89 | txt += value + "
";
90 | });
91 | console.log(txt);
92 | ```
93 |
94 | This method helps you easily loop through array elements and perform operations on each element.
95 |
96 | ## Array.map Method
97 |
98 | ### 8. How does the map method work, and what is its use?
99 | The `map` method executes a function for each element in an array and returns a new array with the results.
100 |
101 | ```javascript
102 | var numbers1 = [45, 4, 9, 16, 25];
103 | var numbers2 = numbers1.map(function(value) {
104 | return value * 2;
105 | });
106 | console.log(numbers2); // [90, 8, 18, 32, 50]
107 | ```
108 |
109 | This method is useful when you need to create a new array with modifications to the elements of the original array.
110 |
111 | ## Array.filter Method
112 |
113 | ### 9. How does the filter method work, and what is its use?
114 | The `filter` method creates a new array with all elements that pass the test implemented by the provided function.
115 |
116 | ```javascript
117 | var numbers = [45, 4, 9, 16, 25];
118 | var over18 = numbers.filter(function(value) {
119 | return value > 18;
120 | });
121 | console.log(over18); // [45, 25]
122 | ```
123 |
124 | This method helps you create a new array that only includes elements that meet a specific condition.
125 |
126 | ## Array.reduce Method
127 |
128 | ### 10. How does the reduce method work, and what is its use?
129 | The `reduce` method reduces all elements in an array to a single value.
130 |
131 | ```javascript
132 | var numbers = [45, 4, 9, 16, 25];
133 | var sum = numbers.reduce(function(total, value) {
134 | return total + value;
135 | });
136 | console.log(sum); // 99
137 | ```
138 |
139 | This method helps you calculate values like the total sum of all elements.
140 |
141 | ## Array.reduceRight Method
142 |
143 | ### 11. How does the reduceRight method work, and how is it different from reduce?
144 | The `reduceRight` method works similarly to `reduce`, but it processes the array elements from right to left.
145 |
146 | ```javascript
147 | var numbers = [45, 4, 9, 16, 25];
148 | var sum = numbers.reduceRight(function(total, value) {
149 | return total + value;
150 | });
151 | console.log(sum); // 99
152 | ```
153 |
154 | This method is useful when you need to perform a reduction operation starting from the end of the array.
155 |
156 | ## Array.every Method
157 |
158 | ### 12. How does the every method work, and what is its use?
159 | The `every` method checks whether all elements in an array satisfy a specific condition.
160 |
161 | ```javascript
162 | var numbers = [45, 4, 9, 16, 25];
163 | var allOver18 = numbers.every(function(value) {
164 | return value > 18;
165 | });
166 | console.log(allOver18); // false
167 | ```
168 |
169 | This method is useful when you need to ensure all elements meet a specific condition.
170 |
171 | ## Array.some Method
172 |
173 | ### 13. How does the some method work, and what is its use?
174 | The `some` method checks whether at least one element in an array meets a specific condition.
175 |
176 | ```javascript
177 | var numbers = [45, 4, 9, 16, 25];
178 | var someOver18 = numbers.some(function(value) {
179 | return value > 18;
180 | });
181 | console.log(someOver18); // true
182 | ```
183 |
184 | This method is especially useful when you need to check if at least one element meets a specific condition.
185 |
186 | ## Array.indexOf Method
187 |
188 | ### 14. How can we find the position of an element in an array using indexOf?
189 | The `indexOf` method returns the position of the first matching element in an array.
190 |
191 | ```javascript
192 | var fruits = ["Apple", "Orange", "Apple", "Mango"];
193 | var index = fruits.indexOf("Apple");
194 | console.log(index); // 0
195 | ```
196 |
197 | This method is handy when you need to find the position of a specific element.
198 |
199 | ## Array.lastIndexOf Method
200 |
201 | ### 15. How does the lastIndexOf method work, and how is it different from indexOf?
202 | The `lastIndexOf` method works similarly to `indexOf`, but it starts searching from the end of the array.
203 |
204 | ```javascript
205 | var fruits = ["Apple", "Orange", "Apple", "Mango"];
206 | var index = fruits.lastIndexOf("Apple");
207 | console.log(index); // 2
208 | ```
209 |
210 | This method is useful when you need to find the position of the last matching element.
211 |
212 | ## JSON.parse Method
213 |
214 | ### 16. How does the JSON.parse method work, and what is its use?
215 | The `JSON.parse` method is used to convert a JSON text string into a JavaScript object.
216 |
217 | ```javascript
218 | var jsonString = '{"name":"John", "age":30, "city":"New York"}';
219 | var obj = JSON.parse(jsonString);
220 | console.log(obj.name); // 'John'
221 | ```
222 |
223 | This method is particularly useful when you receive JSON data from a server and need to work with it as a JavaScript object.
224 |
225 | ## JSON.stringify Method
226 |
227 | ### 17. How does the JSON.stringify method work, and what is its use?
228 | The `JSON.stringify` method is used to convert a JavaScript object into a JSON string.
229 |
230 | ```javascript
231 | var obj = {name: "John", age: 30, city: "New York"};
232 | var jsonString = JSON.stringify(obj);
233 | console.log(jsonString); // '{"name":"John","age":30,"city":"New York"}'
234 | ```
235 |
236 | This method is particularly useful when you need to send data to a server as a JSON string.
237 |
238 | ## Date.now Method
239 |
240 | ### 18. How does the Date.now method work, and what is its use?
241 | The `Date.now` method returns the number of milliseconds since January 1, 1970.
242 |
243 | ```javascript
244 | var timeInMs = Date.now();
245 | console.log(timeInMs);
246 | ```
247 |
248 | This method is useful for time and date calculations, such as calculating how long an operation took.
249 |
250 | ## Date.toISOString Method
251 |
252 | ### 19. How does the toISOString method work, and what is its use?
253 | The `toISOString` method is used to convert a `Date` object to a string in the standard ISO format.
254 |
255 | ```javascript
256 | var d = new Date();
257 | console.log(d.toISOString());
258 | ```
259 |
260 | This method is useful when you need to convert a date to a portable and standard format.
261 |
262 | ## Date.toJSON Method
263 |
264 | ### 20. How does the toJSON method work, and what is its use?
265 | The `toJSON` method converts a `Date` object to a string in JSON format. The JSON format for
266 |
267 | dates is similar to the ISO-8601 standard.
268 |
269 | ```javascript
270 | var d = new Date();
271 | console.log(d.toJSON());
272 | ```
273 |
274 | This method is particularly useful when you need to prepare a date in JSON format for data transfer.
275 |
276 | ## Using Getters and Setters
277 |
278 | ### 21. How do getters and setters work, and what are they used for?
279 | ES5 allows you to define object methods that look like getting or setting a property.
280 |
281 | ```javascript
282 | var person = {
283 | firstName: "John",
284 | lastName: "Doe",
285 | get fullName() {
286 | return this.firstName + " " + this.lastName;
287 | }
288 | };
289 |
290 | console.log(person.fullName); // 'John Doe'
291 | ```
292 |
293 | This example creates a getter for the `fullName` property that returns the full name.
294 |
295 | ## Object.defineProperty Method
296 |
297 | ### 22. How does the Object.defineProperty method work, and what is its use?
298 | The `Object.defineProperty` method allows you to define or modify a property on an object.
299 |
300 | ```javascript
301 | const person = {
302 | firstName: "John",
303 | lastName : "Doe",
304 | };
305 |
306 | Object.defineProperty(person, "language", {
307 | value: "EN",
308 | writable: true,
309 | enumerable: true,
310 | configurable: true
311 | });
312 |
313 | console.log(person.language); // 'EN'
314 | ```
315 |
316 | This method is useful when you need more control over an object's properties, such as specifying whether a property is writable or enumerable.
317 |
318 | ## Object.create Method
319 |
320 | ### 23. How does the Object.create method work, and what is its use?
321 | The `Object.create` method is used to create a new object from an existing object.
322 |
323 | ```javascript
324 | const person = {
325 | firstName: "John",
326 | lastName: "Doe"
327 | };
328 |
329 | const man = Object.create(person);
330 | man.firstName = "Peter";
331 | console.log(man.firstName); // 'Peter'
332 | console.log(man.lastName); // 'Doe'
333 | ```
334 |
335 | This method is particularly useful when you need to create a new object from an existing prototype.
336 |
337 | ## Object.keys Method
338 |
339 | ### 24. How does the Object.keys method work, and what is its use?
340 | The `Object.keys` method returns an array containing the keys of an object.
341 |
342 | ```javascript
343 | const person = {
344 | firstName: "John",
345 | lastName: "Doe",
346 | age: 50,
347 | eyeColor: "blue"
348 | };
349 |
350 | const keys = Object.keys(person);
351 | console.log(keys); // ['firstName', 'lastName', 'age', 'eyeColor']
352 | ```
353 |
354 | This method is useful when you need to access the keys of an object.
355 |
356 | ## Function.bind Method
357 |
358 | ### 25. How does the bind method work, and what is its use?
359 | The `bind` method allows an object to borrow a method from another object.
360 |
361 | ```javascript
362 | const person = {
363 | firstName: "John",
364 | lastName: "Doe",
365 | fullName: function() {
366 | return this.firstName + " " + this.lastName;
367 | }
368 | };
369 |
370 | const member = {
371 | firstName: "Hege",
372 | lastName: "Nilsen",
373 | };
374 |
375 | let fullName = person.fullName.bind(member);
376 | console.log(fullName()); // 'Hege Nilsen'
377 | ```
378 |
379 | This method is particularly useful when you need to bind a method to a specific object.
380 |
381 | ## Trailing Commas
382 |
383 | ### 26. How can we use trailing commas in object and array definitions?
384 | ES5 allows you to use trailing commas in object and array definitions.
385 |
386 | ```javascript
387 | var person = {
388 | firstName: "John",
389 | lastName: "Doe",
390 | age: 46,
391 | };
392 |
393 | var points = [
394 | 1,
395 | 5,
396 | 10,
397 | 25,
398 | 40,
399 | 100,
400 | ];
401 | ```
402 |
403 | This feature helps improve readability and keeps the code cleaner, but keep in mind that JSON does not accept trailing commas.
--------------------------------------------------------------------------------
/EN/06-ES7-2016.md:
--------------------------------------------------------------------------------
1 | # ES7-2016 Questions
2 |
3 | ## Exponentiation Operator in JavaScript
4 |
5 | ### 1. How does the Exponentiation Operator (`**`) work in JavaScript, and what are its uses?
6 | In ES7, a new operator called `**` was introduced, which lets you easily raise a number to the power of another number. This operator is a simpler and more straightforward replacement for the `Math.pow` function, making it easier to write code related to powers.
7 |
8 | ```javascript
9 | const result = 2 ** 3; // 2 raised to the power of 3
10 | console.log(result); // 8
11 | ```
12 |
13 | In this example, `2 ** 3` is calculated, and the result is 8. This operator makes writing exponents in JavaScript easier and the code more concise. This feature is particularly efficient in complex mathematical calculations that involve multiple exponents.
14 |
15 | ## Exponentiation Assignment Operator
16 |
17 | ### 2. How does the Exponentiation Assignment Operator (`**=`) work, and what are its advantages?
18 | Along with the introduction of the `**` operator in ES7, the `**=` operator was also added, allowing you to raise a number to the power of another number and assign the result to the same variable. This operator works just like `+=` or `*=`, making code writing even simpler than before.
19 |
20 | ```javascript
21 | let num = 4;
22 | num **= 2; // 4 raised to the power of 2
23 | console.log(num); // 16
24 | ```
25 |
26 | In this example, the initial value of `num` is 4, and after using `**=`, this value changes to 16 because 4 to the power of 2 is calculated. This operator is very useful and concise when you want to directly assign the result of an exponentiation operation to the same variable.
27 |
28 | ## `Array.includes` Method
29 |
30 | ### 3. What is the `Array.includes` method in JavaScript, and how is it used?
31 | In ES7, a new method called `includes` was added to arrays, allowing you to easily check whether a specific element is in an array. Unlike `indexOf`, which returns the index, this method returns a Boolean value (true or false), making it much quicker and easier to check if an element exists.
32 |
33 | ```javascript
34 | const arr = [1, 2, 3, 4];
35 | console.log(arr.includes(2)); // true
36 | console.log(arr.includes(5)); // false
37 | ```
38 |
39 | In this example, `arr.includes(2)` returns `true` because the number 2 is present in the array, while `arr.includes(5)` returns `false` because the number 5 is not in the array. This method is very helpful when you need a quick and simple check to see if an element exists in an array, making the code cleaner and more readable.
--------------------------------------------------------------------------------
/EN/07-ES8-2017.md:
--------------------------------------------------------------------------------
1 | # ES8-2017 Questions
2 |
3 | ## String Padding in JavaScript
4 |
5 | ### 1. How does String Padding work in JavaScript, and what are its uses?
6 | In ES8, two new methods, `padStart` and `padEnd`, were added to strings that let you pad a string from the beginning or the end with other characters to reach a specified length. These methods are especially useful when you want to format a string in a particular way, like adding leading zeros to a number for better display.
7 |
8 | ```javascript
9 | const str = '5';
10 | console.log(str.padStart(3, '0')); // '005' - padding from the start
11 | console.log(str.padEnd(3, '0')); // '500' - padding from the end
12 | ```
13 |
14 | In this example, `padStart` pads the string `5` from the start with `0` to reach a length of 3, and `padEnd` does the same from the end. This feature is useful for situations where you need specific formatting, such as displaying fixed-length numbers or product codes.
15 |
16 | ## `Object.entries` Method
17 |
18 | ### 2. What does the `Object.entries` method do in JavaScript, and how does it work?
19 | The `Object.entries` method was introduced in ES8, allowing you to convert an object into an array of key-value pairs. This method returns all the enumerable properties of an object as an array of arrays, each containing a key and a value.
20 |
21 | ```javascript
22 | const obj = { a: 1, b: 2, c: 3 };
23 | console.log(Object.entries(obj)); // [['a', 1], ['b', 2], ['c', 3]]
24 | ```
25 |
26 | In this example, `Object.entries` converts the properties of the object `obj` into an array of key-value pairs. This method is especially useful when you need to convert an object into a more processable format, like arrays.
27 |
28 | ## `Object.values` Method
29 |
30 | ### 3. What are the benefits of the `Object.values` method, and how is it used?
31 | The `Object.values` method was added in ES8, allowing you to return only the values of an object's properties as an array. This method works similarly to `Object.entries` but returns only the values instead of key-value pairs.
32 |
33 | ```javascript
34 | const obj = { a: 1, b: 2, c: 3 };
35 | console.log(Object.values(obj)); // [1, 2, 3]
36 | ```
37 |
38 | In this example, `Object.values` returns the values of the properties of the object `obj` as an array. This method is useful when you only need the values and not the keys, such as when you want to perform a specific operation on all the values of an object.
39 |
40 | ## `async/await` Syntax
41 |
42 | ### 4. How does the `async/await` syntax work in JavaScript, and what are its advantages?
43 | In ES8, a new syntax called `async/await` was introduced, making it much simpler and easier to understand when working with asynchronous code. Using `async/await`, you can write code that looks like it's synchronous, but it actually runs asynchronously. Functions defined with `async` return a `Promise`, and `await` makes the code wait until that `Promise` is either resolved or rejected.
44 |
45 | ```javascript
46 | async function fetchData() {
47 | const response = await fetch('https://api.example.com/data');
48 | const data = await response.json();
49 | return data;
50 | }
51 |
52 | fetchData().then(data => console.log(data));
53 | ```
54 |
55 | In this example, `fetchData` is an asynchronous function that waits with `await` until the data is returned from the API and then processes it. This syntax helps you write asynchronous code in a way that is easier to read and maintain without needing to use long chains of `then`.
56 |
57 | ## Trailing Commas in Functions
58 |
59 | ### 5. What is the use of trailing commas in function parameter lists and function calls?
60 | In ES8, the ability to use trailing commas in function parameter lists and function calls was introduced. This feature is especially useful when you want to modify your code over time because you don't need to change the previous line when adding new parameters. It helps with code readability and makes comparing code changes easier.
61 |
62 | ```javascript
63 | function sum(a, b, c,) {
64 | return a + b + c;
65 | }
66 | console.log(sum(1, 2, 3,)); // 6
67 | ```
68 |
69 | In this example, a trailing comma is used at the end of the parameter list and arguments. These commas don't affect code execution but help keep your code cleaner and make managing changes easier.
70 |
71 | ## `Object.getOwnPropertyDescriptors` Method
72 |
73 | ### 6. What information does the `Object.getOwnPropertyDescriptors` method provide, and how can it be used?
74 | The `Object.getOwnPropertyDescriptors` method was introduced in ES8, allowing you to return all property descriptors of an object as a new object. These descriptors include information like whether the property is writable, enumerable, and configurable.
75 |
76 | ```javascript
77 | const obj = { a: 1, get b() { return 2; } };
78 | console.log(Object.getOwnPropertyDescriptors(obj));
79 | /* Output:
80 | {
81 | a: { value: 1, writable: true, enumerable: true, configurable: true },
82 | b: {
83 | get: [Function: get b],
84 | set: undefined,
85 | enumerable: true,
86 | configurable: true
87 | }
88 | }
89 | */
90 | ```
91 |
92 | In this example, `Object.getOwnPropertyDescriptors` returns all the information about the properties of the object `obj`, including whether those properties are changeable. This method is very useful when you need to know the complete details of an object's properties. This information can help you manage objects more advanced, such as creating more precise copies or making controlled changes to properties.
--------------------------------------------------------------------------------
/EN/08-ES9-2018.md:
--------------------------------------------------------------------------------
1 | # ES9-2018 Questions
2 |
3 | ## Asynchronous Iteration Loop
4 |
5 | ### 1. How can you use `for-await-of` to iterate over asynchronous data, and what are the benefits of this feature?
6 | In ES9, a new feature called `for-await-of` was introduced, allowing you to iterate over data that is produced asynchronously. This loop works similarly to `for-of`, except it's specifically designed for working with `Promises`. This feature is particularly useful when you need to wait for several asynchronous operations to complete, like fetching data from an API or database, and you want to process the results one by one.
7 |
8 | ```javascript
9 | async function* asyncGenerator() {
10 | yield 'Hello';
11 | yield 'World';
12 | }
13 |
14 | (async () => {
15 | for await (const value of asyncGenerator()) {
16 | console.log(value); // Logs each value
17 | }
18 | // Output:
19 | // Hello
20 | // World
21 | })();
22 | ```
23 |
24 | In this example, an asynchronous function (`asyncGenerator`) is used to generate data. Then, `for-await-of` retrieves and prints the data one by one. This feature lets you efficiently manage asynchronous data and ensures each piece of data is fully received before processing it.
25 |
26 | ## `Promise.prototype.finally` Method
27 |
28 | ### 2. How can the `finally` method improve `Promise` management, and what are its use cases?
29 | The `finally` method was added to `Promises` to ensure that a piece of code runs after a `Promise` is completed, whether it was successful or failed. This method is particularly useful in scenarios where you need to perform a specific task, such as cleanup or updating the user interface, after an operation finishes, regardless of its outcome.
30 |
31 | ```javascript
32 | fetch('https://api.example.com/data')
33 | .then(response => response.json())
34 | .catch(error => console.error('Error:', error))
35 | .finally(() => console.log('Request finished')); // This code always runs
36 | ```
37 |
38 | In this example, `finally` ensures that the message "Request finished" is displayed after the request is completed, whether it was successful or not. This feature helps you ensure that final tasks, such as hiding a loading indicator or releasing resources, are always performed.
39 |
40 | ## Object Rest Properties
41 |
42 | ### 3. How can you use `Object Rest` properties to extract specific parts of an object, and what are the use cases for this feature?
43 | In ES9, `Rest` properties, previously used with arrays, were extended to objects. This feature allows you to extract certain properties from an object while keeping the remaining properties in a new object. This capability is especially useful when you want to remove unnecessary or less important parts from an object and keep only the properties you need.
44 |
45 | ```javascript
46 | const obj = { a: 1, b: 2, c: 3 };
47 | const { a, ...rest } = obj;
48 |
49 | console.log(rest); // { b: 2, c: 3 }
50 | ```
51 |
52 | In this example, the property `a` is separated from the original object, and the remaining properties are stored in a new object called `rest`. This feature helps you easily separate extra data from objects and keep only the information you need.
53 |
54 | ## New RegExp Features
55 |
56 | ### 4. What new features were introduced for `RegExp`, and how can they improve working with regular expressions?
57 | In ES9, several new features were added to `RegExp` to make working with regular expressions simpler and more powerful. These features include named capture groups, lookbehind assertions, and the `s` flag, also known as dotAll. These capabilities allow you to create and manage more complex patterns with greater flexibility.
58 |
59 | - **Named Capture Groups:** Allow you to assign a name to matched groups for easier access.
60 | - **Lookbehind Assertions:** Enable you to match a pattern only if it is preceded by a specific pattern.
61 | - **`s` flag (dotAll):** Makes the dot (`.`) in regular expressions match any character, including newline characters.
62 |
63 | ```javascript
64 | // Named Capture Groups
65 | const regExp = /(?\d{4})-(?\d{2})-(?\d{2})/;
66 | const match = regExp.exec('2024-08-12');
67 | console.log(match.groups.year); // 2024
68 |
69 | // Lookbehind Assertions
70 | const lookbehindRegExp = /(?<=\$)\d+/;
71 | console.log(lookbehindRegExp.exec('$100')[0]); // 100
72 |
73 | // dotAll flag
74 | const dotAllRegExp = /foo.bar/s;
75 | console.log(dotAllRegExp.test('foo\nbar')); // true
76 | ```
77 |
78 | In these examples, new `RegExp` features like named capture groups, lookbehind assertions, and the `s` flag are used to create more robust and flexible regular expressions. These features help you match more complex patterns and process data more precisely.
79 |
80 | ## Shared Memory in JavaScript
81 |
82 | ### 5. How does shared memory work in JavaScript, and what are its applications?
83 | In ES9, support for shared memory using `SharedArrayBuffer` and atomic operations with `Atomics` was added to JavaScript. These features allow you to safely share data between multiple threads or web workers and perform operations that execute atomically without interruption. This capability is particularly useful in applications that require parallel processing or when you want to prevent data races.
84 |
85 | ```javascript
86 | const buffer = new SharedArrayBuffer(1024); // Create a shared buffer
87 | const uint8 = new Uint8Array(buffer); // Create a typed array to access the buffer
88 |
89 | Atomics.add(uint8, 0, 10); // Atomically add 10 to the first element
90 | console.log(Atomics.load(uint8, 0)); // 10
91 | ```
92 |
93 | In this example, a `SharedArrayBuffer` of 1024 bytes is created, and then a `Uint8Array` is created to access this buffer. Using `Atomics.add`, an atomic operation is performed, ensuring no other thread interferes in the middle of the operation and changes the values. These features help you manage parallel operations safely and efficiently.
--------------------------------------------------------------------------------
/EN/09-ES10-2019.md:
--------------------------------------------------------------------------------
1 | # ES10-2019 Questions
2 |
3 | ## `String.prototype.trimStart` and `String.prototype.trimEnd` Methods
4 |
5 | ### 1. How can you manage whitespace at the start and end of strings using `trimStart` and `trimEnd`?
6 | In ES10, two new methods, `trimStart` and `trimEnd`, were added to JavaScript, allowing developers to specifically remove whitespace from the beginning or end of strings. These methods are more specific versions of the `trim` method, which removes whitespace from both sides. With these, you can choose exactly which side of the string should be trimmed.
7 |
8 | ```javascript
9 | const str = ' Hello World! ';
10 | console.log(str.trimStart()); // 'Hello World! '
11 | console.log(str.trimEnd()); // ' Hello World!'
12 | ```
13 |
14 | In this example, `trimStart` removes the whitespace from the beginning, and `trimEnd` removes it from the end of the string. This feature is particularly useful for cleaning up strings in user inputs or data received from different sources.
15 |
16 | ## `Object.fromEntries` Method
17 |
18 | ### 2. What is the purpose of the `Object.fromEntries` method, and how can it help manage data?
19 | In ES10, the `Object.fromEntries` method was introduced, allowing you to easily convert an array of key-value pairs into an object. This method complements `Object.entries`, which converts an object into an array of key-value pairs. This feature is particularly useful when dealing with structured data like JSON.
20 |
21 | ```javascript
22 | const entries = [['a', 1], ['b', 2], ['c', 3]];
23 | const obj = Object.fromEntries(entries);
24 | console.log(obj); // { a: 1, b: 2, c: 3 }
25 | ```
26 |
27 | In this example, an array of key-value pairs is converted into an object using `Object.fromEntries`. This method helps you quickly convert data in arrays into object structures, making it easier to process and access.
28 |
29 | ## Optional Catch Binding
30 |
31 | ### 3. How does the `Optional Catch Binding` feature help simplify error handling?
32 | In ES10, a new feature called `Optional Catch Binding` was introduced, allowing you to omit the error parameter in `catch` blocks if you don't need it. This feature is especially useful when you just want to handle errors without needing to process their details.
33 |
34 | ```javascript
35 | try {
36 | // some code
37 | } catch {
38 | console.log('An error occurred.');
39 | }
40 | ```
41 |
42 | In this example, the error parameter is omitted in the `catch` block because we don't need to inspect the error details. This approach makes the code simpler and more readable, allowing you to focus only on the main parts of your code.
43 |
44 | ## `Array.prototype.flat` and `Array.prototype.flatMap` Methods
45 |
46 | ### 4. How can you use `flat` and `flatMap` to convert multi-dimensional arrays into simpler arrays?
47 | In ES10, the `flat` and `flatMap` methods were added to JavaScript, allowing you to flatten multi-dimensional arrays into simpler ones. `flat` does this by removing nested layers, while `flatMap` lets you first map each element to a new array and then flatten the result.
48 |
49 | ```javascript
50 | const arr = [1, [2, [3, [4]]]];
51 | console.log(arr.flat(2)); // [1, 2, 3, [4]]
52 |
53 | const arr2 = [1, 2, 3];
54 | console.log(arr2.flatMap(x => [x, x * 2])); // [1, 2, 2, 4, 3, 6]
55 | ```
56 |
57 | In this example, `flat` converts a multi-layered array into a simpler array, while `flatMap` allows you to map each element to a new array and then flatten the result. These methods are particularly useful for managing complex and multi-layered data.
58 |
59 | ## Revised `Array.sort` Feature
60 |
61 | ### 5. How does the `Revised Array.sort` feature help improve data sorting?
62 | In ES10, the `sort` method was revised to guarantee stable sorting. This means that when two elements in an array have the same value, their original order is preserved and does not change during sorting. This feature is especially important for sorting data where the original order matters.
63 |
64 | ```javascript
65 | const arr = [{ name: 'John', age: 25 }, { name: 'Jane', age: 22 }, { name: 'Jack', age: 25 }];
66 | arr.sort((a, b) => a.age - b.age);
67 | console.log(arr);
68 | /* Output:
69 | [
70 | { name: 'Jane', age: 22 },
71 | { name: 'John', age: 25 },
72 | { name: 'Jack', age: 25 }
73 | ]
74 | */
75 | ```
76 |
77 | In this example, the original order of elements with the same age (like John and Jack) is preserved during sorting. This feature helps you sort data without worrying about changing the original order.
78 |
79 | ## Revised `JSON.stringify` Feature
80 |
81 | ### 6. How do the improved features in `JSON.stringify` help prevent errors?
82 | In ES10, `JSON.stringify` was revised to always produce valid Unicode strings. This change fixes problems that previously occurred when dealing with specific Unicode characters, ensuring that the generated strings are always correctly parsed.
83 |
84 | ```javascript
85 | const str = '\uD800';
86 | console.log(JSON.stringify(str)); // '"\\ud800"' instead of a malformed string
87 | ```
88 |
89 | In this example, `JSON.stringify` correctly converts a string containing a malformed Unicode character and produces a valid string. This feature is especially useful for working with international text data and preventing errors related to data parsing.
90 |
91 | ## Use of Separators in String Literals
92 |
93 | ### 7. How can you use separators in string literals to make JSON a full superset of ECMAScript?
94 | In ES10, the ability to use line separators (`\u2028`) and paragraph separators (`\u2029`) in string literals was introduced. This feature makes JSON a full superset of ECMAScript, creating more compatibility between string literals and JSON.
95 |
96 | ```javascript
97 | const str = 'Hello\u2028World';
98 | console.log(JSON.parse(`"${str}"`)); // 'Hello
World'
99 | ```
100 |
101 | In this example, the line separator (`\u2028`) is correctly used in the string, and JSON parses it without any issues. This feature is very useful for working with text data from various sources that need specific formatting.
102 |
103 | ## Revised `Function.prototype.toString` Method
104 |
105 | ### 8. What are the benefits of the revised `Function.prototype.toString` method, and how can it help analyze code?
106 | In ES10, the `Function.prototype.toString` method was revised to return the exact source code text of the function. This text includes everything, such as comments and whitespace, which helps with more precise analysis and debugging.
107 |
108 | ```javascript
109 | function example() {
110 | // This is a comment
111 | return "Hello, world!";
112 | }
113 |
114 | console.log(example.toString());
115 | /* Output:
116 | function example() {
117 | // This is a comment
118 | return "Hello, world!";
119 | }
120 | */
121 | ```
122 |
123 | In this example, the `toString` method returns the code of the `example` function exactly as it was written, including all details like comments and whitespace. This feature helps you examine and analyze the code accurately, and it is also very useful when you need to document or transfer code to different environments.
--------------------------------------------------------------------------------
/EN/10-ES11-2020.md:
--------------------------------------------------------------------------------
1 | # ES11-2020 Questions
2 |
3 | ## BigInt Feature
4 |
5 | ### 1. Why was `BigInt` added to JavaScript, and what are its uses?
6 | The `BigInt` data type was added to JavaScript so you can work with really large integers without losing precision in calculations. This is particularly useful when you need to handle numbers much larger than the range that `Number` (which uses 64-bit) can handle. `BigInt` allows you to manage numbers larger than 2^53-1 (the largest integer representable in `Number`) with full accuracy.
7 |
8 | ```javascript
9 | const bigNumber = BigInt(9007199254740991);
10 | const anotherBigNumber = 9007199254740991n; // You can also create a BigInt by adding 'n' at the end of the number
11 | console.log(bigNumber + anotherBigNumber); // 18014398509481982n
12 | ```
13 |
14 | In this example, two large numbers are defined using `BigInt` and added together without losing precision. This feature is great for financial or scientific calculations where you need to handle very large numbers accurately.
15 |
16 | ## String.prototype.matchAll Method
17 |
18 | ### 2. What problems does the `matchAll` method solve, and how can you use it?
19 | The `matchAll` method was added to JavaScript to let you find all matches of a regular expression in a string and get detailed information about them. Previously, you had to use more complex methods or nested loops to do this, but now `matchAll` returns all matches as an iterator, making access to them much easier.
20 |
21 | ```javascript
22 | const regex = /t(e)(st(\d?))/g;
23 | const str = 'test1test2';
24 | const matches = [...str.matchAll(regex)];
25 |
26 | console.log(matches[0]);
27 | // Output:
28 | // ["test1", "e", "st1", "1"]
29 |
30 | console.log(matches[1]);
31 | // Output:
32 | // ["test2", "e", "st2", "2"]
33 | ```
34 |
35 | In this example, `matchAll` finds all matches of the regular expression `regex` in the string `str` and returns them as an array of results. This feature is handy for working with texts that require precise processing, such as extracting data from documents or analyzing strings.
36 |
37 | ## Nullish Coalescing Operator
38 |
39 | ### 3. How can the `Nullish Coalescing` operator make your code more robust?
40 | The `??` operator, known as `Nullish Coalescing`, lets you safely assign a default value to a variable when it is `null` or `undefined`. This operator is particularly useful when variables may come from external sources and may not have a value, helping to prevent unexpected errors.
41 |
42 | ```javascript
43 | const foo = null ?? 'default';
44 | const bar = 0 ?? 'default';
45 |
46 | console.log(foo); // 'default'
47 | console.log(bar); // 0
48 | ```
49 |
50 | In this example, `foo` gets the default value 'default' because it is `null`, but `bar` keeps its value of `0` since it is a valid value. This operator is especially useful when you want to ensure variables have safe default values.
51 |
52 | ## Optional Chaining Operator
53 |
54 | ### 4. How does the `Optional Chaining` operator help prevent errors?
55 | The `?.` operator, known as `Optional Chaining`, allows you to access properties or methods in a chain without worrying about whether they exist or not. This operator prevents `undefined` or `null` errors and makes your code more stable.
56 |
57 | ```javascript
58 | const user = {
59 | profile: {
60 | name: 'John'
61 | }
62 | };
63 |
64 | const userName = user?.profile?.name;
65 | const userAge = user?.profile?.age;
66 |
67 | console.log(userName); // 'John'
68 | console.log(userAge); // undefined (no error)
69 | ```
70 |
71 | In this example, we safely access the `profile` and `name` properties using `?.`. If any of these properties do not exist, instead of throwing an error, it returns `undefined`, allowing the code to continue running smoothly.
72 |
73 | ## Logical AND Assignment Operator
74 |
75 | ### 5. When is the `Logical AND Assignment` operator useful, and how does it work?
76 | The `&&=` operator, introduced in ES11, lets you assign a value to a variable only if the current value of that variable is `true`. This operator is especially useful when you want to conditionally change a value without writing the entire condition.
77 |
78 | ```javascript
79 | let x = true;
80 | let y = false;
81 |
82 | x &&= 'Assigned if true';
83 | y &&= 'Not assigned because false';
84 |
85 | console.log(x); // 'Assigned if true'
86 | console.log(y); // false
87 | ```
88 |
89 | In this example, the value of `x` changes because it is `true`, but the value of `y`, which is `false`, remains unchanged. This operator can simplify writing complex conditions in your code and make it more readable.
90 |
91 | ## Logical OR Assignment Operator
92 |
93 | ### 6. How can the `Logical OR Assignment` operator simplify conditions?
94 | The `||=` operator allows you to assign a value to a variable only if the current value of that variable is `false`, `null`, or `undefined`. This operator is especially useful when you want to assign a default value to a variable that might not have been initialized yet.
95 |
96 | ```javascript
97 | let a = null;
98 | let b = 'Already set';
99 |
100 | a ||= 'Set because null';
101 | b ||= 'Not set because already has a value';
102 |
103 | console.log(a); // 'Set because null'
104 | console.log(b); // 'Already set'
105 | ```
106 |
107 | In this example, `a` gets a new value because it is `null`, but `b`, which already has a value, keeps it. This operator helps you write simpler conditions and avoid unnecessary complexity.
108 |
109 | ## Nullish Coalescing Assignment Operator
110 |
111 | ### 7. What sets the `Nullish Coalescing Assignment` operator apart from other assignment operators?
112 | The `??=` operator lets you assign a value to a variable only if its current value is `null` or `undefined`. This operator is particularly useful when you want to ensure a variable is initialized but don't want to overwrite `false` or `0` values.
113 |
114 | ```javascript
115 | let c = null;
116 | let d = 'Already defined';
117 |
118 | c ??= 'Set because null';
119 | d ??= 'Not set because already defined';
120 |
121 | console.log(c); // 'Set because null'
122 | console.log(d); // 'Already defined'
123 | ```
124 |
125 | In this example, `c` is replaced with a new value because it is `null`, but `d`, which has a valid value, remains unchanged. This operator helps you perform safer default assignments.
126 |
127 | ## Promise.allSettled Method
128 |
129 | ### 8. What is the purpose of the `Promise.allSettled` method, and how can it help manage promises?
130 | The `Promise.allSettled` method allows you to wait for all promises, whether they succeed or fail, to complete and then review the final outcome of each one. This method is particularly useful when you want to receive all results and not just focus on successful or failed ones.
131 |
132 | ```javascript
133 | const promise1 = Promise.resolve('Resolved');
134 | const promise2 = Promise.reject('Rejected');
135 | const promise3 = new Promise((resolve) => setTimeout(resolve, 1000, 'Delayed'));
136 |
137 | Promise.allSettled([promise1, promise2, promise3])
138 | .then((results) => results.forEach((result) => console.log(result.status)));
139 | /* Output:
140 | fulfilled
141 | rejected
142 | fulfilled
143 | */
144 | ```
145 |
146 | In this example, `Promise.allSettled` waits for all three promises to complete, whether successful or not, and then logs the final status of each. This method is useful when you want to know the status of all promises and handle all outcomes, whether successful or unsuccessful.
147 |
148 | ## Dynamic Import Feature
149 |
150 | ### 9. How can the `Dynamic Import` feature help optimize code loading?
151 | The `Dynamic Import` feature allows you to load modules dynamically only when needed. This reduces the initial page or app load and ensures that other parts are only loaded when really needed. This feature helps optimize performance and reduce load times.
152 |
153 | ```javascript
154 | // Suppose we have a module named 'math.js' containing various functions
155 | async function loadMathModule() {
156 | const math = await import('./math.js');
157 | console.log(math.add(2, 3)); // Using the add function from the math module
158 | }
159 |
160 | loadMathModule();
161 | ```
162 |
163 | In this example, the `math.js` module is only loaded when needed (inside the `loadMathModule` function). This reduces the initial page or app load and ensures that the user only downloads the modules they really need. This feature is very useful for optimizing the performance of web applications and reducing page load times.
--------------------------------------------------------------------------------
/EN/11-ES12-2021.md:
--------------------------------------------------------------------------------
1 | # ES12-2021 Questions
2 |
3 | ## `Promise.any` Method
4 |
5 | ### 1. How does `Promise.any` work, and when is it useful?
6 | The `Promise.any` method lets you pick the first `Promise` that successfully resolves out of a bunch. Instead of waiting for all the `Promise`s to finish, you just use the first one that comes back with a result. This is super handy when you've started a few tasks at the same time and only care about whichever one finishes first.
7 |
8 | ```javascript
9 | const myPromise1 = new Promise((resolve, reject) => {
10 | setTimeout(resolve, 200, "King");
11 | });
12 |
13 | const myPromise2 = new Promise((resolve, reject) => {
14 | setTimeout(resolve, 100, "Queen");
15 | });
16 |
17 | Promise.any([myPromise1, myPromise2]).then((result) => {
18 | console.log(result); // "Queen"
19 | });
20 | ```
21 |
22 | In this example, `Promise.any` waits for one of the two `Promise`s to complete successfully and returns the first result, which is "Queen". This feature is especially useful when you want to get the fastest response from multiple simultaneous operations and don't care about the rest.
23 |
24 | ## `replaceAll` Method
25 |
26 | ### 2. How does the `replaceAll` method help with text replacement in strings?
27 | The `replaceAll` method allows you to replace all occurrences of a word or phrase in a string with another word or phrase. Unlike `replace`, which only changes the first match, `replaceAll` changes every match. This method is super helpful when you want to make a complete change in a text and don't want to miss anything.
28 |
29 | ```javascript
30 | let text = "Cats are great. Cats are friendly.";
31 | text = text.replaceAll("Cats", "Dogs");
32 | console.log(text); // "Dogs are great. Dogs are friendly."
33 | ```
34 |
35 | Here, `replaceAll` replaces all instances of "Cats" with "Dogs". This method is especially useful when you want to make a comprehensive change to a phrase in a text without having to manually do it multiple times.
36 |
37 | Additionally, you can use `replaceAll` with regular expressions to find and replace more complex matches in text. Just remember to use the `g` (global) flag.
38 |
39 | ```javascript
40 | let text = "Cats are great. Cats are friendly.";
41 | text = text.replaceAll(/Cats/g, "Dogs");
42 | console.log(text); // "Dogs are great. Dogs are friendly."
43 | ```
44 |
45 | This approach helps you apply all necessary changes to the text with just one line of code.
46 |
47 | ## Numeric Separators
48 |
49 | ### 3. What are numeric separators (`_`), and how can you use them?
50 | Numeric separators (`_`) let you write large numbers in your code in a more readable way. These separators don't affect the actual value of the number, but they make reading and understanding large numbers easier. This is especially helpful when working with numbers in the millions or billions, reducing reading and writing errors.
51 |
52 | ```javascript
53 | const num = 1_000_000_000;
54 | console.log(num); // 1000000000
55 | ```
56 |
57 | Here, the `_` separators make the number easier to read, but the result is still 1000000000. These separators only improve code readability, and you can place them anywhere in the number to make it easier to read.
58 |
59 | ```javascript
60 | const num1 = 1_234_567_890_123_456;
61 | console.log(num1); // 1234567890123456
62 | ```
63 |
64 | This feature is particularly useful when you're working with large and complex numbers and want to ensure the code is both readable and low on errors.
--------------------------------------------------------------------------------
/EN/12-ES13-2022.md:
--------------------------------------------------------------------------------
1 | # ES13-2022 Questions
2 |
3 | ## `Array.at` Method
4 |
5 | ### 1. How does the `Array.at` method work, and what problem does it solve when accessing array elements?
6 | The `Array.at` method is a cool new way to access specific elements in an array using an index, just like you would with `[]`. But what sets this method apart is that it lets you use negative indices to access elements from the end of the array. This is super handy when you want to grab something from the end of an array without having to know its length.
7 |
8 | ```javascript
9 | const fruits = ["Banana", "Orange", "Apple", "Mango"];
10 | let fruit = fruits.at(-1);
11 | console.log(fruit); // "Mango"
12 | ```
13 |
14 | In this example, `at(-1)` is used to select the last element in the array, "Mango". This method makes it a lot easier to write cleaner code and access the last elements of an array without any hassle.
15 |
16 | ## `String.at` Method
17 |
18 | ### 2. How does the `String.at` method help access characters in a string, and what are its advantages?
19 | The `String.at` method does for strings what `Array.at` does for arrays. It allows you to easily select a specific character from a string based on an index, even using negative indices to access characters from the end of the string. This feature is especially useful when working with long strings.
20 |
21 | ```javascript
22 | const name = "W3Schools";
23 | let letter = name.at(-1);
24 | console.log(letter); // "s"
25 | ```
26 |
27 | In this example, `at(-1)` gets the last character of the string, "s". This method is super efficient when you need quick and direct access to specific characters in a string.
28 |
29 | ## `d` Flag in RegExp
30 |
31 | ### 3. How does the `d` flag in RegExp work, and what information does it provide for matches?
32 | The `d` flag in regular expressions (RegExp) was added to show the exact start and end positions of matches in the results. This flag helps you not only see what matched, but also precisely where those matches occurred. It's incredibly useful for in-depth text analysis.
33 |
34 | ```javascript
35 | let text = "aaaabb";
36 | let result = text.match(/(aa)(bb)/d);
37 | console.log(result.indices); // [[0, 6], [0, 2], [4, 6]]
38 | ```
39 |
40 | In this example, the `d` flag helps pinpoint the exact positions of the matches "aa" and "bb" in the text. This flag is particularly handy when you need precise analysis of matches.
41 |
42 | ## `Object.hasOwn` Method
43 |
44 | ### 4. What role does the `Object.hasOwn` method play in checking property ownership, and how is it different from previous methods like `hasOwnProperty`?
45 | The `Object.hasOwn` method is a new, safer, and more optimized way to check if a specific object has a certain property. It's more versatile than `hasOwnProperty` and can be used on all types of objects, making it the best choice for checking property ownership.
46 |
47 | ```javascript
48 | const obj = { name: "John", age: 30 };
49 | console.log(Object.hasOwn(obj, "name")); // true
50 | console.log(Object.hasOwn(obj, "gender")); // false
51 | ```
52 |
53 | In this example, we use `Object.hasOwn` to check if the property "name" exists in the object `obj`. This method helps you perform checks confidently without worrying about compatibility issues or potential errors.
54 |
55 | ## `error.cause` Feature
56 |
57 | ### 5. How does the `error.cause` feature help you pinpoint the exact cause of errors and manage them better?
58 | The `error.cause` feature allows you to specify the underlying reason when an error occurs and present it as part of the error. This feature is particularly useful when you want more detailed information about the cause of errors, making debugging easier.
59 |
60 | ```javascript
61 | try {
62 | connectData();
63 | } catch (err) {
64 | throw new Error("Connecting failed.", { cause: err });
65 | }
66 | ```
67 |
68 | In this example, when `connectData` throws an error, that error is recorded as the `cause` of the new error we throw. This method gives you more detailed information about errors, making them easier to manage.
69 |
70 | ## `await import` Feature
71 |
72 | ### 6. How does the `await import` feature help with module loading management, and why should you use it?
73 | The `await import` feature allows you to dynamically load modules only when you actually need them. This feature is especially useful when you want the initial code of your program to be lighter and load faster, with only the necessary parts loading over time.
74 |
75 | ```javascript
76 | const { myFunction } = await import('./myModule.js');
77 | myFunction();
78 | ```
79 |
80 | In this example, the module `myModule.js` is loaded dynamically and only when we need it. This reduces the initial load time of the page, and modules are only loaded if necessary, which improves performance and execution speed.
81 |
82 | ## Class Field Declarations
83 |
84 | ### 7. What are the advantages of class field declarations, and how can they make class code cleaner and more organized?
85 | Class field declarations allow you to define class variables directly inside the class itself, without having to declare them in the `constructor` method. This feature makes class code simpler, more readable, and more organized.
86 |
87 | ```javascript
88 | class Hello {
89 | counter = 0;
90 | }
91 | const myClass = new Hello();
92 | console.log(myClass.counter); // 0
93 | ```
94 |
95 | In this example, the field `counter` is defined directly inside the `Hello` class, making the code both shorter and less complex. This method brings more order to class code and makes it easier to understand and maintain.
96 |
97 | ## Private Methods and Fields in Classes
98 |
99 | ### 8. How do private methods and fields in classes enhance security and integrity of code, and why should you use them?
100 | Private methods and fields let you keep some data and functions within a class private, accessible only within that class. This feature enhances code security and prevents unauthorized access or unwanted changes.
101 |
102 | ```javascript
103 | class Hello {
104 | #counter = 0;
105 |
106 | #increment() {
107 | this.#counter++;
108 | }
109 |
110 | getCount() {
111 | return this.#counter;
112 | }
113 | }
114 | const myClass = new Hello();
115 | console.log(myClass.getCount()); // 0
116 | ```
117 |
118 | In this example, `#counter` and `#increment` are defined as private and can only be accessed within the `Hello` class. This approach ensures that the internal code of the class is not accessible or modifiable from outside, which helps increase the security and integrity of the code.
--------------------------------------------------------------------------------
/EN/13-ES14-2023.md:
--------------------------------------------------------------------------------
1 | # ES14-2023 Questions
2 |
3 | ## `Array.findLast` Method
4 |
5 | ### 1. How does the `findLast` method work in arrays, and what is its use?
6 | The `findLast` method is a new addition to arrays that allows you to start from the end of an array and find the first element that matches a certain condition. This method works similarly to `find`, but instead of starting from the beginning of the array, it starts from the end. This is especially useful when you want to start searching from the end and find the first match.
7 |
8 | ```javascript
9 | const temp = [27, 28, 30, 40, 42, 35, 30];
10 | let high = temp.findLast(x => x > 40);
11 | console.log(high); // 42
12 | ```
13 |
14 | In this example, `findLast` starts from the end of the array and finds the first value greater than 40, which is 42. This method is great when you need the last match for a specific condition.
15 |
16 | ## `Array.findLastIndex` Method
17 |
18 | ### 2. What does the `findLastIndex` method do, and how can it optimize searches in arrays?
19 | The `findLastIndex` method is similar to `findLast`, but instead of returning the value, it returns the index (position) of the last element that meets a certain condition. This method is useful when you want to know where a specific condition was last met in the array.
20 |
21 | ```javascript
22 | const temp = [27, 28, 30, 40, 42, 35, 30];
23 | let pos = temp.findLastIndex(x => x > 40);
24 | console.log(pos); // 4
25 | ```
26 |
27 | In this example, `findLastIndex` finds the last position where a value greater than 40 exists, which is index 4 (value 42). This method is useful for optimizing searches and finding the location of the last match.
28 |
29 | ## `Array.toReversed` Method
30 |
31 | ### 3. How is `toReversed` different from `reverse`, and why is it better to use?
32 | The `toReversed` method is a new and safer way to reverse arrays that returns a new array without modifying the original one. Unlike `reverse`, which directly changed the original array, `toReversed` keeps the original array unchanged and returns a reversed copy.
33 |
34 | ```javascript
35 | const months = ["Jan", "Feb", "Mar", "Apr"];
36 | const reversed = months.toReversed();
37 | console.log(reversed); // ["Apr", "Mar", "Feb", "Jan"]
38 | console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
39 | ```
40 |
41 | In this example, `toReversed` returns a reversed version of the `months` array without altering the original array. This method is useful when you need to reverse an array but don't want the original array to change.
42 |
43 | ## `Array.toSorted` Method
44 |
45 | ### 4. How does `toSorted` help with sorting arrays, and why is it better than using `sort`?
46 | The `toSorted` method is a new way to sort arrays that returns a sorted copy of the array without modifying the original one. This method works like `sort`, but its advantage is that it keeps the original array intact.
47 |
48 | ```javascript
49 | const months = ["Jan", "Feb", "Mar", "Apr"];
50 | const sorted = months.toSorted();
51 | console.log(sorted); // ["Apr", "Feb", "Jan", "Mar"]
52 | console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
53 | ```
54 |
55 | In this example, `toSorted` returns a sorted array without changing the original one. This method is ideal when you need to sort but don't want the original array to be altered.
56 |
57 | ## `Array.toSpliced` Method
58 |
59 | ### 5. How can `toSpliced` be useful in manipulating arrays, and how does it differ from `splice`?
60 | The `toSpliced` method is a new and safe way to remove or replace elements in an array that returns a modified copy without altering the original array. This method is a better alternative to `splice` because `splice` would change the original array, but `toSpliced` does not.
61 |
62 | ```javascript
63 | const months = ["Jan", "Feb", "Mar", "Apr"];
64 | const spliced = months.toSpliced(0, 1);
65 | console.log(spliced); // ["Feb", "Mar", "Apr"]
66 | console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
67 | ```
68 |
69 | In this example, `toSpliced` returns a new version of the `months` array with the first element removed. The original array remains unchanged. This method is great for when you want to make changes to an array but keep the original intact.
70 |
71 | ## `Array.with` Method
72 |
73 | ### 6. How does the `with` method work, and what is its use in updating array elements?
74 | The `with` method is a new way to replace elements in an array that returns a new version of the array with the specified element replaced, without modifying the original array. This method is useful for updating specific elements in an array without changing the rest of the array.
75 |
76 | ```javascript
77 | const months = ["Januar", "Februar", "Mar", "April"];
78 | const updated = months.with(2, "March");
79 | console.log(updated); // ["Januar", "Februar", "March", "April"]
80 | console.log(months); // ["Januar", "Februar", "Mar", "April"]
81 | ```
82 |
83 | In this example, `with` returns a new version of the `months` array where the third element ("Mar") is replaced with "March". This allows you to easily update the array without changing the original one.
84 |
85 | ## `#!` (Shebang) Feature
86 |
87 | ### 7. What role does the `#!` (Shebang) feature play in executing JavaScript scripts, and why is it important to use?
88 | The `#!` feature, also known as Shebang, is added to script files to tell the operating system which interpreter should be used to run the file. This feature is particularly useful when you want to run JavaScript code directly in Unix or Linux environments.
89 |
90 | ```javascript
91 | #!/usr/bin/env node
92 | console.log('Hello World');
93 | ```
94 |
95 | In this example, the `#!` indicates that the script should be executed with `node`. This allows you to run JavaScript code directly with `./fileName.js` instead of using `node fileName.js`. This feature helps manage and execute scripts more easily in different environments.
--------------------------------------------------------------------------------
/EN/14-ES15-2024.md:
--------------------------------------------------------------------------------
1 | # ES15-2024 Questions
2 |
3 | ## `Object.groupBy` Method
4 |
5 | ### 1. What does the `Object.groupBy` method do, and what are its applications?
6 | > The `Object.groupBy` method is a new feature that allows you to group elements of an array of objects based on the values returned by a callback function. This method does not modify the original object; instead, it returns a new object with elements grouped into different categories. This feature is particularly useful when you want to group data dynamically, like grouping fruits based on their quantity.
7 |
8 | ```javascript
9 | const fruits = [
10 | { name: "apples", quantity: 300 },
11 | { name: "bananas", quantity: 500 },
12 | { name: "oranges", quantity: 200 },
13 | { name: "kiwi", quantity: 150 }
14 | ];
15 |
16 | function myCallback({ quantity }) {
17 | return quantity > 200 ? "ok" : "low";
18 | }
19 |
20 | const result = Object.groupBy(fruits, myCallback);
21 | console.log(result);
22 | // Output:
23 | // { ok: [ { name: 'apples', quantity: 300 }, { name: 'bananas', quantity: 500 } ],
24 | // low: [ { name: 'oranges', quantity: 200 }, { name: 'kiwi', quantity: 150 } ] }
25 | ```
26 |
27 | > In this example, `Object.groupBy` categorizes the fruits into "ok" and "low" groups based on their quantities. This method is particularly useful for dynamically grouping data based on various criteria.
28 |
29 | ## `Map.groupBy` Method
30 |
31 | ### 2. How does `Map.groupBy` differ from `Object.groupBy`, and when is it better to use?
32 | > The `Map.groupBy` method works similarly to `Object.groupBy`, but instead of returning a JavaScript object, it returns a `Map`. `Map` is more versatile because it can accept any data type as a key, making it more suitable for complex or non-string-based grouping.
33 |
34 | ```javascript
35 | const fruits = [
36 | { name: "apples", quantity: 300 },
37 | { name: "bananas", quantity: 500 },
38 | { name: "oranges", quantity: 200 },
39 | { name: "kiwi", quantity: 150 }
40 | ];
41 |
42 | function myCallback({ quantity }) {
43 | return quantity > 200 ? "ok" : "low";
44 | }
45 |
46 | const result = Map.groupBy(fruits, myCallback);
47 | console.log(result);
48 | // Output:
49 | // Map(2) { 'ok' => [ { name: 'apples', quantity: 300 }, { name: 'bananas', quantity: 500 } ],
50 | // 'low' => [ { name: 'oranges', quantity: 200 }, { name: 'kiwi', quantity: 150 } ] }
51 | ```
52 |
53 | > In this example, `Map.groupBy` groups the data similarly to `Object.groupBy`, but the output is a `Map`. `Map` is beneficial when you need advanced features like maintaining the order of elements or using non-string keys.
54 |
55 | ## `Temporal.PlainDate` Feature
56 |
57 | ### 3. How can `Temporal.PlainDate` help manage dates, and why is it better than `Date`?
58 | > The `Temporal.PlainDate` feature is one of the new tools for managing dates that offers more precision and capabilities compared to `Date`. It allows you to handle dates without worrying about the time of day, making it ideal for tasks like calendar calculations or scheduling specific dates.
59 |
60 | ```javascript
61 | const date = new Temporal.PlainDate(2024, 5, 1);
62 | console.log(date); // 2024-05-01
63 | ```
64 |
65 | > In this example, `Temporal.PlainDate` creates a date without considering the time. This is useful when you only need the date and time is not important.
66 |
67 | ## `Temporal.PlainTime` Feature
68 |
69 | ### 4. What is the use of `Temporal.PlainTime`, and what advantages does it have over using `Date` for time management?
70 | > The `Temporal.PlainTime` feature is used to manage times without the need for a date. It allows you to specify times with millisecond precision without worrying about time zones or dates. This feature is excellent for applications like timers or daily scheduling.
71 |
72 | ```javascript
73 | const time = new Temporal.PlainTime(10, 30);
74 | console.log(time); // 10:30:00
75 | ```
76 |
77 | > In this example, `Temporal.PlainTime` creates a specific time without considering the date. This is great for when you only need to manage time and the date is irrelevant.
78 |
79 | ## `Temporal.PlainMonthDay` Feature
80 |
81 | ### 5. How can `Temporal.PlainMonthDay` be useful in managing special dates like birthdays or anniversaries?
82 | > The `Temporal.PlainMonthDay` feature is used to manage dates that only include the month and day (like birthdays or anniversaries). This feature does not require a year and allows you to easily keep track of specific dates.
83 |
84 | ```javascript
85 | const monthDay = new Temporal.PlainMonthDay(5, 1);
86 | console.log(monthDay); // 05-01
87 | ```
88 |
89 | > In this example, `Temporal.PlainMonthDay` creates a specific date that only includes the month and day. This feature is very useful for tasks that require managing dates without a year.
90 |
91 | ## `Temporal.PlainYearMonth` Feature
92 |
93 | ### 6. How does `Temporal.PlainYearMonth` assist in managing financial dates or monthly reports?
94 | > The `Temporal.PlainYearMonth` feature is used to manage dates that include the year and month (like financial reports or monthly planning). This feature allows you to specify the year and month easily without worrying about the day.
95 |
96 | ```javascript
97 | const yearMonth = new Temporal.PlainYearMonth(2024, 5);
98 | console.log(yearMonth); // 2024-05
99 | ```
100 |
101 | > In this example, `Temporal.PlainYearMonth` creates a date that only includes the year and month. This capability is very useful for managing monthly planning or financial reports.
--------------------------------------------------------------------------------
/FA/01-basic.md:
--------------------------------------------------------------------------------
1 | # سوالات سطح پایه JavaScript
2 |
3 | ## متغیرها و انواع داده
4 |
5 | ### 1. تفاوت بین `let`, `const`, و `var` چیه؟
6 | > تفاوت در اینه که `var` تابع-محدوده (function-scoped) هست، ولی `let` و `const` بلوک-محدوده (block-scoped) هستن. `let` اجازه بهروزرسانی میده ولی نه اعلام دوباره، در حالی که `const` اجازه هیچکدوم رو نمیده.
7 |
8 | ### 2. انواع مختلف داده در JavaScript چیا هستن؟
9 | > انواع دادههای اولیه شامل `Number`, `String`, `Boolean`, `Undefined`, `Null`, `Symbol`, و `BigInt` هستن. دادههای غیر اولیه شامل `Object` (که شامل `Array`, `Function` و غیره میشه) هستن.
10 |
11 | ### 3. چطوری بررسی میکنی که یک متغیر یک آرایه هست؟
12 | > با استفاده از متد `Array.isArray(variable)` میتونی بررسی کنی.
13 |
14 | ### 4. عملگر `typeof` چیه؟
15 | > عملگر `typeof` یک رشته برمیگردونه که نوع عملوند ارزیابینشده رو نشون میده.
16 |
17 | ## عملگرها و ساختارهای کنترلی
18 |
19 | ### 5. تفاوت بین `==` و `===` چیه؟
20 | > تفاوت در اینه که `==` تبدیل نوع (type coercion) انجام میده و برابری مقدار رو بررسی میکنه، در حالی که `===` هم برابری مقدار و هم برابری نوع (strict equality) رو بررسی میکنه.
21 |
22 | ### 6. چطوری با استثناها در JavaScript برخورد میکنی؟
23 | > با استفاده از بلوکهای `try`, `catch`, و `finally` میتونی با استثناها برخورد کنی. `try` یک بلوک کد رو برای خطاها تست میکنه، `catch` خطا رو مدیریت میکنه، و `finally` کدی رو اجرا میکنه بعد از بلوکهای `try` و `catch`، بدون توجه به نتیجه.
24 |
25 | ## توابع
26 |
27 | ### 7. تابع callback چیه؟
28 | > تابع callback تابعیه که به عنوان آرگومان به توابع دیگه پاس داده میشه و سپس داخل تابع خارجی اجرا میشه تا یک کار خاص رو کامل کنه.
29 |
30 | ### 8. کلیدواژه `this` در JavaScript رو توضیح بده.
31 | > کلیدواژه `this` بستگی به زمینه اجرا داره. در یک متد، `this` به شیء اشاره میکنه. در یک تابع، `this` به شیء سراسری (یا undefined در حالت strict) اشاره میکنه. در یک event handler، `this` به عنصری که رویداد رو دریافت کرده اشاره میکنه.
32 |
33 | ### 9. شیء `arguments` چیه؟
34 | > شیء `arguments` یک شیء شبیه به آرایه هست که داخل توابع در دسترسه و حاوی مقادیر آرگومانهایی هست که به تابع پاس داده شدن.
35 |
36 | ### 10. پارامترهای پیشفرض در JavaScript چیه؟
37 | > پارامترهای پیشفرض به شما اجازه میدن تا پارامترهای تابع رو با مقادیر پیشفرض مقداردهی کنید اگه هیچ مقداری پاس داده نشه یا undefined پاس داده بشه.
38 | > ```javascript
39 | > function greet(name = 'Guest') { console.log(`Hello, ${name}`); }
40 | > ```
41 |
42 | ## آرایهها و اشیاء
43 |
44 | ### 11. چطوری یک شیء در JavaScript ایجاد میکنی؟
45 | > اشیاء میتونن با استفاده از literalهای شیء، سازندهها (constructors)، یا متد `Object.create` ایجاد بشن.
46 |
47 | ### 12. چطوری دو شیء رو در JavaScript ادغام میکنی؟
48 | > با استفاده از `Object.assign` یا spread operator میتونی دو شیء رو ادغام کنی.
49 | > ```javascript
50 | > const merged = Object.assign({}, obj1, obj2);
51 | > const merged = {...obj1, ...obj2};
52 | > ```
53 |
54 | ### 13. چطوری یک عنصر رو به ابتدای یک آرایه اضافه میکنی؟
55 | > با استفاده از متد `unshift` میتونی یک عنصر رو به ابتدای یک آرایه اضافه کنی.
56 | > ```javascript
57 | > array.unshift(element);
58 | > ```
59 |
60 | ### 14. چطوری آخرین عنصر از یک آرایه رو حذف میکنی؟
61 | > با استفاده از متد `pop` میتونی آخرین عنصر رو حذف کنی.
62 | > ```javascript
63 | > array.pop();
64 | > ```
65 |
66 | ### 15. چطوری یک کپی سطحی از یک آرایه ایجاد میکنی؟
67 | > با استفاده از متد `slice` یا spread operator میتونی یک کپی سطحی ایجاد کنی.
68 | > ```javascript
69 | > const copy = array.slice();
70 | > const copy = [...array];
71 | > ```
72 |
73 | ### 16. چطوری یک شیء شبیه به آرایه رو به یک آرایه تبدیل میکنی؟
74 | > با استفاده از `Array.from` یا spread operator میتونی یک شیء شبیه به آرایه رو به یک آرایه تبدیل کنی.
75 | > ```javascript
76 | > const array = Array.from(arrayLike);
77 | > const array = [...arrayLike];
78 | > ```
79 |
80 | ## رشتهها
81 |
82 | ### 17. رشته template literals چیه و چطوری ازشون استفاده میکنی؟
83 | > رشته template literals به شما این امکان رو میده که از بیانهای جاسازیشده، رشتههای چند خطی و جایگزینی رشته استفاده کنی. این رشتهها با backticks (`) به جای کوتیشنهای تک یا دوتایی محصور میشن.
84 | > ```javascript
85 | > const name = 'John';
86 | > const message = `Hello, ${name}`;
87 | > ```
88 |
89 | ### 18. چطوری یک رشته رو به عدد تبدیل میکنی در JavaScript؟
90 | > با استفاده از `parseInt(string)`, `parseFloat(string)`, `Number(string)`, یا عملگر یونری `+` میتونی یک رشته رو به عدد تبدیل کنی.
91 |
92 | ## دستکاری DOM
93 |
94 | ### 19. تفاوت بین `innerHTML` و `innerText` چیه؟
95 | > تفاوت در اینه که `innerHTML` تمام متن شامل تگهای HTML رو برمیگردونه، در حالی که `innerText` فقط محتوای متنی بدون تگهای HTML رو برمیگردونه.
96 |
97 | ### 20. چطوری میتونی رفتار پیشفرض رو در یک event handler جلوگیری کنی؟
98 | > با فراخوانی متد `event.preventDefault()` داخل event handler میتونی از رفتار پیشفرض جلوگیری کنی.
99 |
100 | ## رویدادها
101 |
102 | ### 21. رویداد event delegation چیه؟
103 | > رویداد event delegation به شما اجازه میده تا از یک event listener واحد برای مدیریت رویدادهای مشابه در چندین عنصر استفاده کنی با بهرهگیری از propagation (bubbling) رویداد در درخت DOM.
104 |
105 | ### 22. رویداد event bubbling چیه؟
106 | > رویداد event bubbling نوعی propagation رویداد هست که در اون رویداد اول در عنصر هدف تریگر میشه و سپس به ترتیب در هر یک از عناصر جدی اون تا ریشه سند تریگر میشه.
107 |
108 | ## متفرقه
109 |
110 | ### 23. ویژگی `NaN` در JavaScript چیه؟
111 | > ویژگی `NaN` مخفف "Not-a-Number" هست و یک مقدار رو نشون میده که از یک خطای محاسباتی ناشی میشه که نتیجه عددی تعریف نشدهای تولید میکنه.
112 |
113 | ### 24. دستور `use strict` چیه؟
114 | > دستور `"use strict"` حالت strict رو فعال میکنه که کمک میکنه خطاهای رایج کدنویسی رو بگیری و از انجام برخی اقدامات جلوگیری کنی. این کار باعث میشه کد JavaScript امنتر و بهینهتر بشه.
115 |
116 | ### 25. کد polyfill چیه؟
117 | > کد polyfill کدی هست که یک ویژگی رو در مرورگرهای وبی که به صورت بومی از اون ویژگی پشتیبانی نمیکنن، پیادهسازی میکنه و تضمین میکنه که در مرورگرهای مختلف سازگاری برقرار بشه.
118 |
119 | ### 26. مکانیزم CORS چیه؟
120 | > مکانیزم CORS (Cross-Origin Resource Sharing) مکانیزمی هست که به منابع محدود در یک صفحه وب اجازه میده از یک دامنه دیگه غیر از دامنهای که منبع از اون نشأت گرفته درخواست بشن.
121 |
122 | ### 27. مفهوم hoisting در JavaScript چیه؟
123 | > مفهوم hoisting رفتار JavaScript در انتقال اعلامیهها به بالای دامنه جاری هست. اعلامیههای متغیر (با استفاده از `var`) و اعلامیههای تابع hoist میشن، ولی مقداردهی اولیه اونها نه.
124 |
125 | ### 28. چطوری بررسی میکنی که یک شیء در JavaScript خالی هست یا نه؟
126 | > با بررسی طول کلیدهای شیء میتونی بررسی کنی که خالی هست یا نه:
127 | > ```javascript
128 | > Object.keys(obj).length === 0;
129 | > ```
130 |
131 | ### 29. هدف از `JSON.stringify` چیه؟
132 | > هدف از `JSON.stringify` تبدیل یک شیء JavaScript به یک رشته JSON هست.
133 |
134 | ### 30. هدف از `JSON.parse` چیه؟
135 | > هدف از `JSON.parse` تبدیل یک رشته JSON به یک شیء JavaScript هست.
136 |
--------------------------------------------------------------------------------
/FA/02-intermediate.md:
--------------------------------------------------------------------------------
1 | # سوالات سطح متوسط جاوا اسکریپت
2 |
3 | ## متغیرها و محدودههای پیشرفته
4 |
5 | ### 1. فرق بین محدوده تابع و محدوده بلوک چیه؟
6 | > محدوده تابع (function scope) یعنی متغیرها داخل یه تابع قابل دسترسی هستن، ولی محدوده بلوک (block scope) یعنی متغیرها فقط داخل بلوکی که تعریف شدن، مثل داخل یه `if` یا `for` قابل دسترسی هستن.
7 |
8 | ### 2. ویژگی Hoisting تو جاوا اسکریپت چطوری کار میکنه؟
9 | > ویژگی Hoisting یعنی جاوا اسکریپت اعلامیهها رو به بالای محدوده فعلی منتقل میکنه. اعلامیههای متغیر (با `var`) و اعلامیههای تابع hoist میشن، ولی مقداردهی اولیهشون نه.
10 |
11 | ## توابع و closures
12 |
13 | ### 3. مفهوم Closures تو جاوا اسکریپت چیه؟
14 | > مفهوم Closure تابعیه که به محدوده لغوی خودش دسترسی داره حتی وقتی تابع بیرون اون محدوده اجرا بشه.
15 |
16 | ### 4. توابع پیکانی (arrow functions) چی هستن و فرقشون با توابع معمولی چیه؟
17 | > توابع پیکانی سینتکس کوتاهتری دارن و مقدار `this` رو از محدودهی محصورکننده (enclosing scope) به صورت لغوی (lexically) بایند میکنن. این توابع `this`، `arguments`، `super` یا `new.target` خودشون رو ندارن.
18 |
19 | ### 5. فرق بین متدهای `call`، `apply` و `bind` چیه؟
20 | > متد `call` تابع رو با یه مقدار `this` مشخص و آرگومانهایی که یکی یکی ارائه میشن، فراخوانی میکنه. متد `apply` تابع رو با یه مقدار `this` مشخص و آرگومانهایی که به صورت آرایه ارائه میشن، فراخوانی میکنه. متد `bind` یه تابع جدید با یه مقدار `this` مشخص و آرگومانها بازمیگردونه.
21 |
22 | ## اشیاء و پروتوتایپها
23 |
24 | ### 6. زنجیره پروتوتایپ (prototype chain) تو جاوا اسکریپت رو توضیح بده.
25 | > زنجیره پروتوتایپ مجموعهای از لینکها بین اشیاء هست که با استفاده از `new` یا `Object.create` ایجاد میشن. وقتی یه ویژگی شیء دسترسی پیدا میشه، موتور جاوا اسکریپت زنجیره پروتوتایپ رو برای یافتن ویژگی طی میکنه.
26 |
27 | ### 7. ویژگی `__proto__` چیه؟
28 | > ویژگی `__proto__` ارجاعی به شیء پروتوتایپ شیء فعلی هست. این ویژگی برای دسترسی به پروتوتایپ یه شیء استفاده میشه و بخشی از زنجیره پروتوتایپ هست.
29 |
30 | ### 8. چطوری میتونی با استفاده از تابع سازنده یه شیء ایجاد کنی؟
31 | > با تعریف یه تابع و استفاده از کلمه کلیدی `new` برای ایجاد نمونهها:
32 | > ```javascript
33 | > function Person(name) {
34 | > this.name = name;
35 | > }
36 | > const john = new Person('John');
37 | > ```
38 |
39 | ## جاوا اسکریپت غیرهمگام (Asynchronous JavaScript)
40 |
41 | ### 9. یک promise چیه و چطوری ازش استفاده میکنی؟
42 | > یک promise شیئی هست که نمایانگر تکمیل نهایی یا شکست یک عملیات غیرهمگام هست. از متدهای `then` و `catch` برای مدیریت وضعیتهای resolved و rejected استفاده میشه.
43 |
44 | ### 10. مفهوم `async/await` تو جاوا اسکریپت چیه؟
45 | > توابع `async` یک promise برمیگردونن و اجازه میدن که از `await` داخل اونها برای توقف اجرا تا زمان تکمیل یا شکست promise استفاده بشه. این کار باعث میشه کد غیرهمگام شبیه و رفتار مشابه کد همگام داشته باشه.
46 |
47 | ### 11. حلقه رویداد (event loop) تو جاوا اسکریپت چیه؟
48 | > حلقه رویداد مکانیسمی هست که به جاوا اسکریپت اجازه میده عملیاتهای غیرمسدودکننده رو با استفاده از برونسپاری عملیات به هسته سیستم انجام بده. این حلقه به طور پیوسته استک فراخوانی و صف بازگشت (callback queue) رو بررسی میکنه و اولین وظیفه در صف رو به استک فراخوانی میفرسته اگه استک خالی باشه.
49 |
50 | ## آرایهها و اشیاء پیشرفته
51 |
52 | ### 12. تفاوت بین `map` و `forEach` چیه؟
53 | > تفاوت `map` اینه که یک آرایه جدید با نتایج اجرای تابع ارائهشده روی هر عنصر در آرایه اصلی ایجاد میکنه. `forEach` تابع ارائهشده رو یک بار برای هر عنصر آرایه اجرا میکنه اما آرایه جدیدی باز نمیگردونه.
54 |
55 | ### 13. چطوری میتونی یه کپی عمیق از یه شیء ایجاد کنی؟
56 | > برای ایجاد یه کپی عمیق میتونی از یه تابع بازگشتی یا استفاده از متدهای JSON استفاده کنی:
57 | > ```javascript
58 | > const deepCopy = JSON.parse(JSON.stringify(original));
59 | > ```
60 |
61 | ### 14. عملگر گسترش (spread operator) چیه و چطوری ازش استفاده میکنی؟
62 | > عملگر گسترش (`...`) اجازه میده که یک iterable مانند آرایه یا رشته باز بشه.
63 | > ```javascript
64 | > const arr = [1, 2, 3];
65 | > const newArr = [...arr, 4, 5];
66 | > ```
67 |
68 | ### 15. مفهوم Destructuring تو جاوا اسکریپت چیه؟
69 | > مفهوم Destructuring یه سینتکسه که بهت اجازه میده مقادیر رو از آرایهها یا ویژگیها رو از اشیاء به متغیرهای جداگانه استخراج کنی.
70 | > ```javascript
71 | > const { a, b } = { a: 1, b: 2 };
72 | > const [x, y] = [1, 2];
73 | > ```
74 |
75 | ## دستکاری DOM و رویدادها
76 |
77 | ### 16. مفهوم event delegation رو توضیح بده.
78 | > مفهوم event delegation بهت اجازه میده که از یک event listener برای مدیریت رویدادهای مشابه روی چندین عنصر با استفاده از انتشار رویداد (event propagation) درخت DOM استفاده کنی.
79 |
80 | ### 17. چطوری میتونی یه رویداد سفارشی تو جاوا اسکریپت ایجاد کنی؟
81 | > برای ایجاد یه رویداد سفارشی میتونی از سازنده `CustomEvent` استفاده کنی:
82 | > ```javascript
83 | > const event = new CustomEvent('eventName', { detail: { key: 'value' } });
84 | > ```
85 |
86 | ### 18. تفاوت بین `window.onload` و `document.ready` چیه؟
87 | > تفاوت `window.onload` اینه که زمانی فعال میشه که کل صفحه بارگذاری شده باشه، شامل تمام منابع وابسته مثل استایلشیتها و تصاویر. `document.ready` زمانی فعال میشه که ساختار DOM آماده باشه، به این معنا که ساختار سند به طور کامل بارگذاری شده اما منابع خارجی ممکنه هنوز در حال بارگذاری باشن.
88 |
89 | ## مدیریت خطاها
90 |
91 | ### 19. چطوری خطاها رو تو یه زنجیره promise مدیریت میکنی؟
92 | > برای مدیریت خطاها تو یه زنجیره promise میتونی از متد `catch` استفاده کنی.
93 |
94 | ## ماژولها
95 |
96 | ### 20. یک ماژول جاوا اسکریپت چیه؟
97 | > یک ماژول جاوا اسکریپت فایلی هست که کد میتونه بین قسمتهای مختلف یه برنامه با استفاده از دستورات `import` و `export` وارد و صادر بشه. ماژولها به سازماندهی و کپسولهسازی کد کمک میکنن.
98 |
99 | ## مطالب متفرقه
100 |
101 | ### 21. تابع مرتبه بالا (higher-order function) تو جاوا اسکریپت چیه؟
102 | > توابع مرتبه بالا توابعی هستن که میتونن توابع دیگه رو به عنوان آرگومان بپذیرن یا توابعی رو به عنوان نتیجه بازگردونن. مثالها شامل `map`، `filter` و `reduce` هستن.
103 |
104 | ### 22. مفهوم immutability تو جاوا اسکریپت چیه؟
105 | > مفهوم immutability به ناتوانی در تغییر یه شیء یا ساختار داده پس از ایجاد اشاره داره. به جای تغییر شیء موجود، شیءهای جدیدی با مقادیر بهروزرسانی شده ایجاد میشن.
106 |
107 | ### 23. فرآیند Currying تو جاوا اسکریپت چیه؟
108 | > فرآیند Currying تبدیل تابعیه که چندین آرگومان میپذیره به مجموعهای از توابع که هر کدوم یه آرگومان رو میپذیرن. این اجازه میده که تابع به صورت جزئی اعمال بشه.
109 |
110 | ### 24. مفهوم Polyfill چیه؟
111 | > مفهوم Polyfill کدی هست که یه ویژگی رو روی مرورگرهای وب پیادهسازی میکنه که به طور بومی از اون ویژگی پشتیبانی نمیکنن، و بدین ترتیب سازگاری رو تو مرورگرهای مختلف تضمین میکنه.
112 |
113 | ### 25. هدف `Object.keys` چیه؟
114 | > هدف `Object.keys` بازگرداندن یه آرایه از نامهای ویژگیهای قابل شمارش یه شیء هست.
115 |
116 | ### 26. هدف `Object.values` چیه؟
117 | > هدف `Object.values` بازگرداندن یه آرایه از مقادیر ویژگیهای قابل شمارش یه شیء هست.
118 |
119 | ### 27. هدف `Object.entries` چیه؟
120 | > هدف `Object.entries` تبدیل یه شیء به یه آرایه از زوجهای کلید-مقدار هست.
121 |
122 | ### 28. تفاوت بین متدهای `slice` و `splice` چیه؟
123 | > تفاوت `slice` اینه که یه کپی سطحی از قسمتی از یه آرایه به یه آرایه جدید بازمیگردونه. `splice` محتوای یه آرایه رو با حذف یا جایگزینی عناصر موجود و/یا اضافه کردن عناصر جدید تغییر میده.
124 |
--------------------------------------------------------------------------------
/FA/03-advance.md:
--------------------------------------------------------------------------------
1 | # سوالات پیشرفته جاوا اسکریپت
2 |
3 | ## مبانی جاوا اسکریپت
4 |
5 | ### 1. موتور جاوا اسکریپت چیه؟
6 | > موتور جاوا اسکریپت برنامهایه که کدهای جاوا اسکریپت رو اجرا میکنه. مثلاً V8 گوگل، SpiderMonkey موزیلا و Chakra مایکروسافت از این دسته هستن.
7 |
8 | ### 2. مفهوم context اجرای کد و call stack در جاوا اسکریپت رو توضیح بده.
9 | > برای توضیح، context اجرای کد محیطیه که کد جاوا اسکریپت در اون اجرا میشه. این محیط شامل this binding، متغیرها، اشیاء و توابع میشه. call stack هم یه ساختار دادهای به نام stack هست که پیگیری فراخوانیهای توابع رو انجام میده و به موتور جاوا اسکریپت کمک میکنه تا بدونه بعد از اجرای هر تابع باید به کجا برگرده.
10 |
11 | ### 3. حلقه رویداد (event loop) چیه و چطور کار میکنه؟
12 | > حلقه رویداد اجازه میده جاوا اسکریپت عملیات غیرمسدودکننده (non-blocking) انجام بده با این که وظایف رو هر وقت که ممکن باشه به هسته سیستم (system kernel) واگذار کنه. این حلقه بهطور مداوم call stack و callback queue رو بررسی میکنه و اگر call stack خالی باشه، اولین وظیفه از صف (queue) رو به call stack اضافه میکنه.
13 |
14 | ## توابع پیشرفته و closures
15 |
16 | ### 4. مفهوم توابع مرتبهبالا (higher-order functions) رو توضیح بده و یک مثال بزن.
17 | > توابع مرتبهبالا توابعی هستن که میتونن توابع دیگه رو به عنوان آرگومان بپذیرن یا توابع رو به عنوان نتیجه برگردونن. مثال:
18 | > ```javascript
19 | > function higherOrder(fn) {
20 | > // یه تابع جدید برمیگردونه که مقداری میگیره و تابع ورودی رو روی اون اعمال میکنه
21 | > return function(value) {
22 | > return fn(value);
23 | > };
24 | > }
25 | > // تابعی به نام 'double' ایجاد کن که ورودی خود رو با استفاده از تابع higherOrder دو برابر کنه
26 | > const double = higherOrder((x) => x * 2);
27 | > console.log(double(5)); // 10
28 | > ```
29 |
30 |
31 | ### 5. تولیدکنندهها (generators) چی هستن و چطور ازشون استفاده میکنیم؟
32 | > تولیدکنندهها توابعی هستن که میتونن در وسط اجرا متوقف بشن و بعداً از همون جا ادامه پیدا کنن. برای تعریف تولیدکننده از سینتکس `function*` و کلیدواژه `yield` استفاده میکنیم. مثال:
33 | > ```javascript
34 | > function* generator() {
35 | > yield 1; // توقف کن و 1 رو برگردون
36 | > yield 2; // توقف کن و 2 رو برگردون
37 | > yield 3; // توقف کن و 3 رو برگردون
38 | > }
39 | > const gen = generator();
40 | > console.log(gen.next().value); // 1
41 | > console.log(gen.next().value); // 2
42 | > console.log(gen.next().value); // 3
43 | > ```
44 |
45 | ### 6. مفهوم memoization در جاوا اسکریپت رو توضیح بده.
46 | > مفهوم memoization یه تکنیک بهینهسازی هست که برای سریعتر کردن فراخوانیهای توابع استفاده میشه. این تکنیک با کش کردن نتایج فراخوانیهای پرهزینه و برگشت دادن نتیجه کش شده زمانی که ورودیهای مشابه دوباره اتفاق میفته، عمل میکنه.
47 |
48 | ## اشیاء و پروتوتایپها
49 |
50 | ### 7. تفاوت بین `Object.create()` و `Object.assign()` چیه؟
51 | > برای توضیح، `Object.create()` یه شیء جدید با پروتوتایپ و ویژگیهای مشخصشده ایجاد میکنه، در حالی که `Object.assign()` ویژگیها رو از یک یا چند شیء منبع به یک شیء هدف کپی میکنه.
52 |
53 | ### 8. شیء `Proxy` چیه و چطور ازش استفاده میکنیم؟
54 | > شیء `Proxy` برای تعریف رفتار سفارشی برای عملیاتهای بنیادی (مثل جستجوی ویژگی، انتساب، شمارش و فراخوانی تابع) استفاده میشه. مثال:
55 | > ```javascript
56 | > const target = {};
57 | > const handler = {
58 | > get: function(obj, prop) {
59 | > // اگر ویژگی وجود داشته باشه مقدار اون رو برگردون، در غیر این صورت 42 رو برگردون
60 | > return prop in obj ? obj[prop] : 42;
61 | > }
62 | > };
63 | > const proxy = new Proxy(target, handler);
64 | > console.log(proxy.answer); // 42
65 | > ```
66 |
67 | ## ناهمزمانی و بهینهسازی عملکرد
68 |
69 | ### 9. تفاوت بین microtasks و macrotasks در حلقه رویداد چیه؟
70 | > برای توضیح، microtasks کارهایی هستن که بعد از پایان عملیات فعلی اما قبل از رندرینگ اجرا میشن. مثالها شامل promises و callback های `MutationObserver` هستن. از طرف دیگه، macrotasks کارهایی هستن که بعد از رندرینگ اجرا میشن. مثالها شامل `setTimeout`، `setInterval` و وظایف I/O هستن.
71 |
72 | ### 10. وب ورکرا (Web Workers) چی هستن و چطور عملکرد رو بهبود میدن؟
73 | > وب ورکرا اجازه میدن که کد جاوا اسکریپت رو در پسزمینه و در یک نخ جدا از نخ اصلی اجرا کنید، که این امکان رو فراهم میکنه که عملیاتهای سنگین پردازشی رو بدون مسدود کردن رابط کاربری (UI) انجام بدید.
74 |
75 |
76 | ## دستکاری پیشرفته DOM
77 |
78 | ### 11. مفهوم Shadow DOM چی هست و چطور ازش استفاده میکنیم؟
79 | > برای توضیح، Shadow DOM یه استاندارد وب هست که به شما اجازه میده یک درخت DOM و استایلهای CSS رو محصور کنید بهطوری که از DOM اصلی سند پنهان و جدا بشه. این برای ایجاد کامپوننتهای وب مفید هست.
80 |
81 | ### 12. چطور میتونید DOM رو به طور مؤثر بروزرسانی کنید تا از reflows و repaints کمینه کنید؟
82 | > برای بروزرسانی مؤثر DOM، تغییرات DOM رو دستهبندی کنید، از `DocumentFragment` استفاده کنید، از layout thrashing کم کنید و برای انیمیشنها از `requestAnimationFrame` استفاده کنید.
83 |
84 | ## مدیریت حافظه
85 |
86 | ### 13. مفهوم جمعآوری زباله (garbage collection) در جاوا اسکریپت چیه؟
87 | > جمعآوری زباله فرآیندیه که بهطور خودکار حافظهای که دیگه استفاده نمیشه رو آزاد میکنه. یعنی اشیایی که دیگه بهشون نیازی نیست یا بهشون دسترسی نداریم، حذف میشن.
88 |
89 | ### 14. نشت حافظه (memory leaks) چیه و چطور میتونیم ازش جلوگیری کنیم؟
90 | > نشت حافظه زمانی پیش میاد که حافظهای که به یه چیزی اختصاص داده شده بهدرستی آزاد نشه، و این باعث میشه مصرف حافظه با گذشت زمان بیشتر بشه. برای جلوگیری از این مشکل، باید ارجاعها به اشیایی که دیگه لازم نیستن رو حذف کنیم، از متغیرهای جهانی کمتر استفاده کنیم و از ابزارهایی مثل Chrome DevTools برای مانیتور کردن مصرف حافظه استفاده کنیم.
91 |
92 | ## مدیریت خطا پیشرفته
93 |
94 | ### 15. خطاهای سفارشی (custom errors) چی هستن و چطور میتونیم اونها رو در جاوا اسکریپت ایجاد کنیم؟
95 | > خطاهای سفارشی نوعی از خطاها هستن که توسط کاربر تعریف میشن و از کلاس داخلی `Error` ارثبری میکنن. مثال:
96 | > ```javascript
97 | > class CustomError extends Error {
98 | > constructor(message) {
99 | > super(message);
100 | > this.name = 'CustomError';
101 | > }
102 | > }
103 | > throw new CustomError('This is a custom error');
104 | > ```
105 |
106 | ## ماژولها و ابزارهای ساخت
107 |
108 | ### 16. تفاوت بین ماژولهای ES6 و ماژولهای CommonJS چیه؟
109 | > ماژولهای ES6 از دستورات `import` و `export` استفاده میکنن و بهطور استاتیکی تحلیل میشن، که اجازه میده تا بخشهای غیرضروری (tree shaking) حذف بشه. ماژولهای CommonJS از `require` و `module.exports` استفاده میکنن و بهصورت پویا بارگذاری میشن.
110 |
111 | ### 17. باندلرها (Bundlers) مثل Webpack چی هستن و چرا ازشون استفاده میشه؟
112 | > باندلرهایی مثل Webpack ابزارهایی هستن که ماژولهای جاوا اسکریپت رو به یک یا چند فایل بهینهشده برای مرورگر تبدیل میکنن. این ابزارها به مدیریت وابستگیها، تقسیم کد (code splitting) و بهینهسازی خروجی برای تولید کمک میکنن.
113 |
114 | ## امنیت
115 |
116 | ### 18. رایجترین آسیبپذیریهای امنیتی در جاوا اسکریپت چی هستن و چطور میتونیم اونها رو کاهش بدیم؟
117 | > آسیبپذیریهای رایج شامل XSS (Cross-Site Scripting)، CSRF (Cross-Site Request Forgery)، و تزریق کد (code injection) هستن. میتونیم این مشکلات رو با اعتبارسنجی و پاکسازی ورودیهای کاربر، استفاده از Content Security Policy (CSP)، و پیادهسازی مکانیزمهای احراز هویت و مجوزدهی مناسب کاهش بدیم.
118 |
119 | ## ویژگیهای پیشرفته APIها و مرورگر
120 |
121 | ### 19. سرویس ورکرها (service workers) چی هستن و چطور اپلیکیشنهای وب پیشرفته (PWAs) رو ممکن میکنن؟
122 | > سرویس ورکرها اسکریپتهایی هستن که در پسزمینه اجرا میشن و امکاناتی مثل کش کردن، اعلانهای اجباری (push notifications)، و همگامسازی در پسزمینه رو فراهم میکنن. این ویژگیها امکان استفاده آفلاین و بهبود عملکرد اپلیکیشنهای وب پیشرفته (PWAs) رو فراهم میکنن.
123 |
124 | ### 20. استفاده از IndexedDB در اپلیکیشنهای وب رو توضیح بده.
125 | > برای توضیح، IndexedDB یک API سطح پایین برای ذخیره حجم زیادی از دادههای ساختاریافته در مرورگره. این API امکان دسترسی غیرهمزمان به دادهها رو فراهم میکنه و از تراکنشها پشتیبانی میکنه، که اون رو برای ذخیرهسازی آفلاین و نیازهای دادهای پیچیده مناسب میکنه.
126 |
127 | ### 21. وب اسمبلی چیه و چطور با جاوا اسکریپت تعامل داره؟
128 | > وب اسمبلی یه فرمت باینری برای یه ماشین مجازی مبتنی بر استکه که برای کامپایل کردن زبانهای سطح بالا مثل C، C++، و Rust طراحی شده. این تکنولوژی اجازه میده که کد با سرعت بالا توی مرورگر اجرا بشه و میتونه از طریق API جاوا اسکریپت باهاش تعامل داشته باشه.
129 |
130 | ## الگوها و روشهای پیشرفته
131 |
132 | ### 22. مفهوم برنامهنویسی تابعی رو توضیح بده و بگو چطور به جاوا اسکریپت مربوط میشه؟
133 | > برنامهنویسی تابعی یه پارادایم برنامهنویسیه که محاسبات رو به عنوان ارزیابی توابع ریاضی در نظر میگیره و از تغییر حالت و دادههای متغیر اجتناب میکنه. جاوا اسکریپت از برنامهنویسی تابعی پشتیبانی میکنه از طریق توابع کلاس اول (first-class functions)، توابع مرتبهبالا (higher-order functions)، و متدهایی مثل `map`، `reduce` و `filter`.
134 |
135 | ### 23. الگوی مشاهدهگر (observer pattern) چیه و چطور توی جاوا اسکریپت پیادهسازی میشه؟
136 | > الگوی مشاهدهگر یه الگوی طراحی هست که توش یه شیء (subject) یه لیست از وابستگیها (observables) رو نگه میداره و به اونا از تغییرات وضعیت اطلاع میده. این الگو میتونه با استفاده از event listenerها یا کتابخانههایی مثل RxJS برای برنامهنویسی واکنشی پیادهسازی بشه.
137 | ### 24. چطور میتونیم debouncing و throttling رو توی جاوا اسکریپت پیادهسازی کنیم؟
138 | > برای توضیح، debouncing اطمینان حاصل میکنه که یه تابع فقط بعد از گذشت یه تاخیر مشخص از آخرین فراخوانی اجرا بشه. throttling هم اطمینان حاصل میکنه که یه تابع حداکثر یک بار در یه بازه زمانی مشخص فراخوانی بشه. مثال:
139 | > ```javascript
140 | > function debounce(fn, delay) {
141 | > let timer;
142 | > return function(...args) {
143 | > // تایمر قبلی رو پاک کن، اگر وجود داشت، و یه تایمر جدید تنظیم کن
144 | > clearTimeout(timer);
145 | > timer = setTimeout(() => fn.apply(this, args), delay);
146 | > };
147 | > }
148 | > function throttle(fn, limit) {
149 | > let lastCall = 0;
150 | > return function(...args) {
151 | > const now = Date.now();
152 | > // اگر به اندازه کافی از فراخوانی قبلی گذشته باشه، تابع رو اجرا کن
153 | > if (now - lastCall >= limit) {
154 | > lastCall = now;
155 | > fn.apply(this, args);
156 | > }
157 | > };
158 | > }
159 | > ```
160 |
161 | ### 25. مفهوم duck typing در جاوا اسکریپت چیه؟
162 | > برای توضیح، Duck typing مفهومی هست که در اون قابلیت استفاده یه شیء بر اساس وجود متدها و ویژگیهای خاصی سنجیده میشه، نه بر اساس نوع واقعی اون شیء. معمولاً این مفهوم رو با عبارت "اگر شبیه اردک به نظر میاد و صدای اردک میده، پس اردکه" توضیح میدن.
163 |
164 | ### 26. بهینهسازی فراخوانی در انتها (tail call optimization) چیه و چطور توی جاوا اسکریپت کار میکنه؟
165 | > بهینهسازی فراخوانی در انتها یه ویژگی در بعضی از موتورهای جاوا اسکریپته که فراخوانیهای بازگشتی که در موقعیت انتهایی (آخرین عمل در تابع) قرار دارن رو بهینه میکنه. این کار باعث استفاده بهینهتر از حافظه میشه و میتونه از بروز خطاهای stack overflow جلوگیری کنه.
166 |
--------------------------------------------------------------------------------
/FA/04-ES5-2009.md:
--------------------------------------------------------------------------------
1 | # سوالات ES5 - 2009
2 |
3 | ## ویژگی "use strict" در جاوا اسکریپت
4 |
5 | ### 1. چرا از "use strict" استفاده میکنیم و چه مزایایی داره؟
6 | استفاده از "use strict" باعث میشه کدهای جاوا اسکریپت در حالت "strict mode" اجرا بشن. این حالت به شما کمک میکنه کدهای تمیزتر و با خطای کمتری بنویسید، مانند جلوگیری از استفاده از متغیرهای اعلام نشده. "use strict" فقط یک عبارت رشتهای است و اگر مرورگر آن را نشناسد، خطا نمیدهد.
7 |
8 | ```javascript
9 | "use strict";
10 | x = 3.14; // ReferenceError: x is not defined
11 | ```
12 |
13 | تو این مثال، چون از "use strict" استفاده کردیم، اگر متغیری رو بدون var, let یا const تعریف کنیم، خطا میده. این باعث میشه که از خطاهای رایج جلوگیری بشه.
14 |
15 | ## دسترسی به کاراکترهای رشته با استفاده از ایندکس
16 |
17 | ### 2. چطور میتونیم به کاراکترهای یه رشته با استفاده از ایندکس دسترسی داشته باشیم؟
18 | علاوه بر متد charAt که برای دسترسی به کاراکترهای رشته استفاده میشد، میتونید به کاراکترهای رشته با استفاده از ایندکس هم دسترسی داشته باشید، مشابه کاری که با آرایهها انجام میدهید.
19 |
20 | ```javascript
21 | var str = "HELLO WORLD";
22 | console.log(str.charAt(0)); // 'H'
23 | console.log(str[0]); // 'H'
24 | ```
25 |
26 | این روش دسترسی به کاراکترها ممکنه در بعضی مرورگرهای قدیمی به درستی کار نکنه، ولی برای مرورگرهای مدرن مشکلی نداره.
27 |
28 | ## رشتههای چند خطی
29 |
30 | ### 3. چطور میتونیم رشتههای چند خطی بنویسیم؟
31 | میتونید با استفاده از بکاسلش `\` رشتههای چند خطی ایجاد کنید.
32 |
33 | ```javascript
34 | var str = "Hello \
35 | Dolly!";
36 | ```
37 |
38 | این روش ممکنه تو همه مرورگرها به درستی کار نکنه. یه روش امنتر برای نوشتن رشتههای چند خطی، استفاده از عملیات جمع رشتههاست.
39 |
40 | ```javascript
41 | var str = "Hello " +
42 | "Dolly!";
43 | ```
44 |
45 | ## استفاده از کلمات رزرو شده به عنوان نام ویژگی
46 |
47 | ### 4. آیا میتونیم از کلمات رزرو شده به عنوان نام ویژگیها استفاده کنیم؟
48 | بله، در ES5 به شما اجازه داده شده که از کلمات رزرو شده به عنوان نام ویژگیها استفاده کنید.
49 |
50 | ```javascript
51 | var obj = {name: "John", new: "yes"};
52 | ```
53 |
54 | این ویژگی باعث میشه که بتونید از کلمات بیشتری به عنوان نام ویژگیها استفاده کنید.
55 |
56 | ## متد String.trim
57 |
58 | ### 5. متد trim چطور کار میکنه؟
59 | متد trim فضای خالی از دو طرف یه رشته رو حذف میکنه.
60 |
61 | ```javascript
62 | var str = " Hello World! ";
63 | console.log(str.trim()); // 'Hello World!'
64 | ```
65 |
66 | این متد به شما کمک میکنه که فضای خالی غیرضروری رو از رشتهها حذف کنید.
67 |
68 | ## متد Array.isArray
69 |
70 | ### 6. چطور میتونیم بررسی کنیم که یه شیء آرایه هست یا نه؟
71 | متد Array.isArray بررسی میکنه که آیا یه شیء یه آرایه هست یا نه.
72 |
73 | ```javascript
74 | var fruits = ["Banana", "Orange", "Apple", "Mango"];
75 | console.log(Array.isArray(fruits)); // true
76 | ```
77 |
78 | این متد به خصوص برای مواقعی که نیاز دارید نوع دادهای که باهاش کار میکنید رو بدونید، خیلی مفیده.
79 |
80 | ## متد Array.forEach
81 |
82 | ### 7. متد forEach چطور کار میکنه؟
83 | متد forEach یه تابع رو برای هر عنصر آرایه فراخوانی میکنه.
84 |
85 | ```javascript
86 | var txt = "";
87 | var numbers = [45, 4, 9, 16, 25];
88 | numbers.forEach(function(value) {
89 | txt += value + "
";
90 | });
91 | console.log(txt);
92 | ```
93 |
94 | این متد به شما کمک میکنه که به راحتی روی عناصر آرایه پیمایش کنید و عملیاتی رو روی هر عنصر انجام بدید.
95 |
96 | ## متد Array.map
97 |
98 | ### 8. متد map چطور کار میکنه و چه کاربردی داره؟
99 | متد map برای هر عنصر آرایه یه تابع رو اجرا میکنه و یه آرایه جدید با نتایج برمیگردونه.
100 |
101 | ```javascript
102 | var numbers1 = [45, 4, 9, 16, 25];
103 | var numbers2 = numbers1.map(function(value) {
104 | return value * 2;
105 | });
106 | console.log(numbers2); // [90, 8, 18, 32, 50]
107 | ```
108 |
109 | این متد برای مواقعی که نیاز دارید یه آرایه جدید با تغییراتی روی عناصر آرایه اصلی بسازید، خیلی مفیده.
110 |
111 | ## متد Array.filter
112 |
113 | ### 9. متد filter چطور کار میکنه و چه کاربردی داره؟
114 | متد filter یه آرایه جدید با همه عناصری که شرط تابع رو برآورده میکنن، برمیگردونه.
115 |
116 | ```javascript
117 | var numbers = [45, 4, 9, 16, 25];
118 | var over18 = numbers.filter(function(value) {
119 | return value > 18;
120 | });
121 | console.log(over18); // [45, 25]
122 | ```
123 |
124 | این متد به شما کمک میکنه که یه آرایه جدید بسازید که فقط شامل عناصری هست که شرط خاصی رو برآورده میکنن.
125 |
126 | ## متد Array.reduce
127 |
128 | ### 10. متد reduce چطور کار میکنه و چه کاربردی داره؟
129 | متد reduce برای خلاصهسازی یا کاهش همه عناصر یه آرایه به یه مقدار واحد استفاده میشه.
130 |
131 | ```javascript
132 | var numbers = [45, 4, 9, 16, 25];
133 | var sum = numbers.reduce(function(total, value) {
134 | return total + value;
135 | });
136 | console.log(sum); // 99
137 | ```
138 |
139 | این متد به شما کمک میکنه که مقادیری مثل جمع کل عناصر رو به دست بیارید.
140 |
141 | ## متد Array.reduceRight
142 |
143 | ### 11. متد reduceRight چطور کار میکنه و چه تفاوتی با reduce داره؟
144 | متد reduceRight هم مشابه reduce عمل میکنه، با این تفاوت که از انتهای آرایه به سمت ابتدای آرایه عمل میکنه.
145 |
146 | ```javascript
147 | var numbers = [45, 4, 9, 16, 25];
148 | var sum = numbers.reduceRight(function(total, value) {
149 | return total + value;
150 | });
151 | console.log(sum); // 99
152 | ```
153 |
154 | این متد وقتی به درد میخوره که نیاز دارید عملیات کاهش رو از انتهای آرایه شروع کنید.
155 |
156 | ## متد Array.every
157 |
158 | ### 12. متد every چطور کار میکنه و چه کاربردی داره؟
159 | متد every بررسی میکنه که آیا همه عناصر آرایه شرط خاصی رو برآورده میکنن یا نه.
160 |
161 | ```javascript
162 | var numbers = [45, 4, 9, 16, 25];
163 | var allOver18 = numbers.every(function(value) {
164 | return value > 18;
165 | });
166 | console.log(allOver18); // false
167 | ```
168 |
169 | این متد برای مواقعی که نیاز دارید مطمئن بشید همه عناصر یه شرط خاص رو دارن، خیلی مفیده.
170 |
171 | ## متد Array.some
172 |
173 | ### 13. متد some چطور کار میکنه و چه کاربردی داره؟
174 | متد some بررسی میکنه که آیا حداقل یکی از عناصر آرایه شرط خاصی رو برآورده میکنه یا نه.
175 |
176 | ```javascript
177 | var numbers = [45, 4, 9, 16, 25];
178 | var someOver18 = numbers.some(function(value) {
179 | return value > 18;
180 | });
181 | console.log(someOver18); // true
182 | ```
183 |
184 | این متد به خصوص برای مواقعی که نیاز دارید بررسی کنید آیا حداقل یک عنصر شرایط خاصی رو داره، مفیده.
185 |
186 | ## متد Array.indexOf
187 |
188 | ### 14. چطور میتونیم با indexOf موقعیت یه عنصر رو تو یه آرایه پیدا کنیم؟
189 | متد indexOf موقعیت اولین عنصر مشابه رو تو یه آرایه برمیگردونه.
190 |
191 | ```javascript
192 | var fruits = ["Apple", "Orange", "Apple", "Mango"];
193 | var index = fruits.indexOf("Apple");
194 | console.log(index); // 0
195 | ```
196 |
197 | این متد برای مواقعی که نیاز دارید موقعیت یه عنصر خاص رو پیدا کنید، خیلی کاربردیه.
198 |
199 | ## متد Array.lastIndexOf
200 |
201 | ### 15. متد lastIndexOf چطور کار میکنه و چه تفاوتی با indexOf داره؟
202 | متد lastIndexOf مشابه indexOf عمل میکنه، با این تفاوت که جستجو رو از انتهای آرایه شروع میکنه.
203 |
204 | ```javascript
205 | var fruits = ["Apple", "Orange", "Apple", "Mango"];
206 | var index = fruits.lastIndexOf("Apple");
207 | console.log(index); // 2
208 | ```
209 |
210 | این متد برای مواقعی که نیاز دارید موقعیت آخرین عنصر مشابه رو پیدا کنید، مفیده.
211 |
212 | ## متد JSON.parse
213 |
214 | ### 16. متد JSON.parse چطور کار میکنه و چه کاربردی داره؟
215 | متد JSON.parse برای تبدیل یه رشته متنی JSON
216 |
217 | به یه شیء جاوا اسکریپت استفاده میشه.
218 |
219 | ```javascript
220 | var jsonString = '{"name":"John", "age":30, "city":"New York"}';
221 | var obj = JSON.parse(jsonString);
222 | console.log(obj.name); // 'John'
223 | ```
224 |
225 | این متد به خصوص برای مواقعی که دادههای JSON رو از یه سرور دریافت میکنید و نیاز دارید که به صورت یه شیء جاوا اسکریپت باهاش کار کنید، خیلی مفیده.
226 |
227 | ## متد JSON.stringify
228 |
229 | ### 17. متد JSON.stringify چطور کار میکنه و چه کاربردی داره؟
230 | متد JSON.stringify برای تبدیل یه شیء جاوا اسکریپت به یه رشته JSON استفاده میشه.
231 |
232 | ```javascript
233 | var obj = {name: "John", age: 30, city: "New York"};
234 | var jsonString = JSON.stringify(obj);
235 | console.log(jsonString); // '{"name":"John","age":30,"city":"New York"}'
236 | ```
237 |
238 | این متد به خصوص برای مواقعی که نیاز دارید دادهها رو به صورت رشته JSON به یه سرور ارسال کنید، خیلی مفیده.
239 |
240 | ## متد Date.now
241 |
242 | ### 18. متد Date.now چطور کار میکنه و چه کاربردی داره؟
243 | متد Date.now تعداد میلیثانیههای گذشته از تاریخ 1 ژانویه 1970 تا حالا رو برمیگردونه.
244 |
245 | ```javascript
246 | var timeInMs = Date.now();
247 | console.log(timeInMs);
248 | ```
249 |
250 | این متد برای محاسبات زمان و تاریخ خیلی مفیده، مثل محاسبه مدت زمانی که یه عملیات طول کشیده.
251 |
252 | ## متد Date.toISOString
253 |
254 | ### 19. متد toISOString چطور کار میکنه و چه کاربردی داره؟
255 | متد toISOString برای تبدیل یه شیء Date به یه رشته به فرمت استاندارد ISO استفاده میشه.
256 |
257 | ```javascript
258 | var d = new Date();
259 | console.log(d.toISOString());
260 | ```
261 |
262 | این متد برای مواقعی که نیاز دارید تاریخ رو به یه فرمت قابل حمل و استاندارد تبدیل کنید، خیلی مفیده.
263 |
264 | ## متد Date.toJSON
265 |
266 | ### 20. متد toJSON چطور کار میکنه و چه کاربردی داره؟
267 | متد toJSON یه شیء Date رو به یه رشته به فرمت JSON تبدیل میکنه. فرمت JSON تاریخها مشابه استاندارد ISO-8601 هست.
268 |
269 | ```javascript
270 | var d = new Date();
271 | console.log(d.toJSON());
272 | ```
273 |
274 | این متد به خصوص برای مواقعی که نیاز دارید تاریخ رو به یه فرمت JSON برای انتقال دادهها آماده کنید، خیلی مفیده.
275 |
276 | ## استفاده از Getters و Setters
277 |
278 | ### 21. متدهای Getters و Setters چطور کار میکنن و چه کاربردی دارن؟
279 | به شما اجازه میده که متدهای شیء رو به شکلی تعریف کنید که مثل دریافت یا تنظیم یه ویژگی به نظر برسن.
280 |
281 | ```javascript
282 | var person = {
283 | firstName: "John",
284 | lastName: "Doe",
285 | get fullName() {
286 | return this.firstName + " " + this.lastName;
287 | }
288 | };
289 |
290 | console.log(person.fullName); // 'John Doe'
291 | ```
292 |
293 | این مثال یه getter برای ویژگی fullName ایجاد کرده که نام کامل رو برمیگردونه.
294 |
295 | ## متد Object.defineProperty
296 |
297 | ### 22. متد Object.defineProperty چطور کار میکنه و چه کاربردی داره؟
298 | متد Object.defineProperty به شما اجازه میده که یه ویژگی رو تو یه شیء تعریف یا تغییر بدید.
299 |
300 | ```javascript
301 | const person = {
302 | firstName: "John",
303 | lastName : "Doe",
304 | };
305 |
306 | Object.defineProperty(person, "language", {
307 | value: "EN",
308 | writable: true,
309 | enumerable: true,
310 | configurable: true
311 | });
312 |
313 | console.log(person.language); // 'EN'
314 | ```
315 |
316 | این متد برای مواقعی که نیاز دارید کنترل بیشتری روی ویژگیهای شیء داشته باشید، مثل تعیین اینکه آیا ویژگی قابل تغییر یا شمارشپذیر باشه، خیلی مفیده.
317 |
318 | ## متد Object.create
319 |
320 | ### 23. متد Object.create چطور کار میکنه و چه کاربردی داره؟
321 | متد Object.create برای ایجاد یه شیء جدید از یه شیء موجود استفاده میشه.
322 |
323 | ```javascript
324 | const person = {
325 | firstName: "John",
326 | lastName: "Doe"
327 | };
328 |
329 | const man = Object.create(person);
330 | man.firstName = "Peter";
331 | console.log(man.firstName); // 'Peter'
332 | console.log(man.lastName); // 'Doe'
333 | ```
334 |
335 | این متد به خصوص برای مواقعی که نیاز دارید یه شیء جدید رو از یه الگوی موجود ایجاد کنید، خیلی مفیده.
336 |
337 | ## متد Object.keys
338 |
339 | ### 24. متد Object.keys چطور کار میکنه و چه کاربردی داره؟
340 | متد Object.keys یه آرایه شامل کلیدهای یه شیء رو برمیگردونه.
341 |
342 | ```javascript
343 | const person = {
344 | firstName: "John",
345 | lastName: "Doe",
346 | age: 50,
347 | eyeColor: "blue"
348 | };
349 |
350 | const keys = Object.keys(person);
351 | console.log(keys); // ['firstName', 'lastName', 'age', 'eyeColor']
352 | ```
353 |
354 | این متد برای مواقعی که نیاز دارید به کلیدهای یه شیء دسترسی پیدا کنید، خیلی مفیده.
355 |
356 | ## متد Function.bind
357 |
358 | ### 25. متد bind چطور کار میکنه و چه کاربردی داره؟
359 | متد bind به یه شیء اجازه میده که یه متد رو از یه شیء دیگه قرض بگیره.
360 |
361 | ```javascript
362 | const person = {
363 | firstName: "John",
364 | lastName: "Doe",
365 | fullName: function() {
366 | return this.firstName + " " + this.lastName;
367 | }
368 | };
369 |
370 | const member = {
371 | firstName: "Hege",
372 | lastName: "Nilsen",
373 | };
374 |
375 | let fullName = person.fullName.bind(member);
376 | console.log(fullName()); // 'Hege Nilsen'
377 | ```
378 |
379 | این متد به خصوص برای مواقعی که نیاز دارید یه متد رو به یه شیء خاص متصل کنید، خیلی مفیده.
380 |
381 | ## کاماهای پایانی
382 |
383 | ### 26. چطور میتونیم از کاماهای پایانی توی تعریف شیء و آرایه استفاده کنیم؟
384 | به شما اجازه میده که از کاماهای پایانی در تعریف شیء و آرایه استفاده کنید.
385 |
386 | ```javascript
387 | var person = {
388 | firstName: "John",
389 | lastName: "Doe",
390 | age: 46,
391 | };
392 |
393 | var points = [
394 | 1,
395 | 5,
396 | 10,
397 | 25,
398 | 40,
399 | 100,
400 | ];
401 | ```
402 |
403 | این ویژگی به بهبود خوانایی و تمیزتر شدن کدها کمک میکنه، ولی باید توجه داشته باشید که JSON این نوع از کاماهای پایانی رو قبول نمیکنه.
--------------------------------------------------------------------------------
/FA/06-ES7-2016.md:
--------------------------------------------------------------------------------
1 | # سوالات ES7 - 2016
2 |
3 | ## عملگر توان در جاوا اسکریپت
4 |
5 | ### 1. عملگر توان (`**`) در جاوا اسکریپت چطور کار میکنه و چه کاربردهایی داره؟
6 | در ES7، عملگر جدیدی به نام `**` معرفی شد که به شما اجازه میده به سادگی یک عدد رو به توان عدد دیگهای برسونی. این عملگر در واقع جایگزینی سادهتر و مستقیمتر برای تابع `Math.pow` هست و باعث میشه که نوشتن کدهای مربوط به توانها راحتتر بشه.
7 |
8 | ```javascript
9 | const result = 2 ** 3; // 2 به توان 3
10 | console.log(result); // 8
11 | ```
12 |
13 | در این مثال، `2 ** 3` محاسبه میشه و نتیجه 8 برمیگرده. این عملگر، نوشتن توانها رو در جاوا اسکریپت سادهتر و کد رو مختصرتر کرده. این ویژگی به ویژه در محاسبات ریاضی پیچیده که شامل توانهای متعدد هستن، بسیار کارآمده.
14 |
15 | ## عملگر اختصاص توان
16 |
17 | ### 2. عملگر اختصاص توان (`**=`) چطور عمل میکنه و چه مزایایی داره؟
18 | همراه با معرفی عملگر `**` در ES7، عملگر `**=` هم اضافه شد که به شما اجازه میده تا یک عدد رو به توان عدد دیگهای برسونی و نتیجه رو به همون متغیر اختصاص بدی. این عملگر درست مثل عملگرهای `+=` یا `*=` کار میکنه و نوشتن کد رو حتی از قبل هم سادهتر میکنه.
19 |
20 | ```javascript
21 | let num = 4;
22 | num **= 2; // 4 به توان 2
23 | console.log(num); // 16
24 | ```
25 |
26 | در این مثال، مقدار `num` ابتدا 4 هست و بعد از استفاده از `**=`, این مقدار به 16 تغییر پیدا میکنه، چون 4 به توان 2 محاسبه شده. این عملگر وقتی که بخوایم نتیجه یه عملیات توان رو مستقیم به همون متغیر اختصاص بدیم، خیلی مفید و مختصره.
27 |
28 | ## متد Array.includes
29 |
30 | ### 3. متد `Array.includes` در جاوا اسکریپت چه کاربردی داره و چگونه استفاده میشه؟
31 | در ES7، متد جدید `includes` به آرایهها اضافه شد که به شما اجازه میده به راحتی بررسی کنی که آیا یک عنصر خاص در یک آرایه وجود داره یا نه. این متد به جای اینکه مثل `indexOf` ایندکس رو برگردونه، یک مقدار بولین (true یا false) برمیگردونه که این امر بررسی وجود یک عنصر رو بسیار سریعتر و سادهتر میکنه.
32 |
33 | ```javascript
34 | const arr = [1, 2, 3, 4];
35 | console.log(arr.includes(2)); // true
36 | console.log(arr.includes(5)); // false
37 | ```
38 |
39 | در این مثال، `arr.includes(2)` مقدار `true` رو برمیگردونه چون عدد 2 در آرایه موجود هست، و `arr.includes(5)` مقدار `false` رو برمیگردونه چون عدد 5 در آرایه وجود نداره. این متد برای مواقعی که نیاز به بررسی سریع و ساده وجود یک عنصر در آرایه داریم، بسیار مفیده و کد رو تمیزتر و خواناتر میکنه.
40 |
--------------------------------------------------------------------------------
/FA/07-ES8-2017.md:
--------------------------------------------------------------------------------
1 | # سوالات ES8 - 2017
2 |
3 | ## پدینگ رشته در جاوا اسکریپت
4 |
5 | ### 1. پدینگ رشته در جاوا اسکریپت به چه صورت عمل میکنه و چه کاربردهایی داره؟
6 | در ES8، دو متد جدید به نامهای `padStart` و `padEnd` به رشتهها اضافه شدن که به شما اجازه میدن یک رشته رو از ابتدا یا انتها با کاراکترهای دیگری پر کنی تا به طول مشخص شده برسه. این متدها به ویژه زمانی مفید هستن که بخوای یک رشته رو به فرمت خاصی تبدیل کنی، مثل اضافه کردن صفرهای پیشفرض به یک عدد برای نمایش بهتر.
7 |
8 | ```javascript
9 | const str = '5';
10 | console.log(str.padStart(3, '0')); // '005' - پدینگ از ابتدا
11 | console.log(str.padEnd(3, '0')); // '500' - پدینگ از انتها
12 | ```
13 |
14 | در این مثال، `padStart` رشته `5` رو از ابتدا با `0` پر میکنه تا به طول 3 برسه و `padEnd` همین کار رو از انتها انجام میده. این قابلیت برای مواقعی که نیاز به فرمتبندی خاصی داری، مثل نمایش شمارههای ثابت یا کدهای محصول، بسیار مفیده.
15 |
16 | ## متد Object.entries
17 |
18 | ### 2. متد `Object.entries` در جاوا اسکریپت چه کاربردی داره و چگونه کار میکنه؟
19 | متد `Object.entries` در ES8 معرفی شد و به شما این امکان رو میده که یک شیء رو به یک آرایه از زوجهای کلید-مقدار تبدیل کنی. این متد تمام ویژگیهای شمارشپذیر یک شیء رو به صورت آرایهای از آرایهها برمیگردونه که هر کدوم شامل یک کلید و یک مقدار هستن.
20 |
21 | ```javascript
22 | const obj = { a: 1, b: 2, c: 3 };
23 | console.log(Object.entries(obj)); // [['a', 1], ['b', 2], ['c', 3]]
24 | ```
25 |
26 | در این مثال، `Object.entries` ویژگیهای شیء `obj` رو به یک آرایه از زوجهای کلید-مقدار تبدیل میکنه. این متد به ویژه برای مواقعی که نیاز داری یک شیء رو به فرمتهای قابل پردازشتری مثل آرایهها تبدیل کنی، بسیار مفیده.
27 |
28 | ## متد Object.values
29 |
30 | ### 3. متد `Object.values` چه مزایایی داره و چگونه استفاده میشه؟
31 | متد `Object.values` در ES8 اضافه شد و به شما اجازه میده که فقط مقادیر ویژگیهای یک شیء رو به صورت یک آرایه برگردونی. این متد مشابه `Object.entries` عمل میکنه، اما به جای برگردوندن زوجهای کلید-مقدار، تنها مقادیر رو برمیگردونه.
32 |
33 | ```javascript
34 | const obj = { a: 1, b: 2, c: 3 };
35 | console.log(Object.values(obj)); // [1, 2, 3]
36 | ```
37 |
38 | در این مثال، `Object.values` مقادیر ویژگیهای شیء `obj` رو به صورت یک آرایه برمیگردونه. این متد برای مواقعی که فقط به مقادیر نیاز داری و نیازی به کلیدها نداری، مفیده. مثلاً وقتی که میخوای روی همه مقادیر یک شیء یک عملیات خاص انجام بدی.
39 |
40 | ## سینتکس async/await
41 |
42 | ### 4. سینتکس `async/await` در جاوا اسکریپت چگونه کار میکنه و چه مزایایی داره؟
43 | در ES8، سینتکس جدیدی به نام `async/await` معرفی شد که کار با کدهای غیرهمزمان رو بسیار سادهتر و قابل فهمتر میکنه. با استفاده از `async/await` میتونی کدی بنویسی که به ظاهر همزمان به نظر میاد، اما در واقع به صورت غیرهمزمان اجرا میشه. توابعی که با `async` تعریف میشن یک `Promise` برمیگردونن و `await` باعث میشه که کد منتظر بمونه تا اون `Promise` حل یا رد بشه.
44 |
45 | ```javascript
46 | async function fetchData() {
47 | const response = await fetch('https://api.example.com/data');
48 | const data = await response.json();
49 | return data;
50 | }
51 |
52 | fetchData().then(data => console.log(data));
53 | ```
54 |
55 | در این مثال، `fetchData` یک تابع غیرهمزمانه که با `await` منتظر میمونه تا دادهها از API برگردن و بعد اونها رو پردازش میکنه. این سینتکس به شما کمک میکنه که کدهای غیرهمزمانت رو به روشی بنویسی که خوانایی و نگهداری بهتری داشته باشه، بدون اینکه نیاز به استفاده از زنجیرههای طولانی `then` داشته باشی.
56 |
57 | ## کاماهای پایانی در توابع
58 |
59 | ### 5. استفاده از کاماهای پایانی در لیست پارامترها و فراخوانی توابع چه کاربردی داره؟
60 | در ES8، امکان استفاده از کاماهای پایانی در لیست پارامترهای توابع و فراخوانیهای توابع فراهم شد. این ویژگی به خصوص زمانی مفیده که بخوای کدت رو در طول زمان تغییر بدی، چون با اضافه کردن پارامترهای جدید نیازی به تغییر خط قبلی نداری. این کار به خوانایی کد کمک میکنه و مقایسه تغییرات در کد رو سادهتر میکنه.
61 |
62 | ```javascript
63 | function sum(a, b, c,) {
64 | return a + b + c;
65 | }
66 | console.log(sum(1, 2, 3,)); // 6
67 | ```
68 |
69 | در این مثال، از یک کاما در انتهای لیست پارامترها و آرگومانها استفاده شده. این کاماها هیچ تاثیری روی اجرای کد ندارن، اما به شما کمک میکنن که کد تمیزتر و مدیریت تغییرات راحتتر باشه.
70 |
71 | ## متد Object.getOwnPropertyDescriptors
72 |
73 | ### 6. متد `Object.getOwnPropertyDescriptors` چه اطلاعاتی ارائه میده و چطور میشه از اون استفاده کرد؟
74 | متد `Object.getOwnPropertyDescriptors` در ES8 معرفی شد و به شما اجازه میده که همه توصیفکنندههای ویژگیهای یک شیء رو به صورت یک شیء جدید برگردونی. این توصیفکنندهها شامل اطلاعاتی مثل قابل نوشتن بودن، شمارشپذیری و قابل پیکربندی بودن هر ویژگی هستن.
75 |
76 | ```javascript
77 | const obj = { a: 1, get b() { return 2; } };
78 | console.log(Object.getOwnPropertyDescriptors(obj));
79 | /* Output:
80 | {
81 | a: { value: 1, writable: true, enumerable: true, configurable: true },
82 | b: {
83 | get: [Function: get b],
84 | set: undefined,
85 | enumerable: true,
86 | configurable: true
87 | }
88 | }
89 | */
90 | ```
91 |
92 | در این مثال، `Object.getOwnPropertyDescriptors` تمام اطلاعات مربوط به ویژگیهای شیء `obj` رو برمیگردونه، شامل اینکه آیا اون ویژگیها قابل تغییر هستن یا نه. این متد برای مواقعی که نیاز داری جزئیات کامل از ویژگیهای یک شیء رو بدونی، بسیار مفیده. این اطلاعات میتونن به شما در مدیریت پیشرفتهتری از اشیاء کمک کنن، مثل ایجاد کپیهای دقیقتر یا انجام تغییرات کنترلشده روی ویژگیها.
93 |
--------------------------------------------------------------------------------
/FA/08-ES9-2018.md:
--------------------------------------------------------------------------------
1 | # سوالات ES9 - 2018
2 |
3 | ## حلقه Asynchronous Iteration
4 |
5 | ### 1. چطور میتونی با استفاده از `for-await-of` روی دادههای غیرهمزمان تکرار کنی و این قابلیت چه مزایایی داره؟
6 | در ES9، یک قابلیت جدید به نام `for-await-of` معرفی شد که به شما اجازه میده روی دادههایی که به صورت غیرهمزمان تولید میشن، تکرار کنی. این حلقه مشابه `for-of` کار میکنه، با این تفاوت که به طور خاص برای کار با `Promise`ها طراحی شده. این قابلیت وقتی خیلی مفید هست که نیاز داشته باشی منتظر تکمیل چندین عملیات غیرهمزمان بشی، مثل دریافت داده از یک API یا دیتابیس، و بخوای روی نتایج اونها یکی یکی کار کنی.
7 |
8 | ```javascript
9 | async function* asyncGenerator() {
10 | yield 'Hello';
11 | yield 'World';
12 | }
13 |
14 | (async () => {
15 | for await (const value of asyncGenerator()) {
16 | console.log(value); // هر مقدار رو لاگ کن
17 | }
18 | // Output:
19 | // Hello
20 | // World
21 | })();
22 | ```
23 |
24 | در این مثال، از یک تابع غیرهمزمان (`asyncGenerator`) برای تولید دادهها استفاده شده. سپس با `for-await-of` دادهها یکی یکی دریافت و چاپ میشن. این قابلیت به شما اجازه میده تا به طور کارآمد دادههای غیرهمزمان رو مدیریت کنی و مطمئن بشی که هر داده قبل از پردازش به طور کامل دریافت شده.
25 |
26 | ## متد Promise.prototype.finally
27 |
28 | ### 2. متد `finally` چطور میتونه به بهبود مدیریت `Promise`ها کمک کنه و چه کاربردهایی داره؟
29 | متد `finally` به `Promise`ها اضافه شد تا اطمینان حاصل بشه که یک تکه کد بعد از تکمیل `Promise`، چه با موفقیت و چه با شکست، اجرا میشه. این متد به ویژه در مواردی مفیده که نیاز داری بعد از اتمام یک عملیات، حتماً یک کار خاص مثل پاکسازی یا بهروزرسانی رابط کاربری رو انجام بدی، بدون توجه به نتیجه اون عملیات.
30 |
31 | ```javascript
32 | fetch('https://api.example.com/data')
33 | .then(response => response.json())
34 | .catch(error => console.error('Error:', error))
35 | .finally(() => console.log('Request finished')); // این کد همیشه اجرا میشه
36 | ```
37 |
38 | در این مثال، `finally` تضمین میکنه که پیغام "Request finished" بعد از اتمام درخواست نمایش داده بشه، چه درخواست موفقیتآمیز بوده باشه و چه ناموفق. این ویژگی به شما کمک میکنه تا اطمینان حاصل کنی که کارهای نهایی مثل مخفی کردن لودینگ یا آزاد کردن منابع حتماً انجام میشن.
39 |
40 | ## ویژگیهای Object Rest
41 |
42 | ### 3. چطور میتونی با استفاده از ویژگیهای `Object Rest` بخشهای خاصی از یک شیء رو استخراج کنی و این ویژگی چه کاربردهایی داره؟
43 | در ES9، ویژگیهای `Rest` که قبلاً در آرایهها استفاده میشدن، به اشیاء هم گسترش پیدا کردن. این ویژگی به شما اجازه میده تا یک سری ویژگی خاص رو از یک شیء استخراج کنی و باقیمانده ویژگیها رو در قالب یک شیء جدید نگه داری. این قابلیت به ویژه در مواقعی مفیده که میخوای بخشهای غیرضروری یا کمتر مهم رو از یک شیء حذف کنی و فقط ویژگیهای مورد نیازت رو نگه داری.
44 |
45 | ```javascript
46 | const obj = { a: 1, b: 2, c: 3 };
47 | const { a, ...rest } = obj;
48 |
49 | console.log(rest); // { b: 2, c: 3 }
50 | ```
51 |
52 | در این مثال، ویژگی `a` از شیء اصلی جدا شده و باقی ویژگیها در یک شیء جدید به نام `rest` ذخیره شدن. این قابلیت به شما کمک میکنه که به راحتی دادههای اضافی رو از اشیاء جدا کنی و فقط اطلاعات مورد نیازت رو نگه داری.
53 |
54 | ## ویژگیهای جدید RegExp
55 |
56 | ### 4. چه ویژگیهای جدیدی برای `RegExp` معرفی شدن و چطور میتونن کار با عبارات منظم رو بهبود بدن؟
57 | در ES9، چندین ویژگی جدید به `RegExp` اضافه شدن که کار با عبارات منظم رو سادهتر و قدرتمندتر میکنن. این ویژگیها شامل گروههای نامگذاری شده، Lookbehind Assertions و فلگ `s` یا همون dotAll هستن. این قابلیتها به شما این امکان رو میدن که با انعطاف بیشتری الگوهای پیچیدهتری بسازی و مدیریت کنی.
58 |
59 | - **گروههای نامگذاری شده:** به شما اجازه میده به گروههای تطبیق داده شده یک اسم بدی تا دسترسی بهشون راحتتر بشه.
60 | - **Lookbehind Assertions:** به شما امکان میده که فقط در صورتی یک الگو رو تطبیق بدی که قبل از اون یک الگوی خاص وجود داشته باشه.
61 | - **فلگ `s` (dotAll):** باعث میشه که نقطه (`.`) در عبارات منظم هر کاراکتری، حتی کاراکترهای خط جدید رو هم تطبیق بده.
62 |
63 | ```javascript
64 | // Named Capture Groups
65 | const regExp = /(?\d{4})-(?\d{2})-(?\d{2})/;
66 | const match = regExp.exec('2024-08-12');
67 | console.log(match.groups.year); // 2024
68 |
69 | // Lookbehind Assertions
70 | const lookbehindRegExp = /(?<=\$)\d+/;
71 | console.log(lookbehindRegExp.exec('$100')[0]); // 100
72 |
73 | // dotAll flag
74 | const dotAllRegExp = /foo.bar/s;
75 | console.log(dotAllRegExp.test('foo\nbar')); // true
76 | ```
77 |
78 | در این مثالها، از ویژگیهای جدید `RegExp` مثل گروههای نامگذاری شده، Lookbehind Assertions و فلگ `s` استفاده شده تا عبارات منظم قویتر و انعطافپذیرتری بسازی. این ویژگیها به شما کمک میکنن که الگوهای پیچیدهتری رو تطبیق بدی و دادهها رو به شکلی دقیقتر پردازش کنی.
79 |
80 | ## حافظه اشتراکی جاوا اسکریپت
81 |
82 | ### 5. حافظه اشتراکی در جاوا اسکریپت چطور کار میکنه و چه کاربردهایی داره؟
83 | در ES9، پشتیبانی از حافظه اشتراکی با استفاده از `SharedArrayBuffer` و عملیات اتمی با `Atomics` به جاوا اسکریپت اضافه شد. این ویژگیها به شما اجازه میدن که دادهها رو به صورت ایمن بین چندین نخ یا وب ورکر به اشتراک بذاری و عملیاتهایی انجام بدی که به صورت اتمی و بدون وقفه اجرا میشن. این قابلیت به ویژه در برنامههایی که نیاز به پردازش موازی دارن یا وقتی که میخوای از تداخل دادهها جلوگیری کنی، بسیار مفیده.
84 |
85 | ```javascript
86 | const buffer = new SharedArrayBuffer(1024); // ایجاد یک بافر اشتراکی
87 | const uint8 = new Uint8Array(buffer); // ایجاد یک آرایه تایپی برای دسترسی به بافر
88 |
89 | Atomics.add(uint8, 0, 10); // به صورت اتمی 10 رو به اولین عنصر اضافه کن
90 | console.log(Atomics.load(uint8, 0)); // 10
91 | ```
92 |
93 | در این مثال، یک `SharedArrayBuffer` با اندازه 1024 بایت ساخته شده و بعد یک `Uint8Array` برای دسترسی به این بافر ایجاد شده. با استفاده از `Atomics.add`، یک عملیات اتمی انجام میشه که مطمئن میشه هیچ نخ دیگهای وسط این عملیات نمیاد و مقادیر رو تغییر نمیده. این ویژگیها به شما کمک میکنن که عملیاتهای موازی رو به صورت ایمن و کارآمد مدیریت کنی.
94 |
--------------------------------------------------------------------------------
/FA/09-ES10-2019.md:
--------------------------------------------------------------------------------
1 | # سوالات ES10 - 2019
2 |
3 | ## متدهای String.prototype.trimStart و String.prototype.trimEnd
4 |
5 | ### 1. چطور با استفاده از `trimStart` و `trimEnd` میتونی فضای خالی ابتدا و انتهای رشتهها رو مدیریت کنی؟
6 | در ES10، دو متد جدید `trimStart` و `trimEnd` به جاوا اسکریپت اضافه شدن که به توسعهدهندگان این امکان رو میدن که فضای خالی موجود در ابتدا یا انتهای رشتهها رو به صورت هدفمند حذف کنن. این متدها نسخههای خاصتری از متد `trim` هستن که به جای حذف فضاهای خالی از دو طرف، به شما اجازه میدن که دقیقاً تعیین کنی کدوم سمت رشته باید برش بخوره.
7 |
8 | ```javascript
9 | const str = ' Hello World! ';
10 | console.log(str.trimStart()); // 'Hello World! '
11 | console.log(str.trimEnd()); // ' Hello World!'
12 | ```
13 |
14 | تو این مثال، `trimStart` فضاهای خالی ابتدا و `trimEnd` فضاهای خالی انتهای رشته رو حذف میکنن. این ویژگی به خصوص برای پاکسازی رشتهها در ورودیهای کاربر یا دادههایی که از منابع مختلف دریافت میشن، بسیار مفیده.
15 |
16 | ## متد Object.fromEntries
17 |
18 | ### 2. متد `Object.fromEntries` چه کاربردی داره و چطور میتونه به مدیریت دادهها کمک کنه؟
19 | در ES10، متد `Object.fromEntries` معرفی شد که به شما این امکان رو میده تا به راحتی یه آرایه از زوجهای کلید-مقدار رو به یه شیء تبدیل کنی. این متد مکمل `Object.entries` هست که یه شیء رو به یه آرایه از زوجهای کلید-مقدار تبدیل میکنه. این قابلیت به خصوص در مواردی که با دادههای ساختاریافته مثل JSON سروکار داری، بسیار مفیده.
20 |
21 | ```javascript
22 | const entries = [['a', 1], ['b', 2], ['c', 3]];
23 | const obj = Object.fromEntries(entries);
24 | console.log(obj); // { a: 1, b: 2, c: 3 }
25 | ```
26 |
27 | در این مثال، یک آرایه از زوجهای کلید-مقدار با استفاده از `Object.fromEntries` به یک شیء تبدیل شده. این متد به شما کمک میکنه تا به سرعت دادههای موجود در آرایهها رو به ساختارهای شیء تبدیل کنید که برای پردازش و دسترسی بهتر هستن.
28 |
29 | ## ویژگی Optional Catch Binding
30 |
31 | ### 3. ویژگی `Optional Catch Binding` چطور به سادهسازی مدیریت خطاها کمک میکنه؟
32 | در ES10، یک ویژگی جدید به نام `Optional Catch Binding` معرفی شد که به شما این امکان رو میده تا در بلاکهای `catch` از پارامتر خطا صرفنظر کنی اگه نیازی بهش نداری. این ویژگی به خصوص برای مواقعی مفیده که تنها میخوای خطاها رو مدیریت کنی بدون اینکه نیازی به پردازش دقیق جزئیات اونها داشته باشی.
33 |
34 | ```javascript
35 | try {
36 | // some code
37 | } catch {
38 | console.log('An error occurred.');
39 | }
40 | ```
41 |
42 | در این مثال، پارامتر خطا در بلاک `catch` حذف شده چون در اینجا نیازی به بررسی جزئیات خطا نداریم. این کار باعث سادهتر و خواناتر شدن کد میشه و به شما اجازه میده که فقط بر روی بخشهای اصلی کد تمرکز کنی.
43 |
44 | ## متدهای Array.prototype.flat و Array.prototype.flatMap
45 |
46 | ### 4. چطور میتونی با استفاده از `flat` و `flatMap` آرایههای چندبعدی رو به آرایههای سادهتر تبدیل کنی؟
47 | در ES10، متدهای `flat` و `flatMap` به جاوا اسکریپت اضافه شدن که به شما اجازه میدن آرایههای چندبعدی رو به آرایههای سادهتر تبدیل کنی. `flat` این کار رو با حذف لایههای تو در تو انجام میده، در حالی که `flatMap` به شما این امکان رو میده که اول هر عنصر رو به یک تابع بفرستی و بعد نتیجهی تخت شده رو دریافت کنی.
48 |
49 | ```javascript
50 | const arr = [1, [2, [3, [4]]]];
51 | console.log(arr.flat(2)); // [1, 2, 3, [4]]
52 |
53 | const arr2 = [1, 2, 3];
54 | console.log(arr2.flatMap(x => [x, x * 2])); // [1, 2, 2, 4, 3, 6]
55 | ```
56 |
57 | در این مثال، `flat` یک آرایهی چندلایهای رو به یک آرایهی سادهتر تبدیل میکنه، در حالی که `flatMap` به شما اجازه میده تا اول هر عنصر رو به یک آرایه جدید نگاشت کنید و بعد نتیجه رو تخت کنی. این متدها به خصوص برای مدیریت دادههای پیچیده و چندلایهای بسیار مفیدن.
58 |
59 | ## ویژگی Revised Array.sort
60 |
61 | ### 5. ویژگی `Revised Array.sort` چطور به بهبود مرتبسازی دادهها کمک میکنه؟
62 | در ES10، متد `sort` به گونهای بازبینی شده که مرتبسازی پایدار (stable) رو تضمین میکنه. این یعنی وقتی دو عنصر در آرایه مقادیر یکسانی دارن، ترتیب اصلیشون حفظ میشه و در طول مرتبسازی تغییر نمیکنه. این ویژگی به خصوص برای مرتبسازی دادههایی که ترتیب اصلیشون اهمیت داره، بسیار مهمه.
63 |
64 | ```javascript
65 | const arr = [{ name: 'John', age: 25 }, { name: 'Jane', age: 22 }, { name: 'Jack', age: 25 }];
66 | arr.sort((a, b) => a.age - b.age);
67 | console.log(arr);
68 | /* Output:
69 | [
70 | { name: 'Jane', age: 22 },
71 | { name: 'John', age: 25 },
72 | { name: 'Jack', age: 25 }
73 | ]
74 | */
75 | ```
76 |
77 | در این مثال، ترتیب اصلی عناصر با سن مشابه (مثل John و Jack) در طول مرتبسازی حفظ شده. این قابلیت به شما کمک میکنه که بدون نگرانی از تغییر ترتیب اصلی، دادهها رو مرتب کنی.
78 |
79 | ## ویژگی Revised JSON.stringify
80 |
81 | ### 6. ویژگیهای بهبود یافته در `JSON.stringify` چطور میتونن از بروز خطاها جلوگیری کنن؟
82 | در ES10، `JSON.stringify` به گونهای بازبینی شده که همیشه رشتههای Unicode صحیح تولید کنه. این تغییر باعث میشه که مشکلاتی که قبلاً در مواجهه با کاراکترهای خاص Unicode پیش میاومد، رفع بشه و رشتههای تولید شده همیشه به درستی پارس بشن.
83 |
84 | ```javascript
85 | const str = '\uD800';
86 | console.log(JSON.stringify(str)); // '"\\ud800"' به جای رشته معیوب
87 | ```
88 |
89 | در این مثال، `JSON.stringify` رشتهای که شامل کاراکتر Unicode معیوب بود رو به درستی تبدیل کرده و یک رشتهی صحیح تولید کرده. این ویژگی به خصوص برای کار با دادههای متنی بینالمللی و جلوگیری از بروز خطاهای مرتبط با پارس دادهها بسیار مفیده.
90 |
91 | ## استفاده از جداکنندهها در رشتههای متنی
92 |
93 | ### 7. چطور میتونی با استفاده از جداکنندهها در رشتههای متنی، JSON رو به یک سوپرست کامل از ECMAScript تبدیل کنی؟
94 | در ES10، امکان استفاده از جداکنندههای خط (line separator) و جداکنندههای پاراگراف (paragraph separator) در رشتههای متنی فراهم شده. این ویژگی JSON رو به یک سوپرست کامل از ECMAScript تبدیل میکنه و سازگاری بیشتری بین رشتههای متنی و JSON به وجود میاره.
95 |
96 | ```javascript
97 | const str = 'Hello\u2028World';
98 | console.log(JSON.parse(`"${str}"`)); // 'Hello
World'
99 | ```
100 |
101 | در این مثال، جداکننده خط (`\u2028`) به درستی در رشته استفاده شده و JSON بدون هیچ مشکلی اون رو پارس میکنه. این ویژگی برای کار با دادههای متنی که از منابع مختلف میان و نیاز به فرمتبندی خاصی دارن، بسیار مفیده.
102 |
103 | ## بازبینی متد Function.prototype.toString
104 |
105 | ### 8. بازبینی متد `Function.prototype.toString` چه مزایایی داره و چطور میتونه به تحلیل کد کمک کنه؟
106 | در ES10، متد `Function.prototype.toString` به گونهای بازبینی شده که متن دقیق کد منبع تابع رو برمیگردونه. این متن شامل همه چیز میشه، از جمله کامنتها و فاصلههای خالی، که به تحلیل دقیقتر و دیباگ کردن کمک میکنه.
107 |
108 | ```javascript
109 | function example() {
110 | // این یک کامنت است
111 | return "Hello, world!";
112 | }
113 |
114 | console.log(example.toString());
115 | /* Output:
116 | function example() {
117 | // این یک کامنت است
118 | return "Hello, world!";
119 | }
120 | */
121 | ```
122 |
123 | در این مثال، متد `toString` کد تابع `example` رو به همون شکلی که نوشته شده برمیگردونه، شامل همه جزئیات مثل کامنتها و فاصلههای خالی. این ویژگی به شما کمک میکنه که بتونی کد رو به دقت بررسی و تحلیل کنی، و همچنین در مواردی که نیاز به مستندسازی یا انتقال کد به محیطهای دیگه داری، خیلی مفیده.
124 |
--------------------------------------------------------------------------------
/FA/10-ES11-2020.md:
--------------------------------------------------------------------------------
1 | # سوالات ES11 - 2020
2 |
3 | ## ویژگی BigInt
4 |
5 | ### 1. چرا `BigInt` به جاوا اسکریپت اضافه شد و چه کاربردهایی داره؟
6 | نوع دادهی `BigInt` به جاوا اسکریپت اضافه شد تا بتونی با اعداد صحیح خیلی بزرگ کار کنی بدون اینکه دقت محاسبات از دست بره. این نوع داده به خصوص وقتی مفید هست که نیاز داری با اعداد خیلی بزرگتر از محدودهی `Number` که از `64-bit` استفاده میکنه، سروکار داشته باشی. `BigInt` این امکان رو فراهم میکنه که اعداد بزرگتر از ۲^۵۳-۱ (بزرگترین عدد صحیح قابل نمایش در `Number`) رو به دقت مدیریت کنی.
7 |
8 | ```javascript
9 | const bigNumber = BigInt(9007199254740991);
10 | const anotherBigNumber = 9007199254740991n; // با اضافه کردن n به آخر عدد هم میتونی BigInt ایجاد کنی
11 | console.log(bigNumber + anotherBigNumber); // 18014398509481982n
12 | ```
13 |
14 | در این مثال، دو عدد بزرگ با استفاده از `BigInt` تعریف شدند و بدون از دست رفتن دقت، با هم جمع شدند. این قابلیت برای انجام محاسبات مالی یا علمی که نیاز به اعداد بسیار بزرگ دارند، بسیار مفید است.
15 |
16 | ## متد String.prototype.matchAll
17 |
18 | ### 2. متد `matchAll` چه مشکلاتی رو حل میکنه و چطور میتونی ازش استفاده کنی؟
19 | متد `matchAll` به جاوا اسکریپت اضافه شد تا بتونی همهی تطبیقهای یه عبارت منظم رو در یک رشته پیدا کنی و اطلاعات دقیقی از اونها بگیری. قبلاً برای انجام این کار، باید از روشهای پیچیدهتر یا حلقههای تو در تو استفاده میکردی، اما حالا `matchAll` همه تطبیقها رو به صورت یک Iterator برمیگردونه که دسترسی بهشون رو خیلی راحتتر میکنه.
20 |
21 | ```javascript
22 | const regex = /t(e)(st(\d?))/g;
23 | const str = 'test1test2';
24 | const matches = [...str.matchAll(regex)];
25 |
26 | console.log(matches[0]);
27 | // Output:
28 | // ["test1", "e", "st1", "1"]
29 |
30 | console.log(matches[1]);
31 | // Output:
32 | // ["test2", "e", "st2", "2"]
33 | ```
34 |
35 | در این مثال، `matchAll` همهی تطبیقهای عبارت منظم `regex` رو در رشته `str` پیدا میکنه و به صورت یک آرایه از نتایج برمیگردونه. این ویژگی برای کار با متنهایی که نیاز به پردازش دقیق دارند، مثل استخراج داده از اسناد یا تجزیه و تحلیل رشتهها، خیلی مفید هست.
36 |
37 | ## عملگر Nullish Coalescing
38 |
39 | ### 3. عملگر `Nullish Coalescing` چطور میتونه کدهای شما رو پایدارتر کنه؟
40 | عملگر `??` که به عنوان `Nullish Coalescing` شناخته میشه، به شما این امکان رو میده که وقتی یک متغیر `null` یا `undefined` هست، به طور ایمن یک مقدار پیشفرض به اون اختصاص بدی. این عملگر به خصوص در مواردی که ممکنه متغیرها از منابع خارجی دریافت بشن و مقداری نداشته باشن، بسیار مفیده و میتونه از بروز خطاهای غیرمنتظره جلوگیری کنه.
41 |
42 | ```javascript
43 | const foo = null ?? 'default';
44 | const bar = 0 ?? 'default';
45 |
46 | console.log(foo); // 'default'
47 | console.log(bar); // 0
48 | ```
49 |
50 | در این مثال، `foo` به خاطر اینکه `null` هست، مقدار پیشفرض 'default' رو میگیره، ولی `bar` چون مقدار `0` داره که یک مقدار معتبر هست، همون مقدار خودش رو نگه میداره. این عملگر به خصوص وقتی مفیده که بخوای متغیرهایی با مقادیر پیشفرض مطمئن داشته باشی.
51 |
52 | ## عملگر Optional Chaining
53 |
54 | ### 4. عملگر `Optional Chaining` چطور به جلوگیری از خطاها کمک میکنه؟
55 | عملگر `?.` که به عنوان `Optional Chaining` معرفی شده، به شما این امکان رو میده که بدون اینکه نگران وجود یا عدم وجود ویژگیها یا متدها در یک زنجیره باشید، بهشون دسترسی پیدا کنی. این عملگر از بروز خطاهای `undefined` یا `null` جلوگیری میکنه و به کدتون پایداری بیشتری میبخشه.
56 |
57 | ```javascript
58 | const user = {
59 | profile: {
60 | name: 'John'
61 | }
62 | };
63 |
64 | const userName = user?.profile?.name;
65 | const userAge = user?.profile?.age;
66 |
67 | console.log(userName); // 'John'
68 | console.log(userAge); // undefined (بدون خطا)
69 | ```
70 |
71 | در این مثال، با استفاده از `?.` به صورت ایمن به ویژگیهای `profile` و `name` دسترسی پیدا کردیم. اگه هر کدوم از این ویژگیها وجود نداشته باشه، به جای اینکه برنامه به خطا بخوره، `undefined` برمیگردونه و اجرای کد بدون مشکل ادامه پیدا میکنه.
72 |
73 | ## عملگر Logical AND Assignment
74 |
75 | ### 5. عملگر `Logical AND Assignment` چه زمانی مفیده و چطور کار میکنه؟
76 | عملگر `&&=` که در ES11 معرفی شد، به شما این امکان رو میده که یه مقدار رو فقط در صورتی به یه متغیر اختصاص بدی که مقدار فعلی اون متغیر `true` باشه. این عملگر به خصوص وقتی مفیده که بخوای به طور شرطی یه مقدار رو تغییر بدی، بدون اینکه مجبور باشی کل شرط رو بنویسی.
77 |
78 | ```javascript
79 | let x = true;
80 | let y = false;
81 |
82 | x &&= 'Assigned if true';
83 | y &&= 'Not assigned because false';
84 |
85 | console.log(x); // 'Assigned if true'
86 | console.log(y); // false
87 | ```
88 |
89 | در این مثال، مقدار `x` چون `true` هست، تغییر میکنه، ولی مقدار `y` که `false` هست، ثابت میمونه و تغییری نمیکنه. این عملگر میتونه نوشتن شرطهای پیچیده رو در کد سادهتر و خواناتر کنه.
90 |
91 | ## عملگر Logical OR Assignment
92 |
93 | ### 6. عملگر `Logical OR Assignment` چطور میتونه به سادهسازی شرطها کمک کنه؟
94 | عملگر `||=` به شما این امکان رو میده که یه مقدار رو به یه متغیر اختصاص بدی، ولی فقط در صورتی که مقدار فعلی اون متغیر `false`، `null`، یا `undefined` باشه. این عملگر به خصوص وقتی مفیده که بخوای یه مقدار پیشفرض به متغیری بدی که ممکنه هنوز مقداردهی نشده باشه.
95 |
96 | ```javascript
97 | let a = null;
98 | let b = 'Already set';
99 |
100 | a ||= 'Set because null';
101 | b ||= 'Not set because already has a value';
102 |
103 | console.log(a); // 'Set because null'
104 | console.log(b); // 'Already set'
105 | ```
106 |
107 | در این مثال، `a` چون `null` هست، مقدار جدیدی میگیره ولی `b` که از قبل مقدار داره، همون مقدار رو حفظ میکنه. این عملگر به شما کمک میکنه که شرطهای سادهتری بنویسی و از پیچیدگیهای اضافی جلوگیری کنی.
108 |
109 | ## عملگر Nullish Coalescing Assignment
110 |
111 | ### 7. عملگر `Nullish Coalescing Assignment` چه تفاوتی با سایر عملگرهای تخصیص داره؟
112 | عملگر `??=` به شما این امکان رو میده که یه مقدار رو به یه متغیر اختصاص بدی، ولی فقط در صورتی که مقدار فعلی اون `null` یا `undefined` باشه. این عملگر به خصوص وقتی مفیده که بخوای مطمئن بشی یه متغیر مقداردهی شده ولی نمیخوای مقادیر `false` یا `0` رو بازنویسی کنی.
113 |
114 | ```javascript
115 | let c = null;
116 | let d = 'Already defined';
117 |
118 | c ??= 'Set because null';
119 | d ??= 'Not set because already defined';
120 |
121 | console.log(c); // 'Set because null'
122 | console.log(d); // 'Already defined'
123 | ```
124 |
125 | در این مثال، `c` چون مقدار `null` داره، با مقدار جدید جایگزین میشه ولی `d` که مقدار معتبر داره، تغییری نمیکنه. این عملگر به شما کمک میکنه که مقداردهیهای پیشفرض رو به شکلی ایمنتر انجام بدی.
126 |
127 | ## متد Promise.allSettled
128 |
129 | ### 8. متد `Promise.allSettled` چه کاربردی داره و چطور میتونه به مدیریت وعدهها کمک کنه؟
130 | متد `Promise.allSettled` به شما این امکان رو میده که منتظر بمونی تا همهی وعدهها (`Promises`)، چه موفق و چه ناموفق، به پایان برسن و بعد نتیجهی نهایی هر کدوم رو بررسی کنی. این متد به خصوص وقتی مفیده که بخوای همه نتایج رو دریافت کنی و فقط به موارد موفق یا ناموفق توجه نکنی.
131 |
132 | ```javascript
133 | const promise1 = Promise.resolve('Resolved');
134 | const promise2 = Promise.reject('Rejected');
135 | const promise3 = new Promise
136 |
137 | ((resolve) => setTimeout(resolve, 1000, 'Delayed'));
138 |
139 | Promise.allSettled([promise1, promise2, promise3])
140 | .then((results) => results.forEach((result) => console.log(result.status)));
141 | /* Output:
142 | resolved
143 | rejected
144 | fulfilled
145 | */
146 | ```
147 |
148 | در این مثال، `Promise.allSettled` صبر میکنه تا هر سه وعده به پایان برسن، چه موفق و چه ناموفق، و بعد وضعیت نهایی هر کدوم رو لاگ میکنه. این متد برای زمانی مفیده که بخوای از وضعیت همه وعدهها مطلع بشی و به همه نتایج، چه موفق و چه ناموفق، رسیدگی کنی.
149 |
150 | ## ویژگی Dynamic Import
151 |
152 | ### 9. ویژگی `Dynamic Import` چطور میتونه به بهینهسازی بارگذاری کد کمک کنه؟
153 | ویژگی `Dynamic Import` به شما این امکان رو میده که ماژولها رو به صورت پویا و تنها زمانی که نیاز هست بارگذاری کنی. این کار باعث میشه که بار اولیه صفحه یا برنامه کاهش پیدا کنه و بخشهای دیگه فقط زمانی بارگذاری بشن که واقعاً نیاز هستن. این ویژگی به بهینهسازی عملکرد و کاهش زمان بارگذاری کمک میکنه.
154 |
155 | ```javascript
156 | // Dynamic Import
157 | // فرض کن یه ماژول به اسم 'math.js' داریم که حاوی توابع مختلفی هست
158 | async function loadMathModule() {
159 | const math = await import('./math.js');
160 | console.log(math.add(2, 3)); // استفاده از تابع add از ماژول math
161 | }
162 |
163 | loadMathModule();
164 | ```
165 |
166 | در این مثال، ماژول `math.js` فقط وقتی که نیاز بهش داریم (داخل تابع `loadMathModule`) بارگذاری میشه. این کار باعث میشه که بار اولیه صفحه یا برنامه کاهش پیدا کنه و کاربر فقط ماژولهایی که واقعاً نیاز داره رو دانلود کنه. این ویژگی برای بهینهسازی عملکرد برنامههای وب و کاهش زمان بارگذاری صفحات خیلی مفیده.
167 |
--------------------------------------------------------------------------------
/FA/11-ES12-2021.md:
--------------------------------------------------------------------------------
1 | # سوالات ES2021 - 2021
2 |
3 | ## متد Promise.any
4 |
5 | ### 1. متد `Promise.any` چطور کار میکنه و چه زمانی به درد میخوره؟
6 | متد `Promise.any` بهت این امکان رو میده که از بین چند تا `Promise`، اون یکی که زودتر با موفقیت به نتیجه میرسه رو انتخاب کنی. یعنی به جای اینکه منتظر بمونی همهی `Promise`ها تکمیل بشن، فقط همون یکی که زودتر جواب میده رو استفاده میکنی. این قابلیت وقتی خیلی به درد میخوره که چند تا کار رو با هم شروع کردی و فقط اولین نتیجه برات مهمه.
7 |
8 | ```javascript
9 | const myPromise1 = new Promise((resolve, reject) => {
10 | setTimeout(resolve, 200, "King");
11 | });
12 |
13 | const myPromise2 = new Promise((resolve, reject) => {
14 | setTimeout(resolve, 100, "Queen");
15 | });
16 |
17 | Promise.any([myPromise1, myPromise2]).then((result) => {
18 | console.log(result); // "Queen"
19 | });
20 | ```
21 |
22 | تو این مثال، `Promise.any` منتظر میمونه تا یکی از این دو `Promise` با موفقیت تکمیل بشه و اولین نتیجه یعنی "Queen" رو برمیگردونه. این ویژگی مخصوصاً زمانی کاربرد داره که میخوای سریعترین جواب رو از بین چند عملیات همزمان بگیری و به بقیه کار نداشته باشی.
23 |
24 | ## متد replaceAll
25 |
26 | ### 2. متد `replaceAll` چه کمکی به جایگزینی متن تو رشتهها میکنه؟
27 | متد `replaceAll` بهت این امکان رو میده که همهی نمونههای یه کلمه یا عبارت رو تو یه رشته، با یه کلمه یا عبارت دیگه جایگزین کنی. برخلاف `replace` که فقط اولین نمونه رو عوض میکرد، `replaceAll` همهی تطابقها رو تغییر میده. این متد خیلی به درد موقعی میخوره که میخوای کل متن رو تغییر بدی و نمیخوای چیزی از قلم بیفته.
28 |
29 | ```javascript
30 | let text = "Cats are great. Cats are friendly.";
31 | text = text.replaceAll("Cats", "Dogs");
32 | console.log(text); // "Dogs are great. Dogs are friendly."
33 | ```
34 |
35 | اینجا `replaceAll` همهی "Cats"ها رو با "Dogs" عوض میکنه. این متد بهخصوص زمانی مفیده که میخوای بهصورت کلی یه عبارت رو توی متن تغییر بدی بدون اینکه بخوای چندین بار دستی این کار رو انجام بدی.
36 |
37 | علاوه بر این، میتونی از `replaceAll` با عبارات منظم هم استفاده کنی تا تطابقهای پیچیدهتری رو تو متن پیدا کنی و جایگزین کنی. فقط یادت باشه که باید از فلگ `g` (global) استفاده کنی.
38 |
39 | ```javascript
40 | let text = "Cats are great. Cats are friendly.";
41 | text = text.replaceAll(/Cats/g, "Dogs");
42 | console.log(text); // "Dogs are great. Dogs are friendly."
43 | ```
44 |
45 | این روش بهت کمک میکنه تا با یه خط کد، تمام تغییرات لازم رو توی متن اعمال کنی.
46 |
47 | ## جداکنندههای عددی
48 |
49 | ### 3. جداکنندههای عددی (`_`) چه تاثیری دارن و چطور میشه ازشون استفاده کرد؟
50 | جداکنندههای عددی (`_`) بهت این امکان رو میدن که اعداد بزرگ رو به صورت خواناتری توی کد بنویسی. این جداکنندهها هیچ تاثیری توی مقدار واقعی عدد ندارن، اما باعث میشن که خوندن و درک اعداد بزرگ راحتتر بشه. بهخصوص وقتی که با اعداد میلیون یا میلیاردی کار میکنی، این ویژگی به کاهش خطاهای خوندن و نوشتن کمک میکنه.
51 |
52 | ```javascript
53 | const num = 1_000_000_000;
54 | console.log(num); // 1000000000
55 | ```
56 |
57 | اینجا جداکنندههای `_` باعث شدن که عدد راحتتر خونده بشه، اما نتیجه همون 1000000000 هست. این جداکنندهها فقط خوانایی کد رو بالا میبرن و میتونی اونها رو هر جایی از عدد قرار بدی تا خوندنش راحتتر بشه.
58 |
59 | ```javascript
60 | const num1 = 1_234_567_890_123_456;
61 | console.log(num1); // 1234567890123456
62 | ```
63 |
64 | این قابلیت بهخصوص وقتی به کار میاد که داری با اعداد بزرگ و پیچیده کار میکنی و میخوای مطمئن بشی که کد هم خوانا هست و هم کم خطا.
65 |
--------------------------------------------------------------------------------
/FA/12-ES13-2022.md:
--------------------------------------------------------------------------------
1 | # سوالات ES13 - 2022
2 |
3 | ## متد Array.at
4 |
5 | ### 1. متد `Array.at` چطور کار میکنه و چه مشکلی رو توی دسترسی به عناصر آرایهها حل میکنه؟
6 | >متد `Array.at` یه متد جدید و قدرتمنده که بهت اجازه میده یه عنصر خاص از آرایه رو با استفاده از اندیس انتخاب کنی، مشابه کاری که با `[]` انجام میدادی. اما چیزی که این متد رو متمایز میکنه، امکان استفاده از اندیسهای منفی برای دسترسی به عناصر انتهایی آرایه هست. این قابلیت برای وقتی که میخوای از انتهای آرایه به عناصری دسترسی پیدا کنی بدون اینکه نیاز باشه طول آرایه رو بدونی، خیلی مفیده.
7 |
8 | ```javascript
9 | const fruits = ["Banana", "Orange", "Apple", "Mango"];
10 | let fruit = fruits.at(-1);
11 | console.log(fruit); // "Mango"
12 | ```
13 |
14 | > تو این مثال، از `at(-1)` استفاده شده تا آخرین عنصر آرایه یعنی "Mango" انتخاب بشه. این متد، نوشتن کدهای تمیزتر و دسترسی سادهتر به عناصر انتهایی آرایه رو خیلی راحتتر کرده.
15 |
16 | ## متد String.at
17 |
18 | ### 2. متد `String.at` چطور به دسترسی به کاراکترهای رشته کمک میکنه و چه مزایایی داره؟
19 | > متد `String.at` همون کار `Array.at` رو برای رشتهها انجام میده. با این متد میتونی به سادگی یه کاراکتر خاص از یه رشته رو بر اساس اندیس انتخاب کنی، حتی با استفاده از اندیسهای منفی که بهت اجازه میدن از انتهای رشته به کاراکترها دسترسی پیدا کنی. این ویژگی به خصوص در کار با رشتههای طولانی خیلی مفیده.
20 |
21 | ```javascript
22 | const name = "W3Schools";
23 | let letter = name.at(-1);
24 | console.log(letter); // "s"
25 | ```
26 |
27 | > تو این مثال، از `at(-1)` استفاده کردیم تا آخرین کاراکتر رشته یعنی "s" رو به دست بیاریم. این متد برای وقتی که نیاز داری به سرعت و به طور مستقیم به کاراکترهای خاصی از یه رشته دسترسی پیدا کنی، بسیار کارآمده.
28 |
29 | ## فلگ d در RegExp
30 |
31 | ### 3. فلگ `d` در RegExp چطور کار میکنه و چه اطلاعاتی رو برای تطبیقها فراهم میکنه؟
32 | > فلگ `d` تو عبارات منظم (RegExp) اضافه شده تا بتونه مکان دقیق شروع و پایان تطبیقها رو تو نتایج نشون بده. این فلگ بهت کمک میکنه که نه تنها بفهمی چه چیزی تطبیق داده شده، بلکه بفهمی کجا دقیقاً این تطبیقها اتفاق افتاده. این اطلاعات برای تحلیل دقیق متنها خیلی مفیده.
33 |
34 | ```javascript
35 | let text = "aaaabb";
36 | let result = text.match(/(aa)(bb)/d);
37 | console.log(result.indices); // [[0, 6], [0, 2], [4, 6]]
38 | ```
39 |
40 | > تو این مثال، فلگ `d` کمک میکنه تا مکان دقیق تطبیقهای "aa" و "bb" رو توی متن مشخص کنیم. این فلگ بهویژه برای وقتی که به تجزیه و تحلیل دقیق تطبیقها نیاز داری، خیلی مفیده.
41 |
42 | ## متد Object.hasOwn
43 |
44 | ### 4. متد `Object.hasOwn` چه نقشی در بررسی مالکیت ویژگیهای شیء داره و چه تفاوتی با روشهای قبلی مثل `hasOwnProperty` داره؟
45 | > متد `Object.hasOwn` یه متد جدیده که یه راه امن و بهینه برای بررسی این موضوعه که آیا یه شیء خاص یه ویژگی مشخص داره یا نه. این متد نسبت به `hasOwnProperty` جامعتره و میتونه برای همه نوع اشیاء استفاده بشه، بنابراین برای بررسی مالکیت ویژگیها بهترین انتخابه.
46 |
47 | ```javascript
48 | const obj = { name: "John", age: 30 };
49 | console.log(Object.hasOwn(obj, "name")); // true
50 | console.log(Object.hasOwn(obj, "gender")); // false
51 | ```
52 |
53 | > تو این مثال، با استفاده از `Object.hasOwn` بررسی کردیم که آیا ویژگی "name" تو شیء `obj` وجود داره یا نه. این متد بهت کمک میکنه که با خیال راحت بررسیهای لازم رو انجام بدی بدون اینکه نگران ناسازگاری یا خطاهای احتمالی باشی.
54 |
55 | ## ویژگی error.cause
56 |
57 | ### 5. ویژگی `error.cause` چطور بهت کمک میکنه تا علت دقیق خطاها رو مشخص کنی و اونها رو بهتر مدیریت کنی؟
58 | > ویژگی `error.cause` بهت اجازه میده که وقتی یه خطا رخ میده، دلیل اصلی اون رو مشخص کنی و به عنوان بخشی از خطا ارائه بدی. این ویژگی برای زمانی که میخوای جزئیات بیشتری از علت خطاها داشته باشی و دیباگ کردن رو راحتتر کنی، خیلی مفیده.
59 |
60 | ```javascript
61 | try {
62 | connectData();
63 | } catch (err) {
64 | throw new Error("Connecting failed.", { cause: err });
65 | }
66 | ```
67 |
68 | > تو این مثال، وقتی `connectData` خطا میده، اون خطا به عنوان علت (`cause`) خطای جدیدی که ایجاد میکنیم ثبت میشه. این روش باعث میشه بتونی اطلاعات دقیقتری از خطاها داشته باشی و اونا رو بهتر مدیریت کنی.
69 |
70 | ## ویژگی await import
71 |
72 | ### 6. ویژگی `await import` چطور به مدیریت بارگذاری ماژولها کمک میکنه و چرا باید ازش استفاده کنی؟
73 | > ویژگی `await import` بهت اجازه میده که ماژولها رو به صورت پویا و تنها زمانی که واقعاً بهشون نیاز داری بارگذاری کنی. این ویژگی مخصوصاً زمانی مفیده که بخوای کد اولیه برنامه سبکتر و سریعتر بارگذاری بشه و فقط بخشهایی که نیاز هستن، به مرور زمان بارگذاری بشن.
74 |
75 | ```javascript
76 | const { myFunction } = await import('./myModule.js');
77 | myFunction();
78 | ```
79 |
80 | > تو این مثال، ماژول `myModule.js` به صورت پویا و فقط زمانی که نیاز بهش داریم بارگذاری میشه. این کار باعث میشه که بار اولیه صفحه کاهش پیدا کنه و ماژولها فقط در صورت نیاز بارگذاری بشن، که این خودش باعث بهبود کارایی و سرعت اجرای برنامه میشه.
81 |
82 | ## اعلان فیلدهای کلاس
83 |
84 | ### 7. اعلان فیلدهای کلاس چه مزیتی داره و چطور میتونه کدهای کلاس رو تمیزتر و منظمتر کنه؟
85 | > اعلان فیلدهای کلاس بهت اجازه میده که متغیرهای کلاس رو به طور مستقیم داخل خود کلاس تعریف کنی، بدون اینکه مجبور باشی اونا رو تو متد `constructor` تعریف کنی. این ویژگی باعث میشه کدهای کلاس سادهتر، خواناتر و منظمتر بشن.
86 |
87 | ```javascript
88 | class Hello {
89 | counter = 0;
90 | }
91 | const myClass = new Hello();
92 | console.log(myClass.counter); // 0
93 | ```
94 |
95 | > تو این مثال، فیلد `counter` به طور مستقیم داخل کلاس `Hello` تعریف شده، که باعث شده کد هم کوتاهتر بشه و هم از پیچیدگی کمتری برخوردار باشه. این روش به کدهای کلاس نظم بیشتری میده و درک و نگهداری اونا رو راحتتر میکنه.
96 |
97 | ## متدها و فیلدهای خصوصی در کلاسها
98 |
99 | ### 8. متدها و فیلدهای خصوصی در کلاسها چطور امنیت و انسجام کد رو بالا میبرن و چرا باید ازشون استفاده کنی؟
100 | > متدها و فیلدهای خصوصی بهت اجازه میدن که بخشی از دادهها و عملکردهای کلاس رو به صورت خصوصی و فقط داخل همون کلاس نگه داری. این ویژگی امنیت کد رو بالا میبره و از دسترسیهای غیرمجاز یا تغییرات ناخواسته جلوگیری میکنه.
101 |
102 | ```javascript
103 | class Hello {
104 | #counter = 0;
105 |
106 | #increment() {
107 | this.#counter++;
108 | }
109 |
110 | getCount() {
111 | return this.#counter;
112 | }
113 | }
114 | const myClass = new Hello();
115 | console.log(myClass.getCount()); // 0
116 | ```
117 |
118 | > تو این مثال، `#counter` و `#increment` به صورت خصوصی تعریف شدن و فقط داخل کلاس `Hello` قابل دسترسی هستن. این روش کمک میکنه که مطمئن بشی کدهای داخلی کلاس از بیرون قابل دسترسی و تغییر نیستن، که این خودش به افزایش امنیت و انسجام کدها کمک میکنه.
119 |
--------------------------------------------------------------------------------
/FA/13-ES14-2023.md:
--------------------------------------------------------------------------------
1 | # سوالات ES14 - 2023
2 |
3 | ## متد Array.findLast
4 |
5 | ### 1. متد `findLast` توی آرایهها چطور کار میکنه و چه کاربردی داره؟
6 | > متد `findLast` یکی از متدهای جدیدی هست که به آرایهها اضافه شده و بهت اجازه میده از انتهای آرایه شروع کنی و اولین عنصری که یه شرط خاص رو برآورده میکنه پیدا کنی. این متد شبیه `find` کار میکنه، ولی به جای اینکه از اول آرایه شروع کنه، از آخر آرایه شروع میکنه. این قابلیت وقتی خیلی به کار میاد که بخوای بررسی رو از انتهای آرایه شروع کنی و اولین تطبیق رو پیدا کنی.
7 |
8 | ```javascript
9 | const temp = [27, 28, 30, 40, 42, 35, 30];
10 | let high = temp.findLast(x => x > 40);
11 | console.log(high); // 42
12 | ```
13 |
14 | > تو این مثال، `findLast` از انتهای آرایه شروع میکنه و اولین مقداری که بزرگتر از 40 هست رو پیدا میکنه که 42 هست. این متد برای مواقعی که به آخرین تطبیق با یه شرط خاص نیاز داری خیلی مفیده.
15 |
16 | ## متد Array.findLastIndex
17 |
18 | ### 2. متد `findLastIndex` چه کار میکنه و چطور میتونه به بهینهسازی جستجوها در آرایهها کمک کنه؟
19 | > متد `findLastIndex` شبیه `findLast` هست ولی به جای اینکه مقدار رو برگردونه، ایندکس (مکان) آخرین عنصری که شرط مشخصی رو برآورده میکنه رو برمیگردونه. این متد وقتی به کار میاد که بخوای بدونی یه شرط خاص در کجای آرایه آخرین بار برآورده شده.
20 |
21 | ```javascript
22 | const temp = [27, 28, 30, 40, 42, 35, 30];
23 | let pos = temp.findLastIndex(x => x > 40);
24 | console.log(pos); // 4
25 | ```
26 |
27 | > تو این مثال، `findLastIndex` آخرین جایی که یه مقدار بزرگتر از 40 هست رو پیدا میکنه که ایندکس 4 (مقدار 42) هست. این متد برای بهینهسازی جستجوها و پیدا کردن مکان آخرین تطبیق خیلی مفیده.
28 |
29 | ## متد Array.toReversed
30 |
31 | ### 3. متد `toReversed` چه تفاوتی با `reverse` داره و چرا استفاده ازش بهتره؟
32 | > متد `toReversed` یه متد جدید و امن برای معکوس کردن آرایههاست که بدون تغییر در آرایه اصلی یه آرایه جدید برمیگردونه. بر خلاف `reverse` که مستقیماً روی آرایه اصلی تغییرات اعمال میکرد، `toReversed` آرایه اصلی رو دستنخورده نگه میداره و یه نسخه معکوس از اون رو برمیگردونه.
33 |
34 | ```javascript
35 | const months = ["Jan", "Feb", "Mar", "Apr"];
36 | const reversed = months.toReversed();
37 | console.log(reversed); // ["Apr", "Mar", "Feb", "Jan"]
38 | console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
39 | ```
40 |
41 | > تو این مثال، `toReversed` یه نسخه معکوس از آرایه `months` برمیگردونه بدون اینکه آرایه اصلی تغییری بکنه. این متد برای وقتی که نیاز داری یه آرایه رو معکوس کنی ولی نمیخوای آرایه اصلی تغییر کنه، خیلی مفیده.
42 |
43 | ## متد Array.toSorted
44 |
45 | ### 4. متد `toSorted` چطور به مرتبسازی آرایهها کمک میکنه و چرا بهتر از `sort` استفاده بشه؟
46 | > متد `toSorted` یه روش جدید برای مرتبسازی آرایههاست که بدون تغییر در آرایه اصلی، یه نسخه مرتب شده از اون رو برمیگردونه. این متد مثل `sort` عمل میکنه، اما مزیتش اینه که آرایه اصلی رو دستنخورده نگه میداره.
47 |
48 | ```javascript
49 | const months = ["Jan", "Feb", "Mar", "Apr"];
50 | const sorted = months.toSorted();
51 | console.log(sorted); // ["Apr", "Feb", "Jan", "Mar"]
52 | console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
53 | ```
54 |
55 | > تو این مثال، `toSorted` یه آرایه مرتب شده رو برمیگردونه بدون اینکه آرایه اصلی تغییر کنه. این متد برای مواقعی که به مرتبسازی نیاز داری ولی نمیخوای آرایه اصلی تغییر کنه، ایدهآله.
56 |
57 | ## متد Array.toSpliced
58 |
59 | ### 5. متد `toSpliced` چطور میتونه در عملیات برش و تغییر آرایهها مفید باشه و چه تفاوتی با `splice` داره؟
60 | > متد `toSpliced` یه متد جدید و امن برای حذف یا جایگزینی عناصر در یه آرایه هست که بدون تغییر در آرایه اصلی، یه نسخه تغییر یافته برمیگردونه. این متد جایگزین بهتری برای `splice` هست چون `splice` آرایه اصلی رو تغییر میداد ولی `toSpliced` این کار رو نمیکنه.
61 |
62 | ```javascript
63 | const months = ["Jan", "Feb", "Mar", "Apr"];
64 | const spliced = months.toSpliced(0, 1);
65 | console.log(spliced); // ["Feb", "Mar", "Apr"]
66 | console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
67 | ```
68 |
69 | > تو این مثال، `toSpliced` یه نسخه جدید از آرایه `months` برمیگردونه که عنصر اول حذف شده. آرایه اصلی دستنخورده باقی مونده. این متد برای وقتی که میخوای تغییراتی در آرایه بدی ولی نمیخوای آرایه اصلی تغییر کنه، خیلی مفیده.
70 |
71 | ## متد Array.with
72 |
73 | ### 6. متد `with` چطور کار میکنه و چه کاربردی در بهروزرسانی عناصر آرایهها داره؟
74 | > متد `with` یه متد جدید برای جایگزینی عناصر در یه آرایه هست که یه نسخه جدید از آرایه با عنصر جایگزین شده برمیگردونه بدون اینکه آرایه اصلی تغییر کنه. این متد برای بهروزرسانی عناصر خاص در یه آرایه بدون تغییر در بقیه آرایه خیلی مفیده.
75 |
76 | ```javascript
77 | const months = ["Januar", "Februar", "Mar", "April"];
78 | const updated = months.with(2, "March");
79 | console.log(updated); // ["Januar", "Februar", "March", "April"]
80 | console.log(months); // ["Januar", "Februar", "Mar", "April"]
81 | ```
82 |
83 | > تو این مثال، `with` یه نسخه جدید از آرایه `months` رو برمیگردونه که عنصر سوم (Mar) با "March" جایگزین شده. این روش باعث میشه بتونی به راحتی و بدون تغییر در آرایه اصلی، آرایه رو بهروزرسانی کنی.
84 |
85 | ## ویژگی !# (Shebang)
86 |
87 | ### 7. ویژگی `!#` (Shebang) چه نقشی در اجرای اسکریپتهای جاوا اسکریپت داره و چرا استفاده ازش مهمه؟
88 | > ویژگی `!#` که به عنوان Shebang هم شناخته میشه، به فایلهای اسکریپت اضافه میشه تا به سیستم عامل بگه این فایل باید با چه مفسری اجرا بشه. این ویژگی به خصوص برای وقتی که میخوای کدهای جاوا اسکریپت رو مستقیماً در محیطهای یونیکس یا لینوکس اجرا کنی خیلی مفیده.
89 |
90 | ```javascript
91 | #!/usr/bin/env node
92 | console.log('Hello World');
93 | ```
94 |
95 | > تو این مثال، `!#` مشخص میکنه که اسکریپت باید با `node` اجرا بشه. این باعث میشه که بتونی کد جاوا اسکریپت رو به طور مستقیم با `./fileName.js` اجرا کنی به جای اینکه بخوای از `node fileName.js` استفاده کنی. این ویژگی به مدیریت و اجرای سادهتر اسکریپتها در محیطهای مختلف کمک میکنه.
96 |
--------------------------------------------------------------------------------
/FA/14-ES15-2024.md:
--------------------------------------------------------------------------------
1 | # سوالات ES15 - 2024
2 |
3 | ## متد Object.groupBy
4 |
5 | ### 1. متد `Object.groupBy` چه کار میکنه و چه کاربردهایی داره؟
6 | > متد `Object.groupBy` یه متد جدیده که بهت اجازه میده عناصر یه آرایه از اشیاء رو بر اساس مقادیر برگشتی از یه تابع کالبک، دستهبندی کنی. این متد هیچ تغییری توی شیء اصلی ایجاد نمیکنه، بلکه یه شیء جدید برمیگردونه که عناصرش به گروههای مختلف تقسیم شدن. این قابلیت وقتی خیلی به درد میخوره که بخوای دادهها رو بر اساس معیارهای مختلف گروهبندی کنی، مثل گروهبندی میوهها بر اساس میزان موجودی.
7 |
8 | ```javascript
9 | const fruits = [
10 | {name: "apples", quantity: 300},
11 | {name: "bananas", quantity: 500},
12 | {name: "oranges", quantity: 200},
13 | {name: "kiwi", quantity: 150}
14 | ];
15 |
16 | function myCallback({ quantity }) {
17 | return quantity > 200 ? "ok" : "low";
18 | }
19 |
20 | const result = Object.groupBy(fruits, myCallback);
21 | console.log(result);
22 | // Output:
23 | // { ok: [ { name: 'apples', quantity: 300 }, { name: 'bananas', quantity: 500 } ],
24 | // low: [ { name: 'oranges', quantity: 200 }, { name: 'kiwi', quantity: 150 } ] }
25 | ```
26 |
27 | > تو این مثال، `Object.groupBy` میوهها رو بر اساس میزان موجودی به دو گروه "ok" و "low" تقسیم میکنه. این روش به خصوص برای دستهبندی دادهها به صورت داینامیک خیلی مفیده.
28 |
29 | ## متد Map.groupBy
30 |
31 | ### 2. متد `Map.groupBy` چه تفاوتی با `Object.groupBy` داره و در چه مواردی بهتره استفاده بشه؟
32 | > متد `Map.groupBy` شبیه `Object.groupBy` کار میکنه، ولی به جای اینکه یه شیء جاوا اسکریپت برگردونه، یه `Map` برمیگردونه. `Map` به دلیل اینکه میتونه هر نوع دادهای رو به عنوان کلید قبول کنه، در بعضی موارد مثل گروهبندی بر اساس مقادیر پیچیدهتر یا non-string کاربرد بهتری داره.
33 |
34 | ```javascript
35 | const fruits = [
36 | {name: "apples", quantity: 300},
37 | {name: "bananas", quantity: 500},
38 | {name: "oranges", quantity: 200},
39 | {name: "kiwi", quantity: 150}
40 | ];
41 |
42 | function myCallback({ quantity }) {
43 | return quantity > 200 ? "ok" : "low";
44 | }
45 |
46 | const result = Map.groupBy(fruits, myCallback);
47 | console.log(result);
48 | // Output:
49 | // Map(2) { 'ok' => [ { name: 'apples', quantity: 300 }, { name: 'bananas', quantity: 500 } ],
50 | // 'low' => [ { name: 'oranges', quantity: 200 }, { name: 'kiwi', quantity: 150 } ] }
51 | ```
52 |
53 | > تو این مثال، `Map.groupBy` دادهها رو مثل `Object.groupBy` گروهبندی میکنه، ولی خروجی یه `Map` هست. `Map` برای مواقعی که به قابلیتهای پیشرفتهتری مثل حفظ ترتیب عناصر یا کلیدهای غیررشتهای نیاز داری، خیلی مفیده.
54 |
55 | ## ویژگی Temporal.PlainDate
56 |
57 | ### 3. ویژگی `Temporal.PlainDate` چطور میتونه به مدیریت تاریخها کمک کنه و چرا بهتر از `Date` هست؟
58 | > ویژگی `Temporal.PlainDate` یکی از ویژگیهای جدید توی مدیریت تاریخهاست که دقت و قابلیتهای بیشتری نسبت به `Date` ارائه میده. این ویژگی بهت اجازه میده تاریخها رو بدون نگرانی از زمان (زمان روز) مدیریت کنی، که برای کارهایی مثل محاسبات تقویمی یا برنامهریزی تاریخهای خاص خیلی مفیده.
59 |
60 | ```javascript
61 | const date = new Temporal.PlainDate(2024, 5, 1);
62 | console.log(date); // 2024-05-01
63 | ```
64 |
65 | > تو این مثال، `Temporal.PlainDate` یه تاریخ رو بدون در نظر گرفتن زمان ایجاد میکنه. این قابلیت برای زمانی که فقط به تاریخ نیاز داری و زمان برات مهم نیست، خیلی مفیده.
66 |
67 | ## ویژگی Temporal.PlainTime
68 |
69 | ### 4. ویژگی `Temporal.PlainTime` چه کاربردی داره و چه مزایایی نسبت به استفاده از `Date` برای زمانبندیها داره؟
70 | > ویژگی `Temporal.PlainTime` برای مدیریت زمانها بدون نیاز به تاریخ استفاده میشه. این ویژگی بهت اجازه میده زمانها رو به دقت میلیثانیه مشخص کنی، بدون اینکه نگران منطقه زمانی یا تاریخ باشی. این قابلیت برای برنامههایی مثل تایمرها یا زمانبندیهای روزانه خیلی مفیده.
71 |
72 | ```javascript
73 | const time = new Temporal.PlainTime(10, 30);
74 | console.log(time); // 10:30:00
75 | ```
76 |
77 | > تو این مثال، `Temporal.PlainTime` یه زمان خاص رو بدون در نظر گرفتن تاریخ ایجاد میکنه. این روش برای زمانی که فقط نیاز به مدیریت زمان داری و تاریخ بیاهمیت هست، عالیه.
78 |
79 | ## ویژگی Temporal.PlainMonthDay
80 |
81 | ### 5. ویژگی `Temporal.PlainMonthDay` چطور میتونه در مدیریت تاریخهای خاص مثل تولدها یا سالگردها مفید باشه؟
82 | > ویژگی `Temporal.PlainMonthDay` برای مدیریت تاریخهایی که فقط شامل ماه و روز هستن (مثل تولدها یا سالگردها) استفاده میشه. این ویژگی نیازی به سال نداره و بهت اجازه میده به سادگی تاریخهای خاصی رو پیگیری کنی.
83 |
84 | ```javascript
85 | const monthDay = new Temporal.PlainMonthDay(5, 1);
86 | console.log(monthDay); // 05-01
87 | ```
88 |
89 | > تو این مثال، `Temporal.PlainMonthDay` یه تاریخ خاص رو که فقط شامل ماه و روز هست رو ایجاد میکنه. این ویژگی برای کارهایی که نیاز به مدیریت تاریخهای بدون سال دارن، خیلی مفیده.
90 |
91 | ## ویژگی Temporal.PlainYearMonth
92 |
93 | ### 6. ویژگی `Temporal.PlainYearMonth` چه کمکی در مدیریت تاریخهای مالی یا گزارشهای ماهانه میکنه؟
94 | > ویژگی `Temporal.PlainYearMonth` برای مدیریت تاریخهایی که شامل سال و ماه هستن (مثل گزارشهای مالی یا برنامهریزیهای ماهانه) استفاده میشه. این ویژگی بهت اجازه میده به سادگی سال و ماه رو مشخص کنی بدون اینکه نگران روز باشی.
95 |
96 | ```javascript
97 | const yearMonth = new Temporal.PlainYearMonth(2024, 5);
98 | console.log(yearMonth); // 2024-05
99 | ```
100 |
101 | > تو این مثال، `Temporal.PlainYearMonth` یه تاریخ رو که فقط شامل سال و ماه هست، ایجاد میکنه. این قابلیت برای مدیریت برنامهریزیهای ماهانه یا گزارشهای مالی خیلی مفیده.
102 |
--------------------------------------------------------------------------------
/README-FA.md:
--------------------------------------------------------------------------------
1 | سوالات جاوا اسکریپت
2 |
3 | به **ریپازیتوری سوالات جاوا اسکریپت** خوش اومدی! اینجا یه راهنمای کامل از جاوا اسکریپت و ویژگیهای مختلف ECMAScript رو میتونی پیدا کنی. فرقی نمیکنه تازهکار باشی یا یه توسعهدهنده باتجربه، این مطالب با اطلاعات مفید و مثالهای کاربردی بهت کمک میکنن که مهارتهات رو توی جاوا اسکریپت ارتقا بدی.
4 |
5 | این ریپازیتوری شامل یه سری فایلهای آموزشی درباره جاوا اسکریپت و ویژگیهای مختلف ECMAScript هست. هر فایل به صورت Markdown نوشته شده و توضیحاتی درباره مفاهیم و ویژگیها همراه با مثالهای کاربردی ارائه میده.
6 |
7 | ## 📚 فهرست مطالب
8 |
9 | 📘 مباحث جاوا اسکریپت
10 |
11 |
12 | - مباحث پایهای: اینجا با مفاهیم پایهای جاوا اسکریپت مثل انواع دادهها، متغیرها، عملگرها، ساختارهای شرطی و حلقهها آشنا میشیم.
13 | - مباحث متوسط: بررسی موضوعاتی مثل توابع، آرایهها، اشیاء، مدیریت خطاها، callbacks و promises، DOM و BOM.
14 | - مباحث پیشرفته: برنامهنویسی شیءگرا، مدیریت حافظه، متدهای پیشرفته آرایهها و رشتهها، `async/await` و مدیریت ماژولها.
15 |
16 |
17 | 🧩 ویژگیهای ECMAScript
18 |
19 | - ES5 - 2009: ویژگی "use strict"، متدهای جدید رشته و آرایه، و JSON.
20 | - ES6 - 2015: ویژگیهایی مثل `let`، `const`، توابع پیکانی، destructuring، کلاسها، promises، و غیره.
21 | - ES7 - 2016: شامل عملگرهای توان و متد `includes` برای آرایهها.
22 | - ES8 - 2017: معرفی padding رشتهها، متدهای شیء، `async/await`، و کاماهای پایانی.
23 | - ES9 - 2018: اضافه شدن iteration غیرهمزمان، متدهای جدید promise، ویژگیهای rest اشیاء، و بهبودهای regex.
24 | - ES10 - 2019: اضافه شدن `trimStart`، `trimEnd`، `Object.fromEntries`، متدهای flat و flatMap، و catch اختیاری.
25 | - ES11 - 2020: ویژگیهایی مثل BigInt، `matchAll`، nullish coalescing، و optional chaining.
26 | - ES12 - 2021: متد `Promise.any`، `replaceAll`، و جداکنندههای عددی.
27 | - ES13 - 2022: ویژگیهای `at` برای آرایهها و رشتهها، فلگ `d` در regex، و `Object.hasOwn`.
28 | - ES14 - 2023: متد `findLast`، `findLastIndex`، و متدهای امن برای آرایهها.
29 | - ES15 - 2024: شامل متدهای جدید گروهبندی و ویژگیهای API زمانی.
30 |
31 |
32 | ---
33 |
34 | ## 📘 مباحث جاوا اسکریپت
35 |
36 | ### مباحث پایهای
37 | [مشاهده فایل](FA/01-basic.md)
38 |
39 |
40 | - معرفی جاوا اسکریپت
41 | - انواع دادهها و متغیرها
42 | - عملگرها و عبارات
43 | - ساختارهای شرطی
44 | - حلقهها
45 |
46 |
47 | ### مباحث متوسط
48 | [مشاهده فایل](FA/02-intermediate.md)
49 |
50 |
51 | - توابع و حوزه متغیرها
52 | - کار با آرایهها و اشیاء
53 | - مدیریت خطاها
54 | - مفهوم callback و Promise
55 | - آشنایی با DOM و BOM
56 |
57 |
58 | ### مباحث پیشرفته
59 | [مشاهده فایل](FA/03-advance.md)
60 |
61 |
62 | - برنامهنویسی شیءگرا
63 | - مدیریت حافظه و بهینهسازی
64 | - متدهای پیشرفته کار با آرایهها و رشتهها
65 | - معرفی و استفاده از
async/await
66 | - مفاهیم ماژولاریتی و مدیریت ماژولها
67 |
68 |
69 | ---
70 |
71 | ## 🧩 ویژگیهای ECMAScript
72 |
73 | ### مباحث ES5 - 2009
74 | [مشاهده فایل](FA/04-ES5-2009.md)
75 |
76 | موضوعات ES5:
77 |
105 |
106 | ### مباحث ES6 - 2015
107 | [مشاهده فایل](FA/05-ES6-2015.md)
108 |
109 |
137 |
138 | ### مباحث ES7 - 2016
139 | [مشاهده فایل](FA/06-ES7-2016.md)
140 |
141 |
146 |
147 | ### مباحث ES8 - 2017
148 | [مشاهده فایل](FA/07-ES8-2017.md)
149 |
150 |
158 |
159 | ### مباحث ES9 - 2018
160 | [مشاهده فایل](FA/08-ES9-2018.md)
161 |
162 |
169 |
170 | ### مباحث ES10 - 2019
171 | [مشاهده فایل](FA/09-ES10-2019.md)
172 |
173 |
183 |
184 | ### مباحث ES11 - 2020
185 | [مشاهده فایل](FA/10-ES11-2020.md)
186 |
187 |
198 |
199 | ### مباحث ES12 - 2021
200 | [مشاهده فایل](FA/11-ES12-2021.md)
201 |
202 |
207 |
208 | ### مباحث ES13 - 2022
209 | [مشاهده فایل](FA/12-ES13-2022.md)
210 |
211 |
221 |
222 | ### مباحث ES14 - 2023
223 | [مشاهده فایل](FA/13-ES14-2023.md)
224 |
225 |
234 |
235 | ### مباحث ES15 - 2024
236 | [مشاهده فایل](FA/14-ES15-2024.md)
237 |
238 |
246 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | JavaScript Questions Repository
2 |
3 | Welcome to the **JavaScript Questions Repository**! Below is a step-by-step guide to JavaScript and ECMAScript features. Whether you are a full beginner or an experienced developer, you will be provided with helpful information and practical examples to enhance your JavaScript skills.
4 |
5 | This repository contains a set of learning files about JavaScript and different features of ECMAScript. Each file is in Markdown format, with a clear explanation of the concepts and features alongside useful examples. The originals have been taken from w3schools.com, I have reorganized it and added further explanation to those topics. Also, all contents have been translated into Persian (Farsi) and added to this repository to make it more convenient for usage.
6 |
7 | برای دسترسی به محتوای فارسی، به فایل [README-FA.md](README-FA.md) مراجعه کنید.
8 |
9 | ## 📚 Table of Contents
10 |
11 | 📘 JavaScript Topics
12 |
13 | - Basic Topics: Covers foundational JavaScript concepts like data types, variables, operators, conditionals, and loops.
14 | - Intermediate Topics: Delves into functions, arrays, objects, error handling, callbacks, promises, DOM, and BOM.
15 | - Advanced Topics: Explores OOP, memory management, advanced array and string methods, async/await, and module management.
16 |
17 |
18 | 🧩 ECMAScript Features
19 |
20 | - ES5 - 2009: Introduces "use strict", new methods for strings and arrays, and JSON handling.
21 | - ES6 - 2015: Features `let`, `const`, arrow functions, destructuring, classes, promises, and more.
22 | - ES7 - 2016: Adds exponentiation operators and the `includes` method for arrays.
23 | - ES8 - 2017: Introduces string padding, object methods, async/await, and trailing commas.
24 | - ES9 - 2018: Focuses on asynchronous iteration, new promise methods, object rest properties, and regex enhancements.
25 | - ES10 - 2019: Adds `trimStart`, `trimEnd`, `Object.fromEntries`, flat and flatMap methods, and optional catch binding.
26 | - ES11 - 2020: Introduces BigInt, `matchAll`, nullish coalescing, and optional chaining.
27 | - ES12 - 2021: Adds `Promise.any`, `replaceAll`, and numeric separators.
28 | - ES13 - 2022: Features `at` methods for arrays and strings, the `d` flag in regex, and `Object.hasOwn`.
29 | - ES14 - 2023: Introduces `findLast`, `findLastIndex`, and safe array methods.
30 | - ES15 - 2024: Covers new grouping methods and Temporal API features.
31 |
32 |
33 | ---
34 |
35 | ## 📘 JavaScript Topics
36 |
37 | ### Basic Topics
38 | [View File](EN/01-basic.md)
39 |
40 |
41 | - Introduction to JavaScript
42 | - Data Types and Variables
43 | - Operators and Expressions
44 | - Conditional Structures
45 | - Loops
46 |
47 |
48 | ### Intermediate Topics
49 | [View File](EN/02-intermediate.md)
50 |
51 |
52 | - Functions and Variable Scope
53 | - Working with Arrays and Objects
54 | - Error Handling
55 | - Understanding Callbacks and Promises
56 | - Introduction to DOM and BOM
57 |
58 |
59 | ### Advanced Topics
60 | [View File](EN/03-advance.md)
61 |
62 |
63 | - Object-Oriented Programming
64 | - Memory Management and Optimization
65 | - Advanced Methods for Arrays and Strings
66 | - Using `async/await`
67 | - Concepts of Modularity and Module Management
68 |
69 |
70 | ---
71 |
72 | ## 🧩 ECMAScript Features
73 |
74 | ### ES5 - 2009 Topics
75 | [View File](EN/04-ES5-2009.md)
76 |
77 |
105 |
106 | ### ES6 - 2015 Topics
107 | [View File](EN/05-ES6-2015.md)
108 |
109 |
137 |
138 | ### ES7 - 2016 Topics
139 | [View File](EN/06-ES7-2016.md)
140 |
141 |
146 |
147 | ### ES8 - 2017 Topics
148 | [View File](EN/07-ES8-2017.md)
149 |
150 |
157 |
158 | ### ES9 - 2018 Topics
159 | [View File](EN/08-ES9-2018.md)
160 |
161 |
168 |
169 | ### ES10 - 2019 Topics
170 | [View File](EN/09-ES10-2019.md)
171 |
172 |
182 |
183 | ### ES11 - 2020 Topics
184 | [View File](EN/10-ES11-2020.md)
185 |
186 |
197 |
198 | ### ES12 - 2021 Topics
199 | [View File](EN/11-ES12-2021.md)
200 |
201 |
206 |
207 | ### ES13 - 2022 Topics
208 | [View File](EN/12-ES13-2022.md)
209 |
210 |
220 |
221 | ### ES14 - 2023 Topics
222 | [View File](EN/13-ES14-2023.md)
223 |
224 |
233 |
234 | ### ES15 - 2024 Topics
235 | [View File](EN/14-ES15-2024.md)
236 |
237 |
--------------------------------------------------------------------------------