default value if var is undifined

Default value if var is undefined

When a variable is declared but not assigned any value, it's default value is undefined. This can happen when you forget to initialize a variable or when a function returns undefined.

It's important to handle undefined values in your code to prevent runtime errors. There are multiple ways to do this:

1. Using the ternary operator


const myVar = undefined;
const defaultValue = myVar ? myVar : 'default value';
console.log(defaultValue); // 'default value'

In the above code, we're checking if myVar is truthy. Since it's undefined, it evaluates to false and the ternary operator returns the default value.

2. Using logical OR operator


const myVar = undefined;
const defaultValue = myVar || 'default value';
console.log(defaultValue); // 'default value'

This approach is similar to the first one but uses the logical OR operator. If myVar is falsy, the expression on the right side of the operator is returned.

3. Using default function parameters


function printName(name = 'default name') {
  console.log(name);
}

printName(); // 'default name'

You can also set default values for function parameters. If the parameter is not passed or is undefined, the default value will be used instead.

In conclusion, always handle undefined values in your code to prevent runtime errors. There are multiple ways to do this, so choose the one that fits your use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe