Junior — Middle
Millal ja milleks kasutatakse JavaScriptis undefined väärtust funktsiooni tagastustulemusena?
sobes.tech AI
Vastus AI-lt
In JavaScript, the value undefined is often used as the return value of a function when the function does not explicitly return any value. This can be useful to indicate the absence of a result or when the function performs side effects but should not return data.
Examples of using undefined:
- The function does not contain a
returnstatement orreturnwithout a value — by default, it returnsundefined. - Explicitly returning
undefinedto signal that the result is missing or not applicable. - Used to check whether a parameter was passed or a result was computed.
Example:
function logMessage(msg) {
console.log(msg);
// No return, the function returns `undefined`
}
const result = logMessage('Hello');
console.log(result); // undefined
Thus, undefined serves as an indicator of the absence of a value or result.