Search code examples
javascriptstringstring-literals

Eloquent JavaScript string concatenation syntax


So this is from the Eloquent Javascript. I am trying to figure out why the return find has "(" + history + " + 5)" instead of "(history + 5)"???

Here is the code snippet:

function findSolution(target) {
  function find(start, history) {
    if (start == target)
      return history;
    else if (start > target)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}

The result:

console.log(findSolution(24));// → (((1 * 3) + 5) * 3)

Solution

  • So difference between "(" + history + " + 5)" and "(history + 5)" is

    "(" + history + " + 5)"

    "("  --> String
    history  -->Number
    "+5)"  -->String
    

    Now if you combine these variable using + it will work like concatenation so "(" + history + "+5)" will give you (5+5) as String

    But "(history + 5)" -->String will be like (history + 5) as history will be not a variable now its a string literal

    Hope it will help