Performance: process.env for environment variables
This affects server-side startup time and memory usage by controlling how environment variables are loaded and accessed.
Jump into concepts and practice - no test required
const config = {
dbHost: process.env.DB_HOST,
dbUser: process.env.DB_USER,
dbPass: process.env.DB_PASS
};
function getConfig() {
return config;
}
// Access cached config object instead of process.env each timefunction getConfig() {
return {
dbHost: process.env.DB_HOST,
dbUser: process.env.DB_USER,
dbPass: process.env.DB_PASS
};
}
// Called repeatedly in request handlers| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated process.env access per request | N/A | N/A | N/A | [X] Bad |
| Cache environment variables once at startup | N/A | N/A | N/A | [OK] Good |
process.env in Node.js primarily provide access to?process.env is a special object in Node.js that holds environment variables as strings.API_KEY in Node.js?process.env are accessed like object properties, either with dot notation or bracket notation without parentheses.process.env.API_KEY correctly accesses the variable as a string. The other options incorrectly use function call syntax.console.log(process.env.PORT || 3000);
PORT is set to 8080, what will be printed?process.env.PORT || 3000 means if process.env.PORT is truthy, use it; otherwise, use 3000.PORT is set to string "8080" (a truthy value), the expression evaluates to "8080".const secret = process.env.SECRET_KEY; console.log(secret.length);
SECRET_KEY is not set in the environment.SECRET_KEY is not set, process.env.SECRET_KEY is undefined.length property on undefined causes a TypeError because undefined has no properties.DB_PASSWORD and provide a default of "defaultPass" if it is missing or empty. Which code snippet correctly does this??? operator only defaults null/undefined, keeping empty strings. Ternary checks truthiness, defaulting falsy values like empty strings.process.env.DB_PASSWORD ? process.env.DB_PASSWORD : "defaultPass" returns the env var if it is a non-empty string (truthy), else the default. This safely handles missing or empty values.