quiz/js: strict mode and iterating over array and object (#445)

This commit is contained in:
Vikas yadav 2024-06-05 06:04:23 +05:30 committed by GitHub
parent 7fc2166491
commit e025eb85b6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 207 additions and 8 deletions

View File

@ -3,6 +3,8 @@ title: What is `"use strict";`?
subtitle: What are the advantages and disadvantages to using it?
---
## TL;DR
`'use strict'` is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.
## Advantages
@ -22,3 +24,103 @@ subtitle: What are the advantages and disadvantages to using it?
- Concatenation of scripts written in different strict modes might cause issues.
Overall, the benefits outweigh the disadvantages and there is not really a need to rely on the features that strict mode prohibits. We should all be using strict mode by default.
---
## What is `"use strict"` in JavaScript
In essence, `"use strict"` is a directive introduced in ECMAScript 5 (ES5) that signals to the JavaScript engine that the code it surrounds should be executed in "strict mode". Strict mode imposes stricter parsing and error handling rules, essentially making your code more secure and less error-prone.
When you use "use strict", it helps you to write cleaner code, like preventing you from using undeclared variables. It can also make your code more secure because it disallows some potentially insecure actions.
### How to use strict mode
1. **Global Scope**: To enable strict mode globally, add the directive at the beginning of the JavaScript file:
```js
'use strict';
// any code in this file will be run in strict mode
function add(a, b) {
return a + b;
}
```
2. **Local Scope**: To enable strict mode within a function, add the directive at the beginning of the function:
```js
function myFunction() {
'use strict';
// this will tell JavaScript engine to use strict mode only for the `myFunction`
// Anything that is outside of the scope of this function will be treated as non-strict mode unless specified to use strict mode
}
```
### Key Features of Strict Mode
1. **Error Prevention** : Strict mode prevents common errors such as:
- Using undeclared variables.
- Assigning values to non-writable properties.
- Using non-existent properties or variables.
- Deleting undeletable properties.
- Using reserved keywords as identifiers.
- Duplicating parameter names in functions.
2. **Improved Security**: Strict mode helps in writing more secure code by:
- Preventing the use of deprecated features like arguments.caller and arguments.callee.
- Restricting the use of eval() to prevent variable declarations in the calling scope.
3. **Compatibility** : Strict mode ensures compatibility with future versions of JavaScript by preventing the use of reserved keywords as identifiers.
### Examples
1. Preventing accidental global
```js
// without strict mode
function defineNumber() {
count = 123;
}
defineNumber();
console.log(count); // logs: 123
// with strict mode
function strictFunc() {
'use strict';
strictVar = 123; // ReferenceError: strictVar is not defined
}
strictFunc();
console.log(strictVar); // ReferenceError: strictVar is not defined
```
2. Making assignments which would otherwise silently fail to throw an exception:
```js
// without strict mode
NaN = 'foo'; // This fails silently
console.log(NaN); // logs: NaN
// with strict mode
('use strict');
NaN = 'foo'; // TypeError: Assignment to read-only properties is not allowed in strict mode
```
3. Making attempts to delete undeletable properties throw an error in strict mode:
```js
// without strict mode
delete Object.prototype; // This fails silently
// with strict mode
('use strict');
delete Object.prototype; // TypeError: Cannot delete property 'prototype' of function Object() { [native code] }
```
### Important Notes
1. **Placement**: The "use strict" directive must be placed at the beginning of the file or function. Placing it anywhere else will not have any effect.
2. **Compatibility**: Strict mode is supported by all modern browsers except Internet Explorer 9 and lower.
3. There is no way to cancel `"use strict"`
## Further reading
- [Strict mode - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
- [The modern mode, "use strict"](https://javascript.info/strict-mode)

View File

@ -2,17 +2,104 @@
title: What language constructions do you use for iterating over object properties and array items?
---
## TL;DR
There are multiple ways to iterate over object properties as well as array in JavaScript. Following are few of them
### Iterating over object properties
#### Good old `for...in` loop
The for...in loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties
```js
const obj = {
a: 1,
b: 2,
c: 3,
};
for (const key in obj) {
// Optional: to avoid iterating over inherited properties
if (obj.hasOwn(obj, key)) {
console.log(`${key}: ${obj[key]}`);
}
}
```
#### Using `Object.keys()`
Object.keys() returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.
```js
const obj = {
a: 1,
b: 2,
c: 3,
};
Object.keys(obj).forEach((key) => {
console.log(`${key}: ${obj[key]}`);
});
```
### Iterating over array
Most common ways to iterate over array are using `for` loop and `Array.prototype.forEach` method.
#### Using `for` loop
```js
let array = [1, 2, 3, 4, 5, 6];
for (let index = 0; index < array.length; index++) {
console.log(array[index]);
}
```
#### Using `Array.prototype.forEach` Method:
```js
let array = [1, 2, 3, 4, 5, 6];
array.forEach((number, index) => {
console.log(`${number} at index ${index}`);
});
```
#### Using `for...of` loop
This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.
```js
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
```
There are also other inbuilt methods available which are suitable for specific scenarios for example:
- `Array.prototype.filter`: You can use the `filter` method to create a new array containing only the elements that satisfy a certain condition.
- `Array.prototype.map`: You can use the `map` method to create a new array based on the existing one, transforming each element with a provided function.
- `Array.prototype.reduce`: You can use the `reduce` method to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.
---
Iterating over object properties and array is very common in JavaScript and we have various ways to achieve this. Here are some of the ways to do it:
## Objects
### `for...in` statement
This loop iterates over all **enumerable** properties of an object, including those inherited from its prototype chain.
```js
for (const property in obj) {
console.log(property);
}
```
The `for...in` statement iterates over all the object's **enumerable** properties (including inherited enumerable properties). Hence most of the time you should check whether the property exists on directly on the object via `Object.hasOwn(object, property)` before using it.
Since `for...in` statement iterates over all the object's **enumerable** properties (including inherited enumerable properties). Hence most of the time you should check whether the property exists on directly on the object via `Object.hasOwn(object, property)` before using it.
```js
for (const property in obj) {
@ -26,15 +113,24 @@ Note that `obj.hasOwnProperty()` is not recommended because it doesn't work for
### `Object.keys()`
`Object.keys()` is a static method that will return an array of all the enumerable property names of the object that you pass it. Since `Object.keys()` returns an array, you can also use the array iteration approaches listed below to iterate through it.
```js
Object.keys(obj).forEach((property) => {
console.log(property);
});
```
`Object.keys()` is a static method that will return an array of all the enumerable property names of the object that you pass it. Since `Object.keys()` returns an array, you can also use the array iteration approaches listed below to iterate through it.
### `Object.entries()`:
_Reference: [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_
This method returns an array of an object's enumerable properties in `[key, value]` pairs.
```js
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
```
### `Object.getOwnPropertyNames()`
@ -46,8 +142,6 @@ Object.getOwnPropertyNames(obj).forEach((property) => {
`Object.getOwnPropertyNames()` is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it. Since `Object.getOwnPropertyNames()` returns an array, you can also use the array iteration approaches listed below to iterate through it.
_Reference: [Object.getOwnPropertyNames() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)_
## Arrays
### `for` loop
@ -76,8 +170,6 @@ arr.forEach((element, index) => {
The `Array.prototype.forEach()` method can be more convenient at times if you do not need to use the `index` and all you need is the individual array elements. However, the downside is that you cannot stop the iteration halfway and the provided function will be executed on the elements once. A `for` loop or `for...of` statement is more relevant if you need finer control over the iteration.
_Reference: [Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)_
### `for...of` statement
```js
@ -100,4 +192,9 @@ for (let [index, elem] of arr.entries()) {
}
```
_Reference: [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)_
## Further reading
- [Object.getOwnPropertyNames() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)
- [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
- [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)