Using Pointers in JavaScript

Posted by

Pointers in JavaScript

Pointers in JavaScript

Pointers are a powerful concept in computer programming that allow us to store memory addresses of variables. They are commonly used in low-level languages like C and C++, but they can also be simulated in high-level languages like JavaScript.

In JavaScript, pointers are not supported directly, but we can achieve similar functionality using references and object references.

Using Object References

Objects in JavaScript are passed by reference, which means that when we assign an object to a variable, we are actually storing a reference to the object in memory. This allows us to modify the object’s properties through the variable.

For example:

let obj1 = {
  name: "Alice",
  age: 30
};

let obj2 = obj1;
obj2.age = 40;

console.log(obj1.age); // Output: 40

Here, both obj1 and obj2 reference the same object in memory. When we modify obj2.age, the changes are reflected in obj1 as well.

Using References

Primitive data types like numbers and strings are passed by value in JavaScript, which means that when we assign a variable to another variable, a copy of the data is created. However, we can use references to simulate pointers for primitive data types.

For example:

let num1 = 10;
let num2 = num1;

num2 = 20;

console.log(num1); // Output: 10

In this case, num1 and num2 are not references to the same memory location, so modifying num2 does not affect num1.

By using object references and references in JavaScript, we can achieve similar functionality to pointers in low-level languages. This allows us to work with memory addresses and manipulate data efficiently in our code.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@romeorichardson3138
7 months ago

C made me wanna cry making Pointer connected Linked Lists

@liondovelearning1391
7 months ago

Hmmm