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?
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.');