What is Arrow function in JavaScript?
Use and evok function without function keyword.
The arrow symbol => is required to be together instead of separated or in different line.
Example 1: Creating a variable With arrow function validating and returning string. It can be also without assigned with var directly with name only
// // with Arrow function
var fullName = (fn, ln) =>
{
if (!fn) {
return `First name is required`
}
if (!ln) {
return `Last name is required`
}
return `Your full name is ${fn} ${ln}`
}
console.log(fullName(`Sam`, `Edward`)) //Your full name is Sam Edward
console.log(fullName(`Sam`)) //Last name is required
console.log(fullName( ``,`Sam`)) //First name is required
Example 2: Creating function without arrow function and validating and returning string. It can be also without assigned with var directly with name only
// without arrow function, with function keyword
function fullName(fn, ln) {
if (!fn) {
return (`First name is required`)
}
if (!ln) {
return (`Last name is required`)
}
return (`Your full name is ${fn} ${ln}`)
}
console.log(fullName(`Sam`,`Edward`)) //Your full name is Sam Edward
console.log(fullName(``,`Sam`)) //Last name is required
console.log(fullName(`Sam`)) //First name is required
Example 3: Creating a variable With arrow function validating and returning string on true and error on false
// with arrow function returning error on false
var fullName = (fn, ln) =>
{
if (!fn) {
throw new console.error(`First name is required`)
}
if (!ln) {
throw new console.error(`Last name is required`)
}
return `Your full name is ${fn} ${ln}`
}
console.log(fullName(`Sam`,`Edward`)) //Your full name is Sam Edward
console.log(fullName(``,`Sam`)) //TypeError: "First name is required" is not a constructor
console.log(fullName(`Sam`)) //TypeError: "Last name is required" is not a constructor
Example 4: Creating a variable With arrow function validating and returning string on true and error on false
// without Arrow function returning error on false
var fullName (fn, ln) {
if (!fn) {
throw new console.error(`First name is required`)
}
if (!ln) {
throw new console.error(`Last name is required`)
}
return `Your full name is ${fn} ${ln}`
}
console.log(fullName(`Sam`,`Edward`)) //Your full name is Sam Edward
console.log(fullName(``,`Sam`)) //TypeError: "First name is required" is not a constructor
console.log(fullName(`Sam`)) //TypeError: "Last name is required" is not a constructor