Skip to content
the poor coder

default value if var is undifined

Poor Man
Published
Reading time
1 min read
On this page

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#

Text

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#

Text

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#

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC