
Template Literals
Before start template literals first we need to know what looks like template literals, actually it's not double or single quotes, normally template literals use backticks (backtick) which you will find in the keyboard upper the tab button.
There is a super benefit to use template literals when we need to use multiple lines in one variable.
Now consider the following example:
jslet name = 'John'// Without template literals, tedious/error-prone:console.log('Hello ' + name + '!')// Wrong: The sum of 2 and 4 is 24.console.log('The sum of 2 and 4 is ' + 2 + 4 + '.')// Correct: The sum of 2 and 4 is 6.console.log('The sum of 2 and 4 is ' + (2 + 4) + '.')// With template literals:console.log(`Hello ${name}!`)console.log(`The sum of 2 and 4 is ${2 + 4}.`)
In this example, we can see two types of example one is without template literals and with template literals.
first, we have declared a variable called name then when we try to use without template literals then we just need to separate two string around the variable with using plus, well but 2 and 3 number of example we can see the sum of two number there is a little bit difficult to understand where we need to use a bracket or anything else, In the last two examples we can see them with template literals, we can use any whare any variable just need to backtrack and like ${} this technique.
Multi-Line Display
There is the main benefit we have already known multiple line display within a variable with using backtick. In addition, if you need a line break then just use \n that will be added to the string,
following example:
jslet message = `Hello World! This isa message that takes upmany different lines.`
Default Function Parameters
Basically, Default function parameters enable identifier parameters to be populated with predefined values if there is no value or undefined then it will be passed.
Let's see wtih an example:
jsfunction sayHello(name) {if (typeof name === 'undefined') {name = 'World'}console.log(`Hello ${name}`)}sayHello('Devsrcblog')sayHello()
Here we can see two types of call-back functions one is with value and another one is without a value, first one we have passed a value so it's not undefined then it should be print Hello Devsrcblog. And another one is default function automatically detect a variable we have to use a condition is it undefined or not this condition will be true, then it should print Hello world.
Basically, default function parameter we had to write like this:
jsfunction sayHello(name = 'World') {console.log(`Hello ${name}!`)}
This was the main logic inside default parameter
all posts