mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
feat(curriculum): Add interactive examples to What Is the Object() Constructor, and When Should You Use It (#63311)
Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
+13
-1
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: what-is-the-object-constructor-and-when-should-you-use-it
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
In JavaScript, a constructor is a special type of function used to create and initialize objects. It is invoked with the `new` keyword and can initialize properties and methods on the newly created object.
|
||||
|
||||
@@ -19,6 +19,8 @@ When you call `new Object()`, it returns a new object that can be used to store
|
||||
|
||||
The `Object()` constructor can be used with or without the `new` keyword. When called as a function without `new`, it behaves differently depending on the type of value passed to it. Here's an example of using the `Object()` constructor without the `new` keyword:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const num = 42;
|
||||
const numObj = Object(num); // Creates an object wrapper for the number
|
||||
@@ -27,17 +29,25 @@ console.log(numObj); // 42
|
||||
console.log(typeof numObj); // "object"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The first `console.log` will show `42`, but it is important to note that this is not a regular number. As you can see in the second `console.log`, `numObj` is an object. This is happening because we used the `Object()` constructor to turn that input of a number into an object.
|
||||
|
||||
What happens if we try to pass `null` or `undefined` to the `Object()` constructor?
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const newObj = new Object(undefined);
|
||||
console.log(newObj); // {}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Well, the result will be an empty object. Another use case for the `Object()` constructor is when you're working with a value of unknown type and you need to ensure it's an object. Let’s take a look at the following example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
function toObject(value) {
|
||||
if (value === null || value === undefined) {
|
||||
@@ -58,6 +68,8 @@ console.log(toObject(true));
|
||||
console.log(toObject([1, 2, 3]));
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, we have a function called `toObject`. The second condition will check if the value is a type of object and will return the value if the condition is `true`. This condition will check for objects as well as arrays since arrays are special types of objects.
|
||||
|
||||
If neither of the conditions is true, the function returns `Object(value)`, which converts the input into an object. This works for values like numbers, strings, and booleans
|
||||
|
||||
Reference in New Issue
Block a user