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:
Clarence Bakosi
2025-10-30 10:58:13 +01:00
committed by GitHub
parent ce6c4114e7
commit ba1a8e7ace
@@ -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. Lets 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