>  기사  >  웹 프론트엔드  >  개발자가 저지르는 일반적인 JavaScript 실수

개발자가 저지르는 일반적인 JavaScript 실수

WBOY
WBOY원래의
2024-08-14 19:12:02554검색
Common JavaScript Mistakes Developers Make재미있게도 대부분의 시나리오에서 코드 중단 및 오류의 원인은 복잡한 버그가 아니라 코드 기본 사항에 숨겨진 일반적인 실수입니다. 이 가이드는 그러한 상황에서 코딩 여정을 안내하는 나침반이 될 것입니다.

이 기사에서는 이러한 일반적인 실수를 해결하는 방법을 알아봅니다. 이 가이드에서는 실수를 발견하고 이를 해결하는 방법에 대한 매력적인 설명과 실용적인 솔루션을 제공합니다.

더 이상 고민할 필요 없이 바로 시작하겠습니다.

let, var, const의 오용 - 변수 범위

JavaScript에서는 let, var, const와 같은 키워드를 사용하여 변수를 선언할 수 있습니다. 개발자가 var와 let을 공유 가변성 기능(함께 선언된 변수를 변경하거나 변경할 수 있음)으로 인해 상호 교환 가능한 것으로 인식하는 것이 일반적이지만 해당 범위와 관련하여 중요한 차이점이 있습니다. 이러한 키워드는 변수의 범위를 정의하는 방식에 따라 크게 다르다는 점을 인식하는 것이 중요합니다.

var는 let 및 const와 어떻게 다른가요?

자바스크립트는 범위를 전역, 함수, 블록 범위로 나눕니다. 이 세그먼트에서는 함수와 블록이라는 두 가지 유형의 범위에만 집중하면 됩니다.

함수 범위

: 함수 내에서 선언된 변수는 해당 함수 내에서만 접근 가능하며 외부에서는 접근할 수 없습니다. 이 기술은 코드의 다른 부분이 실수로 수정되는 것을 방지하고 캡슐화합니다.

블록 범위: ES6(ECMAScript 2015)에 도입된 블록 범위를 사용하면 if 문, 루프 및 중괄호로 정의된 특정 코드 블록 내에서 let 및 const 키워드를 사용하여 변수를 선언할 수 있습니다. 화살표 기능. 이를 통해 다양한 접근성을 더욱 정확하게 제어할 수 있으며 원치 않는 부작용을 방지하는 데 도움이 됩니다.

블록 범위의 정의를 고려하면 var 키워드가 없다는 것을 눈치챘을 것입니다. 이것이 실수였나요? 별말씀을요! var 키워드를 사용하여 정의된 변수는 함수 범위인 반면, let 또는 const로 선언된 변수는 블록 범위입니다. 다음 코드 조각은 이러한 개념을 더 자세히 설명합니다. 함수 범위 정의를 코드로 변환하는 것부터 시작해 보겠습니다.

위 코드는 var 키워드로 선언된 변수가 함수 범위에 있음을 확인합니다. 테스트 변수가 정의된 함수 외부에서 console.log() 문을 사용하여 테스트 변수에 액세스하려고 하면 "Uncaught ReferenceError: 테스트가 정의되지 않았습니다."라는 오류가 발생합니다.

이 시나리오에서는 변수가 정의된 함수로 로컬 범위가 지정되고 이후에 삭제됩니다. 따라서 함수 외부에서 console.log() 문은 변수가 소멸될 때 메모리 스택에서 제거되기 때문에 오류를 발생시킵니다.
function testVar() {
  var test = "new variable";
}
console.log(test);
// This will return an error: Uncaught ReferenceError: test is not defined.

그러나 이전 시도와 달리 정의 함수 내에서 console.log() 문을 사용하여 테스트 변수에 접근하면 참조 오류 없이 변수의 값을 검색합니다.

아래 코드는 이러한 변수가 범위 유형과 관련하여 어떻게 작동하는지 배우는 데 도움이 됩니다.

function testVar() {
  var test = "new variable";
  console.log(test); // This returns - new variable
}

testVar();

위 코드에서 추론한 내용:

function variableScopes() {
  // testing var scope
  var varTest = 1;
  if (true) {
    var varTest = 2;
    console.log("Inside this if block, var yields this:", varTest);
  }
  console.log("Outside the if block, var yields this:", varTest);

  // testing let scope
  let letTest = 1;
  if (true) {
    let letTest = 2;
    console.log("Inside this if block, let yields this:", letTest);
  }
  console.log("Outside the if block, let yields this:", letTest);

  // testing const scope
  const constTest = 1;
  if (true) {
    const constTest = 2;
    console.log("Inside this if block, const yields this:", constTest);
  }
  console.log("Outside the if block, const yields this:", constTest);
}

variableScopes();
// The code result:
// Inside this if block, var yields this: 2
// Outside the if block, var yields this: 2
// Inside this if block, let yields this: 2
// Outside the if block, let yields this: 1
// Inside this if block, const yields this: 2
// Outside the if block, const yields this: 1

var
    : var 키워드는 함수 범위입니다. 즉, var로 선언된 변수는 함수 전체에서 액세스할 수 있습니다. 제공된 코드는 if 문 내부와 외부에서 varTest 변수를 두 번 선언합니다. 그러나 var의 함수 범위로 인해 변수는 본질적으로 동일한 범위 내에서 다시 선언되어 예기치 않은 동작이 발생합니다. 결과적으로 varTest의 값이 if 블록 내부에서 수정되면 블록 외부에 선언된 변수에 영향을 미쳐 두 console.log 문 모두 값 2를 표시하게 됩니다.
  • let
  • : var와 달리 let 키워드는 블록 범위입니다. 즉, let으로 선언된 변수는 정의된 블록 내에서만 액세스할 수 있습니다. 코드에서 letTest 변수는 let 키워드를 사용하여 if 문 내부와 외부에서 선언됩니다. 블록 범위에서 예상한 대로 if 블록 내부의 letTest 값을 수정하면 해당 블록 내의 변수에만 영향을 미칩니다. 따라서 if 블록 내부의 첫 번째 console.log는 값 2를 표시하고 블록 외부의 console.log는 초기 값 1을 유지합니다.
  • const: Similar to the let keyword, variables declared with const are also block-scoped. The code declares the variable constTest as a constant inside and outside the if statement. Despite being constants, the block scope allows re-declaration within different blocks. However, reassigning a value to a constant is not allowed. Thus, modifying the value of constTest inside the if block affects only the variable within that block, while the value outside the block remains unchanged.

Misunderstanding Loose and Strict Equality

Mastering the use of equality operators is crucial for JavaScript developers. Unlike other languages that rely on a single type, JavaScript offers two: the strict equality operator and the loose equality operator. Understanding the nuances between these operators is essential for writing robust and error-free JavaScript code.

Loose Equality

The loose equality performs type coercion before comparison. This operator tends to convert the operands to the same type before evaluating the equality. While this may seem convenient, it often leads to unexpected results, especially when comparing different data types.

The loose equality operator in JavaScript follows several basic rules to determine when to perform type coercion:

  • If the operands have the same type, In this case, where both have the same type, no coercion is necessary, and the equality comparison gets done.

  • If one operand is null and the other is undefined, JavaScript treats null and undefined as equal when using loose equality. Also, null and undefined values can't undergo type coercion, so they are equal.

  • If one operand is a number and the other is a string, JavaScript will attempt to convert the string operand to a number before comparing the values.

  • If one operand is a boolean, If one operand is a boolean, JavaScript will attempt to convert that operand to the numeric value. The numeric values: the value of false is converted to 0, whereas the value of true is converted to 1.

  • If one operand is an object and the other is not, JavaScript will attempt to convert the object operand to a primitive value (using the valueOf and toString methods) before comparing.

  • If both operands are objects, JavaScript compares their references to determine whether they are the same object. Note that the references are compared, not their values. Two objects are only equal if they reference the same object in memory.

  • If either operand is NaN, the loose equality operator returns false. Note that even if both operands are NaN, you still get false because, by default, NaN is not equal to NaN.

Strict Equality

Strict equality compares both values and types strictly without performing any type coercion. It demands that both operands have the same value and data type for equality to be true. This approach offers clarity and predictability, eliminating the pitfalls of implicit type conversion.

It's of utmost importance to be aware of the potential issues and unexpected outcomes that can arise when using loose equality. To steer clear of these, it is strongly recommended that you always use strict equality when comparing operands. This practice will help you maintain data type integrity throughout your codebase, ensuring a more robust and reliable application.

Here is a code snippet for testing different scenarios with their respective results:

// These snippets showcase how JavaScript's loose and
//strict equality operators behave in various scenarios.

// Testing loose equality
const num1 = 5;
const num2 = "5";

console.log(num1 == num2);

// Testing strict equality:
const num3 = 5;
const num4 = "5";

console.log(num3 === num4); // false

// More examples of loose equality
const value1 = 0;
const value2 = false;

console.log(value1 == value2); // true

// More examples of strict equality:
const value3 = 0;
const value4 = false;

console.log(value3 === value4); // false

// Array comparison with loose equality:
const arr1 = [1, 2, 3];
const arr2 = "1,2,3";

console.log(arr1 == arr2); // true

// Array comparison with strict equality:
const arr3 = [1, 2, 3];
const arr4 = "1,2,3";

console.log(arr3 === arr4); // false

Unneccesary usage of the Else block

JavaScript developers are often fond of adding an else block immediately after an if block, even when the logic inside the else block is essentially the default behaviour or can be handled without the else block. This leads to unnecessary code complexity, which can be simplified by restructuring the code.

An else block is executed when the condition of the preceding if statement is evaluated as false. However, in situations where the else block contains code that can be executed without explicitly checking the condition, using the else block becomes redundant and can be avoided.

Code example:

const isEven = (num) => {
  if (num % 2 === 0) {
    return true;
  } else {
    return false;
  }
}
isEven(4); // true
isEven(3); // false

In this code, the function isEven takes a number as input and checks if it's even. If the number is divisible by two without a remainder, it returns true, indicating that the number is even. Otherwise, it returns false, indicating that the number is odd. However, using the else block is unnecessary because if the condition in the if statement is not met (i.e., the number is not even), the function will naturally reach the next line after the if block without needing an else statement.

Now, without the else statement:

const isEven = (num) => {
  if (num % 2 === 0) {
    return true;
  }
  return false;
}
isEven(4); // true
isEven(3); // false

This code is a more concise version of the first code. It checks if the number is even using the if statement; if it is, it returns true. However, if the number is not even, it will return false. There's no need for an else block because the return false statement will only execute if the condition for the if statement is false.

You can even simplify it further by using an arrow function like this:

const isEven = (num) => {
  return num % 2 === 0;
}

This code further simplifies the logic by directly returning the result of the expression num % 2 === 0. If this expression is evaluated as true, the function returns true, indicating that the number is even. Otherwise, it returns false.

Misusing Mutable and Immutable Types

A developer must understand the difference between mutable and immutable types and how they work under the hood. This segment will take objects as the case study to deeply understand how mutable types work and the mistakes usually made when working with them.

  • Mutable types: In JavaScript, mutable types are those whose values can be changed after creation. Examples include objects and arrays.
  • Immutable types: Conversely, immutable types are types whose values cannot be changed after creation. Examples include strings, numbers, and boolean values.

Consider the code snippet below to understand how immutable types work in JavaScript:

let x = 2;
let y = x; // y becomes the copy of the value in variable x which is 2
x += 2;
y += 1;
console.log(x, y); //This will return 4, 3

In this code sample, we define a variable x with a value of 2. The variable x holds an immutable type, precisely a number. Once you define an immutable type, you can't change it directly.

The line "let y = x" creates a copy of the variable x value and assigns it to y. It's crucial to understand that y is independent of x; any operations performed on x will not affect y, and vice versa. This concept is fundamental to understanding immutable types.

Understanding Mutable Types and References

Mutable types, such as objects and arrays in JavaScript, behave differently from immutable types. When you assign one variable to another with mutable types, they point to the same underlying data in memory. This means that modifying one variable will directly affect the other, as they share a reference to the same data.

Let's consider a simple array code snippet to illustrate this concept:

let x = [];
let y = x;
x.push(1);
y.push(2);
console.log(x); // output [1, 2]
console.log(y); // output [1, 2]

In the code above, variables x and y are arrays initially empty. When we push elements into x and y, we observe that both arrays end up with the same elements - [1, 2]. Unlike immutable types, this behaviour is because mutable types store a reference to the object rather than the actual value.

Here's a breakdown of what happens in the code snippet:

  • Variable Assignment: When we assign y to x, y now references the same array that x points to. No copying of the array's content occurs; both variables reference the same array in memory.
  • Modifying the Arrays: When we push elements into either x or y, the modification directly affects the shared array in memory. Both x and y point to this array, so any changes made using either variable get reflected in the shared array.

Real-world Scenario: Misunderstanding Mutable vs Immutable Types

A common mistake occurs when developers mix mutable and immutable types, mainly when dealing with nested objects. Let’s consider the code snippet below:

const developer = {
  name: "John Doe",
  age: 25,
  core: {
    programmingLanguage: "JavaScript",
    framework: "React",
    role: "Frontend Developer",
  },
};

// creating a similar developer but with a different name and language
const developer2 = developer;
developer2.name = "Jane Doe";
developer2.core.programmingLanguage = "TypeScript";

console.log("developer", developer); // {name: 'Jane Doe', age: 25, core: {programmingLanguage: 'TypeScript', framework: 'React', role: 'Frontend Developer"}}
console.log("developer2", developer2); // {name: 'Jane Doe', age: 25, core: {programmingLanguage: 'TypeScript', framework: 'React', role: 'Frontend Developer"}}

When you run the code above, you will notice that developer2, which copies the property of the developer object, modified the developer object, automatically making the two objects identical. Now, I believe you understand why! It is because they are both pointing to the same reference in memory. The question is, "How can you have the two objects without them modifying each other?"

When dealing with objects in JavaScript, a common approach for creating a copy is to use the spread operator (...). However, it's important to note that this method, known as shallow copy, only addresses part of the cloning process.

Consider the use of the spread operator in creating a shallow copy:

const developer2 = { ...developer };

While this method prevents direct modifications to the global object developer, it falls short when dealing with nested objects. Changes to nested properties in the copied object developer2 can still impact the original object developer. For example:

developer2.core.programmingLanguage = "TypeScript";

This modification affects the programmingLanguage value in the nested core object of both developer and developer2.

The reason behind this behaviour lies in how the spread operator operates. It copies the object's properties, but when encountering nested objects, it copies their references rather than their values. As a result, changes to nested objects in the copied version get reflected in the original object due to shared references.

To overcome this limitation and ensure a complete separation between objects, developers turn to a concept known as deep cloning. Deep cloning involves creating a new object with independent values, including nested objects.

In JavaScript, a standard method for deep cloning is using JSON.parse() and JSON.stringify(). To see how this works, replace this line of code:

const developer2 = developer;

With this:

const developer2 = JSON.parse(JSON.stringify(developer));

This new line of code creates a deep clone of the developer object, ensuring that modifications to developer2 do not affect the developer. The JSON.stringify() method converts the object into a string (an immutable type), and then JSON.parse() converts it back into an object, effectively creating a new object with its separate memory reference. Note that there are other methods for performing deep cloning.

The code using deep cloning:

const developer = {
  name: "John Doe",
  age: 25,
  core: {
    programmingLanguage: "JavaScript",
    framework: "React",
    role: "Frontend Developer",
  },
};

// creating a similar developer but with a different name and language
const developer2 = JSON.parse(JSON.stringify(developer));
developer2.name = "Jane Doe";
developer2.core.programmingLanguage = "TypeScript";

console.log("developer", developer); // {name: 'John Doe', age: 25, core: {programmingLanguage: 'JavaScript', framework: 'React', role: 'Frontend Developer"}}
console.log("developer2", developer2); // {name: 'Jane Doe', age: 25, core: {programmingLanguage: 'TypeScript', framework: 'React', role: 'Frontend Developer"}}

Not Understanding the Context of 'this' Keyword: Arrow Functions vs Regular Functions

One common mistake JavaScript developers encounter is not fully grasping the behaviour of the this keyword within arrow functions compared to regular functions. This distinction is crucial as it affects how this is scoped and accessed within different function types.

Sample Code:

function createProgrammingLanguage(name, author) {
  return {
    name,
    author,

    useRegularFunction: function () {
      console.log(`${this.name} was created by ${this.author}`);
    },

    useArrowFunction: () => {
      console.log(`${this.name} was created by ${this.author}`);
    },
  };
}

const javascript = createProgrammingLanguage(
  "JavaScript",
  "Brendan Eich",
);
javascript.useArrowFunction();
javascript.useRegularFunction();

Run the code above in a code editor. If you use an online code editor like CodeSandbox, you will notice that the editor throws an error - "Cannot read properties of undefined (reading 'type')." It points out that the issue is from the useArrowFunction(), but if you are using an IDE like Visual Studio Code or Sublime Text then you would notice that calling the useArrowFunction() method results in this: "JavaScript was created by Brendan Eich" while calling the useRegularFunction() results in this: "undefined was created by undefined".

Explanation of the code Output

The error encountered when running the useArrowFunction method occurs because arrow functions do not have this context; they inherit it from the surrounding lexical scope where they are defined. In this case, since useArrowFunction is defined within createProgrammingLanguage, it refers to the global context (usually a window object in a browser environment) where name, and author are undefined.

On the other hand, useRegularFunction is a regular function defined inside an object literal. Regular functions have their own this context, which is determined by how they are called. In this context, this correctly refers to the object returned by createProgrammingLanguage(), allowing useRegularFunction() to access name and author properties without issues.

The right way to use this in an Arrow function

This solution demonstrates how to correctly use this within an arrow function by leveraging lexical scoping.

function createProgrammingLanguage(name, author) {
  return {
    name,
    author,

    overallFunction: function () {
      console.log(
        `Regular function: ${this.name} was created by ${this.author}`,
      );

      // Arrow function inherits this from the parent function
      const arrowFunction = () => {
        console.log(
          `Arrow function: ${this.name} was created by ${this.author}`,
        );
      };

      arrowFunction();
    },
  };
}

const javascript = createProgrammingLanguage("JavaScript", "Brendan Eich");

javascript.overallFunction();

// Result
// Regular function: JavaScript was created by Brendan Eich
// Arrow function: JavaScript was created by Brendan Eich

Code Explanation

  • Regular Function Context: Inside the overallFunction, this correctly refers to the object returned by createProgrammingLanguage(). Therefore, the values are retrieved when accessing this.name and this.author.

  • Arrow Function Context: The arrowFunction is defined within overallFunction. Arrow functions inherit this from their surrounding lexical scope, the overallFunction. This inheritance ensures that this within the arrow function refers to the same object as this in the parent regular function. As a result, the arrow function correctly accesses this.name and this.author, producing the desired output without encountering the "Cannot read properties of undefined" error.

By understanding arrow functions' lexical scoping behaviour and leveraging this behaviour to inherit this from the parent function's context, you ensure that arrow functions can access object properties and methods within the appropriate context, resolving issues that result in having the this references being undefined.

Accidentally Creating Memory Leaks

Memory leaks in JavaScript can be subtle and insidious, causing problems on devices with limited memory or in frequently called functions. In JavaScript, memory leaks happen when data is held in memory even though it's no longer needed. The primary cause of memory leaks in JavaScript is often unwanted references. Let's explore some common scenarios, how they lead to memory leaks and the solutions.

  • Accidental Global Variables: Accidentally declaring variables in the global scope can lead to memory leaks, as these variables persist as long as the window object exists. Here's an example of a function that mistakenly creates a global variable:
function defineLanaguage() {
  language = "JavaScript"; // Accidental global variable
}

In this code, language becomes a property of the window object ("window.language = 'JavaScript'"). To prevent this and ensure language is scoped correctly, use var, let, or const:

function defineLanaguage() {
  let language = "JavaScript"; // Scoped variable
}

Using a scoped variable ensures that language goes out of scope at the end of the function's execution, preventing memory leaks.

  • Interval Timers: Interval timers can cause memory leaks if improperly managed. Consider the following code:
let language = "JavaScript";
setInterval(() => {
  console.log(language);
}, 100);

In this code, the interval timer keeps a reference to the language variable, preventing it from being garbage collected even when not needed. To avoid this, clear the interval timer when it's no longer required:

let language = "JavaScript";
let intervalId = setInterval(() => {
  console.log(language);
}, 100);

// Clear the interval when no longer needed
clearInterval(intervalId);

Clearing the interval ensures the handler function and its references are cleaned up properly.

  • JavaScript Closures: Closures in JavaScript can inadvertently cause memory leaks if not managed carefully. Consider the following example:
let outer = function () {
  let language = "JavaScript";
  return function () {
    return language;
  };
};

This closure retains a reference to the language variable, preventing it from being collected as garbage. To avoid this, ensure that closures release unnecessary references:

let outer = function () {
  let language = "JavaScript";
  return function () {
    return language;
  };
};

// Clear the outer function reference when no longer needed
outer = null;

Clearing the reference to the outer function allows the language variable to be garbage collected when it's no longer needed.

By addressing these common scenarios of memory leaks in JavaScript, developers can improve the efficiency and stability of their code. To prevent memory leaks, always scope variables correctly, manage interval timers responsibly, and release unnecessary closures. You can research and see some other instances that lead to memory leaks, but the ones mentioned here are common.

Using Variable has Key in Object Wrongly

One common mistake in JavaScript is improperly using a variable as a key when defining an object literal. This mistake can lead to unexpected behaviour or incorrect object structures. Let's delve into this issue, understand why it occurs, and explore the correct approach to defining object keys dynamically.

In order to understand the mistake, consider the following code snippet:

var type = true;
var language = null;

if (type) {
  language = "TypeScript";
} else {
  language = "JavaScript";
}

var obj = {
  language: "programming language",
};

console.log(obj); // Output - { language: "programming language" }

In the code above, the mistake is using the variable language directly as the object (obj) key. Despite language being dynamically assigned a value based on the type condition, it is interpreted as a literal key language rather than using its value as the key.

Expected Result vs Actual Result

  • Expected Result: { TypeScript: "programming language" }
  • Actual Result: { language: "programming language" }

Correcting the Mistake

JavaScript provides a syntax using square brackets ([ ]) to use a variable as a dynamic key in an object. This allows for the evaluation of the variable's value as the key.

var type = true;
var language = null;

if (type) {
  language = "TypeScript";
} else {
  language = "JavaScript";
}

var obj = {
  [language]: "programming language",
};

console.log(obj); // Output - { TypeScript: "programming language" }

Explanation of the Solution

  • Problem: The original code mistakenly used language as a literal key, resulting in { language: "programming language" }.
  • Solution: By enclosing language within square brackets ([ ]) during object declaration, JavaScript interprets it as a dynamic key, using the value of language as the key name ("TypeScript" in this case).

Conclusion

Through this exploration of common JavaScript mistakes, you've gained valuable insights into how to write cleaner, more efficient code.

Keep growing, learning, and building!

위 내용은 개발자가 저지르는 일반적인 JavaScript 실수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.