Search code examples
javascriptstringconcatenationstring-concatenation

String concaternation in javascript


I try to build and a JSON object which eventually will save to a file. But I found out if I use to approach one "element+= element", it will throw "Invalid string length" String. But for approach 2, I can concat a very long String and save a file. (The file is approximate 50mb). So i want to know what is wrong with my first approach?

const person = {
    id: 1,
    name: "john"
}
personJson = JSON.stringify(person);
personJson = personJson + ',';

let element = personJson;
for (let index = 0; index < 500; index++) {
     element += element; 
}
let element = personJson;
for (let index = 0; index < 100000; index++) {
     element = element + personJson; 
}

Solution

  • In both the approaches you're producing different results i.e. Suppose personJson contains string "ab"

    1. element = element + element; is producing the results

      "ab" + "ab"
      
      "abab" + "abab"
      
      "abababab" + "abababab"
      

    and so on... That's why string length is increasing exponentially.

    1. element = element + personJson;

      "ab" + "ab"
      
      "abab" + "ab"
      
      "abababab" + "ab"
      

    and so on... which makes your string length grow linear.

    For better understanding, run below code and see the result:

    const person = {
        id: 1,
        name: "john"
    }
    personJson = JSON.stringify(person);
    personJson = personJson + ',';
    
    let element = personJson;
    for (let index = 0; index < 500; index++) {
         element += element;
         console.log(element.length); 
    }