Can you pass in the value undefined.undefined as an argument to a function in JavaScript?

I am looking to determine if an object contains a specific field with a value, and return a default value if it doesn't.

function checkValue(object, defaultValue) {
  if (!object) {
    console.log(defaultValue);
  } else {
    console.log(object);
  }
}

let testObject;
checkValue(testObject, 'this is the default value')

However, I want this function to handle checking values without requiring them to be passed explicitly...

If I try to pass:

testObject.field1.value

This will result in an error:

TypeError: Cannot read property 'field1' of undefined

Therefore, I need a way to pass any object and evaluate its value without using ternary ?: operators.

Answer №1

To effortlessly achieve this, utilize the power of Optional Chaining

function fetchData(data, defaultData) {
  if (!data) {
    console.log(defaultData)
  } else {
    console.log(data)
  }
}

let dataExample
fetchData(dataExample, dataExample?.field1?.value || 'Default value')

Answer №2

It is impossible to rectify the error within the function as it occurs prior to the function being invoked.

If you are utilizing a JS engine that has support for optional chaining, you can use

testFun(testVar?.foo.value, 'this is default value')
. If this feature is unavailable, it's necessary to reconsider your approach.

function testFun(value, defaultvalue) {
  if (!value) {
    console.log(defaultvalue)
  } else {
    console.log(value)
  }
}

let testVar
testFun(testVar?.foo.value, 'this is default value')

If not, a truthy check must be performed in some way.

function testFun(value, defaultvalue) {
  if (!value) {
    console.log(defaultvalue)
  } else {
    console.log(value)
  }
}

let testVar
testFun(testVar && testVar.foo && testVar.foo.value, 'this is default value')

Alternatively, you may need to modify the code to specify the field to be accessed and implement the checking logic within that function.

function testFun(obj, key, defaultvalue) {
  const value = obj && obj.key && obj.key.value;
  if (!value) {
    console.log(defaultvalue)
  } else {
    console.log(value)
  }
}

let testVar
testFun(testVar, 'foo', 'this is default value')

Answer №3

To handle this scenario, you have the option to utilize optional chaining.

const data = {
  field1: null
};

const value = data.field1?.value;

console.log('Value:', value);

If you opt not to use optional chaining, another approach is to destructure the object by ensuring that the parent of the nested value defaults to an empty object.

const data = {
  field1: {} // Must be initialized as an object for value extraction.
};

const { field1: { value } } = data;
 
console.log('Value:', value);

You could also consider using spread syntax to assign default values to the property, but remember to spread values at each level within the object.

const defaultProps = {
  field1: {
    value: null
  }
}

const data = {
  field1: {
    value: 'foo'
  }
};

const { field1 } = data;
const combined = { ...defaultProps, field1: field1 };

const { field1: { value } } = combined;
 
console.log('Value:', value);

Answer №4

This solution has been successful for me:

function customFunction(fn, defaultVal) {
  try {
    if (fn() === undefined) {
      return defaultVal;
    } else {
      return fn();
    }
  } catch (error) {
    return defaultVal;
  }
}

let testData;
customFunction(() => testData.field1.value, 'this is the default value');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with AJAX in Internet Explorer 9?

I made an AJAX chatroom that works in Chrome and FF, but unfortunately, it doesn't work in IE. Below is the code I used: <script language="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var ajax ...

I am looking to create distinct alphabetical keys in sequential order using AngularJS

Is there a way to create keys in alphabetical order that start with aaaaa and continue on to aaaab, aaaac, and so forth, properly generating the keys? This is how I would like my JSON sample to be created: var keygen={aaaaa, aaaab, ...

Angular Directive: Enabling Form Validation for Submit Button Directive

Managing validations for multiple forms in my project has been quite challenging. Each form requires specific validation expressions, along with a loading element which complicates the reuse of buttons. To tackle this issue, I thought of utilizing a direct ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Is the ctx.arc method in Javascript able to determine the vertices based on the pixel size and radius?

When working with Javascript's Canvas, you have the option to draw a circle easily using the ctx.arc method. I'm curious, does the arc function automatically calculate the optimal number of vertices needed to draw a circle in order to achieve the ...

No longer will popups be blocked

I've been trying to work with jQuery to create a popup. But I'm facing an issue where my code is being blocked by Google. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { var flag = true; ...

Concealing the file input using CSS and JavaScript

One way to hide the file input is by using this code snippet. <div class="custom_btn" >Click to upload</div> <input type="file" name="photo" id="hidden_btn" style="display:none;" /> Next, JavaScript can be used to trigger the hidden inp ...

Setting up a new plugin in ember-cli

Attempting to set up ember-simple-auth in an Ember CLI project, but encountering issues. A new Ember CLI project was created and the following steps were taken to install ember-simple-auth. npm install --save-dev ember-cli-simple-auth ember generate ember ...

Error SCRIPT1002 was encountered in the vendor.js file while using Angular 8 on Internet Explorer 11

Having trouble getting Angular to function properly in IE 11. I've tried all the solutions I could find online. The errors I'm encountering are as follows: SCRIPT1002: Syntax error File: vendor.js, Line: 110874, Column: 40 At line 110874 args[ ...

Success in building with Vue CLI 3 even when encountering lint errors

After setting up a project with Vue CLI 3 rc3 and enabling lintOnSave, I noticed that the linting errors are showing up as warnings during the build process without causing it to fail. Is this the expected behavior? If so, how can I configure it to make ...

"fbAlbum2.js, Bootstrap-tooltip, and Magnific-Popup are three essential tools for

Help needed with fixing the tooltip issue under thumbnails. Here is the setup for the tooltip: $(document).ready(function(){ $("[rel=tooltip]").tooltip({ delay:{show: 300, hide: 150}, placement: 'bottom' }); }); Now, let's loo ...

How come my program gets stuck in a never-ending loop whenever I try to access the API?

I am facing an issue while trying to call my API to retrieve the name of a TP. In the view, all I see is [object promise], and in the browser console, it seems like there is an infinite loop happening. HTML: <table [dtOptions]="dtOptions" cla ...

Using Javascript and JQuery to display the current date upon the initial page load, then preserving the date when navigating to different

When using Bootstrap's Datepicker, I encountered a scenario where I need the current page to load when a user first visits the page. However, if the user selects a different date and then navigates to another page, I want the Datepicker to retain the ...

Splitting data in NodeJS sockets

Whenever I encounter the need to divide data, my standard practice involves converting it into a string format. Here's an example of how I handle data in my function: socket.on('data', function (data) { var str = data.toString().spl ...

Troubleshooting issue with ScrollTo.Document functionality in Javascript For Loop post-refactoring

Recently, I attempted to streamline a list of 10 blocks of javascript code into a for loop. While the individual blocks were functioning properly before, I am encountering issues with the refactored version. Initially, I had 10 separate blocks similar to ...

Getting around popup blockers on safari

Here is the HTML code I am working with: <a href = "#" class="fb">Facebook</a> I am using an onclick event handler that triggers window.open when the link above is clicked. This works fine in Chrome, but it does not work in Safari. How can I ...

Is there a way to verify the custom form when the braintree PayPal checkout button is clicked?

I am seeking a solution to validate a custom PHP form when the Braintree PayPal checkout button is clicked. Currently, the form redirects to the PayPal screen if it is not properly filled out. My goal is to prevent the PayPal popup window from opening if ...

How to include script files in Laravel 5.3

What is the recommended way to include Script files such as vue.js and app.js in Laravel 5.3? Is there a specific method for including them properly? Currently, I am including them as shown below. <script src="http://127.0.0.1/addbook/node_modules/vu ...

Getting information from JavaScript in PHP

Through the utilization of the data() method, I am capturing and storing crucial information. optionScope.data().stage = 'a'; where optionScope = $(this); I aim to preserve this value in my PHP script: <?php include("functions/db. ...

What are some methods for simulating user interaction on input and button elements?

Here is a code snippet available in this stackblitz demo. Essentially, there is a basic form with an input field and a button. Clicking the button will copy the current value of the input to a label: https://i.stack.imgur.com/pw3en.png after click: htt ...