When attempting to print the elements of an array, an "undefined" value unexpectedly appeared

I recently wrote a Javascript code to display a list of items, but for some reason an unexpected undefined text is appearing before the ordered list. I am quite puzzled as to why this issue is occurring.

I am wondering if there is a variable that has not been defined correctly or perhaps inserted in the wrong way within this particular block of code?

You can also view the demo on JSBIN. (Additionally, here is an alternative method to write the code with the same objective.)

var playList = [
  "First Life",
  "Spaceman",
  "Run run run"
];

function print(message) {
  message += "<ol>";
  for (var i=0; i<playList.length; i+=1) {
    message += "<li>" + playList[i]+"</li>";
  }
  message += "</ol>";
  document.write(message);
}

print();

Answer №1

When you don't pass anything to the print() function as a parameter, the value of message defaults to undefined.

You can utilize the OR operator || to assign an empty string to message if no value is passed to the function.

var playList = [
  "First Life",
  "Spaceman",
  "Run run run"
];

function print(message) {
  message = message || ''; // Set message to empty string if not passed

  message += "<ol>"; // Removed unnecessary +

  for (var i = 0; i < playList.length; i += 1) {
    message += "<li>" + playList[i] + "</li>";
  }
  message += "</ol>";
  document.write(message);
}

print();

You can also simplify your code like this:

var playList = [
  "First Life",
  "Spaceman",
  "Run run run"
];

function print(message) {
  document.write((message || '') + '<ol><li>' + playList.join('</li><li>') + '</li></ol>');
}

print();
ol {
  color: green;
}

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

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

"Utilize Ajax and PHP to seamlessly upload a PDF file directly into a MYSQL database

I am trying to figure out how to upload a pdf file from user input into my MySQL database. I have provided code that displays a user registration form with the option to upload a PDF file. My goal is to use AJAX to post this data to a PHP script for storag ...

Access an external URL by logging in, then return back to the Angular application

I am facing a dilemma with an external URL that I need to access, created by another client. My task is to make a call to this external URL and then return to the home page seamlessly. Here's what I have tried: <button class="altro" titl ...

Searching for NavigationEnd events specifically in Angular 12?

When using Angular 11, the following code snippet functions correctly: this.r.events.pipe( filter(event => event instanceof NavigationEnd), map((event: NavigationEnd) => event.url == ROUTES.APPLICATION)) However, when migrating to Angular 12 ...

Is it possible for JavaScript to identify modifications in the HTML, like an input made with Ctrl+Shift+I?

Check out this website I'm currently working on. As a fun challenge for users, we're encouraging them to use ctrl+shift+i to manipulate the HTML and modify certain elements. Is it possible for Javascript or CSS/HTML to detect these changes? For ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

Choosing a specific column in an HTML table using jQuery based on the text within it

I have a table with a similar structure as shown below: <table> <c:forEach ...> <tr> <td>test</td> // this is the initial value <td>random value</td> <td>random value</td&g ...

Deleting multiple data records in PHP/SQL by using a Select Option

Currently, I have developed a system that allows for the deletion of multiple data using a select option. However, I am facing some issues with this functionality. When only one data is selected and the delete button is pressed, it successfully deletes the ...

Retrieving the value of an inner div upon clicking the outer div

I currently have a collection of button divs, each containing distinct information: <div class="button"> <div id="first"> Johny </div> <div id="second"> Dog </div> <div id="third"> Pasta & ...

What is the process for converting a UTC datetime string into the local timezone of users?

I am utilizing Laravel 5.7 for the API and Vue for the frontend development. The API response includes a user's last seen timestamp in UTC format by default, like this: last_seen: "2019-04-17 05:20:37". Laravel API code: $user_details = array( ...

How to add page breaks with spacing and page numbers in HTML to PDF conversion?

Seeking assistance regarding adding spacing between page breaks within an HTML table to accommodate a page number at the bottom of each page. Below, I have depicted my current setup and what I aim to achieve. Is it feasible with the html2pdf library? http ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

How to implement multiple conditions with ng-if in HTML

I need to implement a button that is visible only for specific index numbers: <tbody data-ng-repeat="(wholesalerIndex, wholesaler) in wholesalers"> <tr> <td> <but ...

Is there a way to apply the active class without relying on an anchor element?

After creating a one-page website, I utilized JavaScript to prevent the hash from appearing in the URL. Here is the HTML code: <ul class="click crsl"> <li><a class="page1 dot active"></a></li> <li><a class=" ...

Unique Identifier - primary export (ReactJS - JavaScript)

I am facing an issue concerning generating ID's for alerts using the uuid library. However, when attempting to import the library in the alert.js file, an error message is displayed: ./src/action/alert.js Attempted import error: 'uuid' does ...

What is the process for retrieving the width value from an input field using jQuery?

This example demonstrates an alert trigger when the input value width or cursor crosses the input width. How can we retrieve the width of the input value without just getting the length of the value in jQuery? $('.value_width').text($('.i ...

How to access a webpage on your Android device without the address bar visible

My question relates to sending Push Notifications through OneSignal. Upon clicking a push notification, it automatically redirects the user to my website. Is there a way to hide the address bar on the browser when this happens? I attempted using the follo ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...