Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
How can I achieve something similar to a pointer to a string in javascript?

Is there a concept like a pointer to a string in javascript? Or how would this be done?

let s1 = "hi";
let s2 = "bye";

// I want to write my code like this [,].forEach();
// This is the bit where I want s1 and s2 in the [,] array to actually be pointers to a string
[s1,s2].forEach(s => {if(s.length < 3) s += "*";});

// I want console.log(s1) === "hi*"
// I want console.log(s2) === "bye" (unchanged)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Javascript does not have pointers.

But you can wrap a value in an object and pass references to that object around.

let s1 = { value: "hi" };
let s2 = { value: "bye" };

[s1,s2].forEach(s => {
  if(s.value.length < 3) s.value += "*";
});

console.log(s1.value)
console.log(s2.value)

That's probably the closest you're going to get to this behaviour.

about 4 years ago · Juan Pablo Isaza Report

0

I think I found a solution myself.

Could anyone comment if this is good practice or not?

It uses the new thing in ES6 where you can assign things [s1, s2] =

let s1 = "hi", s2 = "bye";
[s1, s2] = [s1, s2].map(s => s + (s.length < 3 ? "*" : ""));
about 4 years ago · Juan Pablo Isaza Report

0

You cannot reassign individual identifiers unless you specifically reference the identifier. So given

let s1 = "hi";

The only way to make console.log(s1) show something else would be to have a line of code that does

s1 = // something else

And strings are immutable, of course - for a string, you'd have to reassign it, since you can't mutate it.

I suppose you could put the strings into an array or an object, then examine that instead:

const strings = {
  s1: 'hi',
  s2: 'bye',
};
for (const [key, str] of Object.entries(strings)) {
  if (str.length < 3) {
    strings[key] += '*';
  }
}
console.log(strings.s1);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!