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 Difference Between Primitive and Non-Primitive Data Types (#63308)
Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
+9
-1
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: what-is-the-difference-between-primitive-and-non-primitive-data-types
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
In JavaScript, understanding the difference between primitive and non-primitive data types is important for writing efficient and bug-free code.
|
||||
|
||||
@@ -17,6 +17,8 @@ When you work with primitive data types, you're dealing directly with their valu
|
||||
|
||||
Primitive values are immutable, which means once they are created, their value cannot be changed. However, you can reassign a new value to the variable. Here's an example of working with primitive data types:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let num1 = 5;
|
||||
let num2 = num1;
|
||||
@@ -25,12 +27,16 @@ num1 = 10;
|
||||
console.log(num2); // 5
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, we are assigning a primitive value (`5`) from `num1` to `num2`. This creates an independent copy of the value. As a result, any changes made to the original variable (`num1`) do not affect the copy (`num2`).
|
||||
|
||||
Non-primitive data types, on the other hand, are more complex. In JavaScript, these are objects, which include regular objects, arrays, and functions. Unlike primitives, non-primitive types can hold multiple values as properties or elements.
|
||||
|
||||
When you create a variable with a non-primitive value, what's stored in the variable is actually a reference to the location in memory where the object is stored, not the object itself. This leads to some important differences in behavior. Here's an example with non-primitive types:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const originalPerson = { name: "John", age: 30 };
|
||||
const copiedPerson = originalPerson;
|
||||
@@ -40,6 +46,8 @@ originalPerson.age = 31;
|
||||
console.log(copiedPerson.age); // 31
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example we have an object called `originalPerson` with two properties of `name` and `age`. We then assign the `originalPerson` object to a variable called `copiedPerson`.
|
||||
|
||||
Then we update the `age` value for the `originalPerson` object. When we log the `age` property of `copiedPerson` object it shows the updated value.
|
||||
|
||||
Reference in New Issue
Block a user