There is a difference in how JavaScript handles undeclared variables (undefined variable) and undefined values. In the following example the variable dan is declared but never set so it's value is undefined the || returns the first true value it can find so if I pass anything but an empty string, 0, false, NaN, undefined or NULL it'll console.log the passed value. Else it'll log "default value".
function test(dan){
console.log(dan || "default value");
return dan===undefined;
}
console.log(test());//default value, then true
console.log(test(22));//22 then false
A more robust way of checking if a variable was passed would be to see if the variable's value is undefined:
function test(dan){
dan = (typeof(dan)==='undefined')?"default value":dan;
}
In your example the variable dan is not declared at all (variable is undefined), that's why you get error "dan is not defined" because dan is not declared at all.
function test(){
return dan===undefined;//ReferenceError: dan is not defined
}
console.log(test());
You could change your code to this:
var sha = 6, dan;//dan is declared here but no value is set
var secondParameter = dan || sha;
console.log(dan===undefined);//true
console.log(secondParameter);//6
If you want to check if a certain object has a property then it'll not throw an error:
function test(){
return window.neverSetOrDeclared===undefined;
}
console.log(test());//true
It will throw an error when you try to check a property of undefined or null:
null.something//throws error
undefined.something//throws error
window.neverSetOrDeclared===undefined//throws error