What is the best way to set a value to null in JavaScript?

Seeking assistance with the "Days Of The Week Exercise" in JavaScript. I have searched MDN and made numerous attempts, but I am still unsure about what null represents and how to effectively use it.

If the argument (num) is less than 1 or greater than 7, the function is expected to return null.

const days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

let returnDay = (num) => {
    if (num >= 1 && num <= 7) {
        return days[num - 1];
    } else {
        return null;
    }
};

returnDay(1); // Monday
returnDay(7); // Sunday
returnDay(4); // Thursday
returnDay(0); // null

Answer №1

1 <= num <= 7 may not function as you expect in JavaScript. This is because binary operators are evaluated from left to right. Therefore, 1 <= num <= 7 actually translates to (1 <= num) <= 7, resulting in either true <= 7 or false <= 7, depending on the value of num. Despite this, it will always return true, although comparing booleans with numbers is not recommended. As the condition always evaluates to true, the else section is never reached, thus null is never returned.

To achieve the desired outcome, consider using the following structure:

if (1 <= num && num <= 7) {
   ...
} else {
   ...
}

Additionally, keep in mind that array indices commence at 0. In the provided example, days[1] would yield 'Tuesday', not 'Monday'.

Answer №2

Here is a helpful answer for you :)

const days = ['Monday', 'Tuesyday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

const getDay = (num) => {
  const dayIndex = num - 1;
  if (days[dayIndex]) { // When you pass 0, there is no element at index -1 in the array,
                  // so the if statement will evaluate to false and return null immediately;
    return days[dayIndex];
  }
  return null;
};

console.log(getDay(1)); // Monday
console.log(getDay(7)); // Sunday
console.log(getDay(4)); // Thursday
console.log(getDay(0)); // null

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

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

Issues with Angular JS page loading when utilizing session and local storage in Google Chrome

I'm currently learning about AngularJS and I stumbled upon this helpful tutorial http://embed.plnkr.co/dd8Nk9PDFotCQu4yrnDg/ for building a simple SPA page. Everything was working smoothly in Firefox and IE, except when it came to using Local and Sess ...

An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined fu ...

Issue with the status of a vue data object within a component

While working on updating my original Vue project, I encountered an error with the data object sports_feeds_boxscores_*. The website features three tabs that display scores for the major sports leagues. I am currently in the process of adding player stats ...

Exploring the capabilities of Socket.IO in Node.js for establishing a connection with an external server

Background: My localhost (referred to as Server A) hosts a node.js server, while an external server running node.js can be found at (known as Server B). Although I lack control or access over Server B, which serves as a dashboard site for an IoT device in ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Speed up the opening and closing of a div element on mouse hover

Looking to create a smooth delay for opening and closing a div when mouse hover. Here is the code I have: function show_panel1() { document.getElementById('hoverpanel1').style.display="block"; } function hide_panel1() { document.getElementByI ...

"An error occurred stating that currDateEnd.setHours is not a valid function

I am attempting to transform my date into ISO format and adjust the hours to 23. Below is my code: var currDateEnd = $('#calendar').fullCalendar('getView').start; console.log(currDateEnd); currDateEnd.toDate().toISOString(); console.lo ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Utilizing key values to access an array and generate a list of items in React.js

This marks my initiation on Stack Overflow, and I extend an apology in advance for any lack of clarity in my explanation due to unfamiliarity with the platform. My current task involves creating a resume with a dynamic worklist feature on my website. The ...

"Enhance your Strongloop app by adding an object

I have a MySQL table with a column of type JSON. { "type": "1", "local": "1", "maker": "1" } I would like to append to the JSON array: [{ "type": "1", "local": "1", "maker": "1" }, { "type": "2", "local": "2", "maker": "2" }] How can I use Strongloop t ...

Encountering an error in a Javascript function: Property 'style' is unreadable because it is undefined

When attempting to run this Javascript function, an error message appears stating, 'Cannot read property 'style' of undefined at showSlides' var slideIndex = 1; showSlides(slideIndex); // Next/previous controls function plusSlides(n) ...

Unable to call upon JavaScript code from an external file

Just starting out with Spring and JavaScript! I've put together a JSP file https://i.sstatic.net/XemJ5.png In my first.js, you'll find the following method: function firstmethod() { window.alert("Enter a New Number"); return true; } H ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

When attempting to add an item to an array within a sub-document using Mongoose and MongoDB, the error message "Property 'messages' not found" is returned

I am working with four different models: teacher, student, teacherMessageSchema, and studentMessageSchema. The teacherMessageSchema is a subdocument within the 'teacher' model under the messages: [teacherMessageSchema] property, while the student ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

Error in executing Javascript function

Below is a Javascript function I created for expanding and collapsing content: function showAns(inp){ var hide="#hideAns"+inp; var show="#showAns"+inp; var ansdiv ="#ans"+inp; $(hide).click(function(){ $(ansdi ...