Expression interpolation in template strings

Question | Feb 17, 2016 | hkumar 

Compared to other programming languages like Python, Javascript offered limited utilities to developers for string processing. Things are certainly going to get better with ES6 template strings. Template strings are literals and expression placeholders enclosed in back-ticks ( ` ` ). An expression placeholder is of form {expression} that is substituted by a variable, or result of an expression, or even a function. The placeholder syntax should look familiar to you if you know about UNIX shell parameter substitution.

Here is an example of expression substitution or interpolation:

var name = 'Carla';
var a = 20;
var b = 30;
console.log(`Hello ${name}! You owe me $${a+b}.`);
// Hello Carla! You owe me $50.

Note that template strings by default call a function - tag expression - to concatenate all the literals and expression results. You can override that default behavior by writing your own tag function and calling that instead. I am not going to talk much about tag expression here because that is an advance use of template strings. In brief here is the syntax of tag function and how to call it:

function myTag( literals, ...substitutions) {
        console.log( literals ); // [ "Hello ", "! You owe me $", "." ]
        console.log(substitutions); // [ "Carla", 50 ]
        /* Normally you would do some processing 
           and return a processed string */
}
myTag`Hello ${name}! You owe me $${a+b}.`;

Even if you do not write your own tag functions you have plenty to gain from template strings.
Here is the practice question of this post:

var account = { 
    name: 'Jack',
    balance: 100,
    transaction: function( amount ) { 
           this.balance += amount;
           return this.balance;
    }
};

var debit = 10;
console.log(`${account.name} has $${account.balance} balance.`);
console.log(`After a $${debit} debit his balance is $${account.transaction(-debit)}.`);

What would be the output of above?

2015 nextptr