Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this.

Here's what I'm currently seeing:

You are not getting enough sleep undefined

Code snippet that needs fixing:

function getSleepHours(day) {
  if (day === 'monday') {
    return 8;
  } else if (day === 'tuesday') {
    return 8;
  } else if (day === 'wednesday') {
    return 8;
  } else if (day === 'thursday') {
    return 8;
  } else if (day === 'friday') {
    return 8;
  } else if (day === 'saturday') {
    return 8;
  } else if (day === 'sunday') {
    return 5;
  }
}
const getActualSleepHours = () =>
  getSleepHours('monday') +
  getSleepHours('tuesday') +
  getSleepHours('wednesday') +
  getSleepHours('thursday') +
  getSleepHours('friday') +
  getSleepHours('saturday') +
  getSleepHours('sunday');
const idealSleepHours = 56;
let let2 = getActualSleepHours();

function calculateSleepDebt() {
  if (let2 >= idealSleepHours) {
    console.log('You are getting sound sleep');
  } else {
    console.log('You are not getting enough sleep');
  }
}
console.log(calculateSleepDebt()

Answer №1

In order to incorporate calculateSleepDebt() within a console.log statement, it must produce a printable output. For example:

function calculateSleepDebt() {
  if (let2 >= idealSleepHours) {
    return 'You are getting sound sleep';
  } else {
    return 'You are not getting enough sleep';
  }
}

If you prefer not to modify calculateSleepDebt(), then replace the following:

console.log(calculateSleepDebt()

with:

calculateSleepDebt()

This adjustment ensures that calling calculateSleepDebt() will display the desired message while preventing it from returning nothing when utilized in:

console.log(calculateSleepDebt()

resulting in an output of 'undefined'.

Answer №2

Instead of running console.log() a second time, you should simply call your calculateSleepDebt() function once. By calling console.log() within the function, you are essentially logging something inside another log statement, leading to the undefined result.

To solve this issue, just call calculateSleepDebt() directly without wrapping it in console.log(). The correct last line of your code should be calculateSleepDebt() instead of console.log(calculateSleepDebt() (and don't forget the missing ); at the end).

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

Tips for achieving the Bootstrap 5 Modal Fade Out effect without using jQuery or any additional plugins apart from Bootstrap

I'm facing some challenges in achieving the fade out effect in Bootstrap 5 modals. I am aiming for something similar to the "Fade In & Scale" effect demonstrated here: https://tympanus.net/Development/ModalWindowEffects/ It is crucial for me to accom ...

Can you explain the concept of binding and unbinding in jQuery?

Can you explain the concepts of binding and unbinding in jQuery in simple terms for someone who learns slowly? ...

retrieve trackpoint information using OpenLayers

When displaying a map with a GPX track using OpenLayers 5.3, I noticed that the trackpoints default to a MultiLineString geometry type. The example provided in the GPX-example actually has a larger file size because all of the <trkpt> tags are duplic ...

Ways to Ensure a Property of an Object Remains Synced with Another

I'm dealing with the following Object structure: { a: "123" b: "$a" } In this setup, b should always be equal to the value of a. Any suggestions on how I can achieve this using JavaScript? ...

Click Event for Basic CSS Dropdown Menu

My goal is to develop a straightforward feature where a dropdown menu appears below a specific text field once it is clicked. $(".val").children("div").on("click", function() { alert("CLICK"); }); .container { display: inline-block; } .val { d ...

Can you guide me on how to configure the system proxy settings on Windows operating system?

I'm working on developing a VPN application for Windows and I am interested in setting up a proxy on the system. While there are various methods to accomplish this (such as through the registry or command line), I am searching for a more efficient so ...

Utilize AJAX to retrieve the output of a PHP randomizer

Current situation: I have a PHP file with a randomizer function and HTML that utilizes this function to display strings from a separate text document. The Function: <?php function rand_line($fileName, $maxLineLength = 4096) { $handle = @fopen($fileN ...

AngularJS enables box to smoothly slide up and down when hovered over

I am attempting to create a div that will overlay an image on hover with a slide up and slide down effect. Can anyone provide guidance on how to achieve this without relying on jQuery? I would prefer to utilize only AngularJS in my application. Here is a ...

Creating dynamic images with animated text using PHP

How can I add a personal touch to my website banners for visitors? 1) Currently, only the first frame of GIF images is being displayed in the animated banners 2) I am looking to incorporate a text field where users can input their desired text. Upon form ...

What is the reason behind Ramda having multiple curry functions in its source code, much like Redux having multiple compose functions?

There are _curry1, _curry2, _curry3, and _curryN functions within the depths of Ramda's source code This interesting pattern is also utilized in the redux compose function I find myself pondering: why did they choose this intricate pattern over a mo ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Background image loading gets delayed causing it to flicker

Instead of having separate files for different elements on my site, I decided to keep all the JavaScript in one large file called my_scripts.js. To speed up loading times, I defer the loading of this file using inline JavaScript and make sure it is the las ...

Using a loop to chain jQuery's .when().then() method and ensuring a fixed final call at the end of the

The solution that closely matches my issue can be found at One common use case for .then is chaining ajax requests: $.ajax({...}).then(function(){ return $.ajax({...}); }).then(function(){ return $.ajax({...}); }).then(function(){ retu ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn' ...

Verify two asynchronous boolean variables and trigger a function if both conditions are met

Is there a way to enhance the rendering process so that the renderFilters() method is only called when both variables are true: These two variables are loaded asynchronously through 2 API methods: //getManager() this.isLoadingManager = true; //getPdiPOrg ...

Extract data from JSON object on the server side

Within my web service, I have a method that returns a JSON object: {name:'xx'} When making an Ajax request and parsing the response with 'eval', I encountered an issue. onComplete:function(req){ var data=eval(req.responseText); / ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Modify a section of an HTML text's formatting

function changeEveryCharColor(id) { var part; var whole = ""; var cool1 = document.getElementById(id).innerHTML; console.log(cool1); for(var i = 0; i < cool1.length; i++) { color1 = getRandomInt(255); ...

Tips on reloading or refreshing a react-table component using my form component

I currently have two reactJS components set up: CustomerForm component, which includes a form along with form handling code. CustomerList component, which utilizes react-table to list the customers. Both components are fully functional and operational. ...