Search⌘ K
AI Features

Solution Review: Validate Arguments

Explore how to validate function arguments effectively in JavaScript by using typeof checks. Understand how to identify undefined parameters and ensure both inputs are strings before concatenation. This lesson helps you catch common errors in argument handling to write robust JavaScript functions.

We'll cover the following...

Solution

Javascript (babel-node)
var concat = function(string1, string2) {
if (typeof string1 === 'undefined' && typeof string2 === 'undefined') {
throw new TypeError('Both arguments are not defined')
}
else if(typeof string1 === 'undefined'){
throw new TypeError('First argument is not defined');
}
else if(typeof string2 === 'undefined') {
throw new TypeError('Second argument is not defined');
}
if(typeof string1 != "string" || typeof string2 != "string"){
throw new TypeError('not string')
}
return string1 + string2;
}
console.log(concat("a","b"))
try{
console.log(concat("a"))
}
catch(e)
{
console.log(e)
}
try{
console.log(concat(1,2))
}
catch(e){
console.log(e)
}
try{
console.log(concat(undefined,"bd"))
}
catch(e){
console.log(e)
}
try{
console.log(concat())
}
catch(e){
console.log(e)
}

Explanation

...