4

I am to trying to learn Express library and Node.js one step at a time. First I am looking at is the specifics of the Node reqiure(moduleName) function.

I took a look at the documentation for this, and found some weird code in the example documentation:

const circle = require('./circle.js');
console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);

More specifically the ${circle.area(4)} bit.

From what I understand the $ in JavaScript is just like any other variable. When we are using it on client side web development it is used as a delegate for the document function (I think). What is it assigned to when using node?

On top of that, what does this syntax mean? ${circle.area(4)}

If $ is just a reference to some function someFunction(), wouldn't it be equivalent to this someFunction(){cirle.area(4)}. I am not seeing how that could be valid syntax.

Also, why wouldn't they just directly call the circle.area() function directly anyways?

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
Ay Rue
  • 208
  • 1
  • 3
  • 13

1 Answers1

14

This:

`The area of a circle of radius 4 is ${circle.area(4)}`

is an example of ES2015 template strings.

It interpolates whatever circle.area(4) represents directly into the string. If you're curious about this or other ES2015 features, I recommend checking out Babel and playing around in the REPL.

Here's a very simple example to get you started.

You can see this ES2015 code:

const foo = 'some text';
console.log(`${foo} is interpolated.`);

is transpiled to its ES5 equivalent - a simple + concatenation:

var foo = 'some text';
console.log(foo + ' is interpolated.');
Colin Brock
  • 20,219
  • 9
  • 43
  • 61
  • Makes perfect sense, thank you. This is a lot more simple than I thought was going on. – Ay Rue Mar 19 '16 at 22:34
  • @SpencerRue You bet - spend a bit of time with Babel/ES2015 and I have no doubt you'll discover all kinds of new and interesting features :) – Colin Brock Mar 19 '16 at 22:37