Last modified: Jul 21, 2026

JavaScript Default Variable Values Guide

Setting default values for variables is a common need in JavaScript. It helps prevent errors and makes your code more robust. This guide shows you the best ways to do it.

You will learn about logical operators, the nullish coalescing operator, and default function parameters. Each method has its own use case. We will cover all of them with simple examples.

By the end, you will know how to handle missing or undefined values confidently. Let's start with the basics.

Why Use Default Values?

Variables can be undefined or null in many situations. This often happens with user input, API responses, or optional function arguments. Without a default, your code may break.

Default values ensure your program runs smoothly. They provide a fallback when data is missing. This makes your applications more reliable and user-friendly.

For example, if a user does not provide their name, you can show "Guest" instead. This small change can prevent many errors.

Using the Logical OR Operator

The logical OR operator (||) is a common way to set defaults. It returns the right-hand value if the left-hand value is falsy.

Falsy values in JavaScript include false, 0, "" (empty string), null, undefined, and NaN. This method works well for many cases.

Here is an example:


// Using logical OR for default
let username = inputName || "Guest";
console.log(username);

// If inputName is undefined or empty
Output: Guest

However, this method has a drawback. It treats all falsy values the same. If inputName is an empty string, it still uses the default. Sometimes you want to keep the empty string.

For instance, a user might intentionally leave a field blank. In that case, || may not be the best choice.

Using the Nullish Coalescing Operator

The nullish coalescing operator (??) is a newer and safer alternative. It only returns the default when the left-hand value is null or undefined.

This operator ignores other falsy values like 0 or "". This makes it ideal for numeric or string inputs where those values are valid.

Here is how it works:


// Using nullish coalescing for default
let score = userScore ?? 0;
console.log(score);

// If userScore is 0, it stays 0
// If userScore is undefined, becomes 0
Output: 0 (if userScore is 0 or undefined)

This operator is now widely supported in modern JavaScript. It is the recommended way to handle defaults for most cases. Learn more about proper variable handling in our JavaScript Variable Declaration Guide.

Default Parameters in Functions

JavaScript functions can have default parameter values. This is the cleanest way to handle missing arguments. You set the default directly in the function definition.

Default parameters work similarly to the nullish coalescing operator. They only apply when the argument is undefined, not when it is null.

Here is an example:


// Function with default parameter
function greet(name = "Visitor") {
    console.log("Hello, " + name);
}

greet();          // Uses default
greet("Alice");   // Uses provided value

Output:
Hello, Visitor
Hello, Alice

This method is very readable. It also reduces the amount of code you need to write. For more on variable scope in functions, check out our JavaScript Variable Scope Explained guide.

Using Ternary Operator for Defaults

The ternary operator is another option. It checks a condition and returns one of two values. You can use it to set defaults based on a condition.

This method is more verbose but gives you full control. You can check for specific conditions beyond just null or undefined.

Here is an example:


// Using ternary for default
let age = (inputAge !== undefined) ? inputAge : 18;
console.log(age);

// If inputAge is undefined, age becomes 18
Output: 18 (if inputAge is undefined)

Use this when you need custom logic. For simple defaults, prefer ?? or default parameters.

Handling Null and Undefined Separately

Sometimes you need to treat null and undefined differently. The ?? operator treats both the same. If you need separate handling, use an if statement.

This gives you full flexibility. You can assign different defaults for each case.

Here is an example:


// Separate handling for null and undefined
let value = someVariable;
if (value === null) {
    value = "Default for null";
} else if (value === undefined) {
    value = "Default for undefined";
}
console.log(value);

// Output depends on input
Output: "Default for null" or "Default for undefined"

This approach is rare but useful in specific scenarios. Most of the time, ?? is enough.

Default Values in Destructuring

Destructuring assignment also supports default values. This is very handy when working with objects or arrays. You can set defaults right in the destructuring pattern.

This makes your code concise and clear. It is especially useful for configuration objects.

Here is an example:


// Default values in object destructuring
let { name = "Unknown", age = 0 } = user;
console.log(name, age);

// If user has no name or age, defaults are used
Output: Unknown 0

This method is elegant and efficient. It works well with API responses. For more on variable types, see our JavaScript Variable Types Guide.

Common Pitfalls to Avoid

One common mistake is using || for numeric defaults. If the value is 0, it becomes the default. Use ?? instead to preserve 0.

Another pitfall is forgetting that default parameters only apply to undefined. Passing null explicitly will not trigger the default.

Always test your code with different inputs. This ensures your defaults work as expected.

Best Practices Summary

Here are the key takeaways for setting default values:

  • Use ?? for most cases where you want to handle null/undefined.
  • Use default function parameters for function arguments.
  • Use || only when you want to treat all falsy values as missing.
  • Use destructuring defaults for objects and arrays.
  • Use ternary or if statements for complex conditions.

Following these practices will make your code cleaner and safer. It will also reduce bugs related to missing data.

Conclusion

Setting default variable values is a fundamental skill in JavaScript. The nullish coalescing operator (??) is the modern and safest choice for most situations. Default function parameters offer a clean way to handle missing arguments.

Logical OR (||) remains useful but has its caveats. Always consider the type of your data when choosing a method. Test edge cases like 0, empty strings, and null.

By mastering these techniques, you will write more robust and predictable code. Your applications will handle missing data gracefully. Start using defaults today to improve your JavaScript projects.