Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default values in javascript template strings

Is there any way to access the javascript template-string engine to provide default values for undefined variables?

console.log(`this variable is undefined: ${x}`) 
// throws ReferenceError

// but i want to generate something like this:
"this variable is undefined: <warning! undefined variable>"

This would be ok, too:

function tag(strings,...values){
   // values[i] should be "undefined" if this variable is undefined
}
tag`${x}`

If thats not possible, is there a template string engine that does exactly what javascript does and has this feature?

like image 787
tino Avatar asked Dec 27 '17 06:12

tino


People also ask

What is a template string in JavaScript?

Template strings are a powerful feature of modern JavaScript released in ES6. It lets us insert/interpolate variables and expressions into strings without needing to concatenate like in older versions of JavaScript. It allows us to create strings that are complex and contain dynamic elements.

What are ES6 template strings?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.

What is the default value of variable in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.

Which of the following is the correct format for template string in JavaScript?

In JavaScript, the template string implements the string interpolation. A template string is defined by wrapping a sequence of characters into a pair of backticks `I'm template string` . The template string placeholders have the format ${expression} , for example `The number is ${number}` .


1 Answers

You can use the || to coalasce the value, like:

console.log(`this variable is undefined: ${x || '<warning! undefined variable>'}`) 
like image 103
Ayush Gupta Avatar answered Sep 20 '22 01:09

Ayush Gupta