Skip to content

Instantly share code, notes, and snippets.

View gladchinda's full-sized avatar

Glad Chinda gladchinda

View GitHub Profile
const html = (`
<html>
<body>
<div>Template literals are super cool.</div>
</body>
</html>
`).trim();
console.log(html);
// <html>
const price = 24.99;
console.log("The item costs $" + price + " on the online store.");
// The item costs $24.99 on the online store.
const price = 24.99;
console.log(`The item costs $${price} on the online store.`);
// The item costs $24.99 on the online store.
const price = 24.99;
const discount = 10;
console.log(`The item costs $${(price * (100 - discount) / 100).toFixed(2)} on the online store.`);
// The item costs $22.49 on the online store.
[
'The price of ',
' units of the item on the online store is $',
'.'
]
function pricing(literals, ...replacements) {
// Initialize the final string
let finalString = '';
for (let i = 0; i < replacements.length; i++) {
// Get the current literal and replacement
const literal = literals[i];
const replacement = replacements[i];
// Trim trailing whitespaces from the current literal
const price = 24.99;
const discount = 10;
const quantity = 4;
const totalPrice = quantity * price * (100 - discount) / 100;
// WITHOUT TEMPLATE TAG
console.log(`The price of ${quantity} units of the item on the online store is $${totalPrice}.`);
// The price of 4 units of the item on the online store is $89.964.
// METHOD 1: Short-circuiting
// Using the logical OR (||) operator
function convertToBase(number, base) {
number = parseInt(number) || 0;
base = parseInt(base) || 10;
return number.toString(base);
}
// METHOD 2: Ternary (?:) operator
function convertToBase(number = 0, base = 10) {
return parseInt(number).toString(parseInt(base));
}
function getDefaultNumberBase() {
return 10;
}
function convertToBase(number = 0, base = getDefaultNumberBase()) {
return parseInt(number).toString(parseInt(base));
}