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

Explain Null and Undefined in JavaScript

Câu trả lời

In JavaScript, null and undefined are both primitive values that represent the absence of a specific value, but they are used in different contexts and have different implications in the language.

Undefined

undefined is a primitive value that is automatically assigned to variables that have been declared but have not yet been assigned a value. If you define a variable without initializing it, it will have the value undefined. It is also the default return value for functions that do not explicitly return anything, and the value you get when you try to access an object property or array element that does not exist.

Here's an example of undefined:

javascript Copy
let uninitializedVariable;
console.log(uninitializedVariable); // Output: undefined

The typeof operator returns "undefined" when applied to an undefined value:

javascript Copy
console.log(typeof uninitializedVariable); // Output: "undefined"

Null

null, on the other hand, is an intentional absence of any object value. It is often used to indicate that a variable should hold an object but currently does not. Unlike undefined, null must be assigned explicitly. It is commonly used to denote that a variable is empty or to represent the end of a chain of object references.

Here's an example of null:

javascript Copy
let emptyVariable = null;
console.log(emptyVariable); // Output: null

When you use the typeof operator on a null value, it returns "object", which is a historical bug in JavaScript since null is not actually an object:

javascript Copy
console.log(typeof emptyVariable); // Output: "object"

Key Differences

  • undefined indicates that a variable has been declared but not defined, while null is an explicit assignment that indicates the deliberate absence of a value.
  • The typeof operator returns "undefined" for undefined values and "object" for null values.
  • In terms of equality, null and undefined are equal when compared with the abstract equality operator (==), but not when compared with the strict ...
junior

junior

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

senior

Explain difference between: function Person(){} , var person = Person() , and var person = new Person() ?

entry

Explain arrays in JavaScript

middle

Describe Closure concept in JavaScript as best as you could

Bình luận

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

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