JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Instead of halting, I would like it to return an empty string.

splitString(str: string, length: number) {
    if (str != null && str != undefined){
        var words = str.split(" ");
        for (var j = 0; j < words.length; j++) {
            var l = words[j].length;
            if (l > length) {
                var result = [], i = 0;
                while (i < l) {
                    result.push(words[j].substr(i, length))
                    i += length;
                }
                words[j] = result.join(" ");
            }
        }
        return words.join(" ");
    }
    else if (typeof(str) === null ){
        return " "
    }
}

Previously, the program would stop with an error message when encountering a null value, but now it is able to handle it gracefully by returning an empty string. Thank you for the help.

Answer №1

One way to handle default values is by using an empty string, which can be specified either in the function arguments or within the code block itself. Here's an example showcasing this approach:

splitString(str: string, length: number) {
  var words = (str || "").split(" ");
  for (var j = 0; j < words.length; j++) {
    var l = words[j].length;
    if (l > length) {
      var result = [], i = 0;
      while (i < l) {
        result.push(words[j].substr(i, length));
        i += length;
      }
      words[j] = result.join(" ");
    }
  }
  return words.join(" ");
}

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

Creating a React.js component and setting an initial value within it

Recently delved into the world of React.js and currently attempting to create a reusable header that can switch between two states: one for when the user is logged in, and another for when the user is not logged in. // Header.js var Header = React.createC ...

Guide on how to retrieve a single document (mongoose/mongoDB)

Storing data in a database is crucial for many applications. { "_id": "62fa5aa25778ec97bc6ee231", "user": "62f0eb5ebebd0f236abcaf9d", "name": "Marketing Plan", "columns": [ { ...

a user-friendly database solution for storing data in HTML 5 and Google Drive

Greetings, I am currently faced with the following dilemma: As I work on my angular 2 application, I find myself needing to save certain data. Personally, I have a preference for saving data in JSON format. Here is the scenario: Imagine a todo list where ...

Using Kendo's Angular Grid to link data sources

I'm currently facing a minor issue with the Kendo Grid for Angular. My attempt to bind data after fetching is resulting in the following error: ERROR TypeError: Cannot read properties of undefined (reading 'api') This indicates that this. ...

Enabling onClick based on conditions

I'm struggling to disable a Link onClick when a certain condition is not met. Attempted to move the logic outside of render using a function, but the button always ends up disabled. Tried CSS to disable click, only to realize that tab and enter can ...

Unable to display socket data in Angular js Table using ng-repeat

div(ng-controller="dashController") nav.navbar.navbar-expand-sm.navbar-dark.fixed-top .container img(src='../images/Dashboard.png', alt='logo', width='180px') ul.navbar-nav li.nav-item ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...

The functionality of the Bootstrap carousel may be compromised when initialized through JavaScript

Why isn't the Bootstrap carousel working in the example below? It starts working when I paste it into .content <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script sr ...

Two separate projects targeting Admin and User interfaces versus a unified application featuring distinct themes for each user role

In React, there is a scenario that needs to be implemented. An admin panel with various functionalities like Auth, charts, analytics, and user management has already been pre-built. The goal now is to connect this admin panel to another website as the back ...

Caution: The attribute name `data-*` is not recognized as valid

I am attempting to import an SVG file in my NEXT.js project using the babel-plugin-inline-react-svg. I have followed all the instructions and everything is functioning perfectly. // .babelrc { "presets": ["next/babel"], "plugin ...

Retrieving images from GridFs and displaying them in an Angular application

I have been working on storing images from my angular app in MongoDB using GridFs. However, I am having trouble retrieving the images from the database to the app. I am using a custom objectId for the query. UPDATE After some changes, I managed to get t ...

Tips for incorporating JavaScript into .ascx pages

What are some ways to incorporate javascript in .ascx files? ...

How can JavaScript automatically calculate the sum of various numbers entered into multiple input fields?

I would like to automatically add different numbers entered in multiple input fields using JavaScript. Is there a way to calculate the sum of numbers entered in various input fields using JavaScript? "The input field consists of n numbers..." and I am ut ...

Is it possible to establish communication between JAVA and Javascript using Sockets?

Recently, I developed a Java application that generates some data and saves it in a text file on my computer. Instead of saving this data in a text file, I am looking to send it via Socket. Here is an example: Java public static void main(String argv[] ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Which is more effective: Layering multiple canvases in the DOM or consolidating all drawing on a single canvas?

In my previous projects, I have had experience working with layered canvases. While some of my colleagues swear by this approach, I find myself skeptical about its effectiveness. My primary concerns are: If multiple canvases are layered and one undergoes ...

How can I target the initial last element within an *ngFor loop?

In my current project using Ionic, I am developing a personal application where I aim to implement an alphabetical header/divider for a list of games. The idea is to check the first letter of each game, and whenever it differs from the last game's ini ...