Câu hỏi phỏng vấn Javascript
Câu hỏi

What is Coercion in JavaScript?

Câu trả lời

Type coercion in JavaScript refers to the automatic or implicit conversion of values from one data type to another, such as strings to numbers or vice versa. This behavior is a fundamental aspect of the JavaScript language due to its dynamic and loosely-typed nature, which allows variables to change types during runtime[1][2][6][7].

In JavaScript, coercion can occur in various contexts, such as when performing arithmetic operations, string concatenation, or comparisons using equality operators. There are two main types of coercion: implicit and explicit.

Implicit Coercion

Implicit coercion happens without the programmer's explicit instruction. It occurs when JavaScript attempts to perform an operation on two values of different types by converting one value to the type of the other. For example, when using the == operator to compare a number and a string, JavaScript will implicitly convert the string to a number before making the comparison[2][7]. Another common scenario is when performing string concatenation with the + operator, where a number will be converted to a string if the other operand is a string[1][4].

Explicit Coercion

Explicit coercion, on the other hand, is when the programmer intentionally converts a value from one data type to another using functions like parseInt(), Number(), or String()[3][4]. This is done to ensure that the values are of the expected type and to avoid the potential pitfalls that can arise from implicit coercion.

Examples of Coercion

Here are some examples of coercion in JavaScript:

  • String Concatenation: When a number is concatenated with a string using the + operator, the number is implicitly coerced into a string[1][4].
  • Mathematical Operations: When a string containing a numeric value is used in a mathematical operation, it is implicitly coerced into a number[1][2].
  • Comparison Operators: The loose equality operator (==) performs implicit co...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Describe Closure concept in JavaScript as best as you could

middle

What are the differences between ES6 class and ES5 function constructors?

junior

What's the difference between throw Error('msg') vs throw new Error('msg') ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào