The scenario in which a Handlebars if statement transitions to an else statement despite the if statement being true

Issue with if else block in handlebars for messaging feature on social media app. Despite passing empty array of messages from controller, always hitting the else statement. Tried various combinations but still not working. What's the problem?

{{#if messages.length}}
  <p>if statement</p>
  <div class="message-container card" id="{{this._id}}">
    <p> Start a new conversation </p>
  </div>
{{else}}
  <p>else statement</p>
  {{#each messages}}

    <div class="message-container card" id="{{this._id}}">

      <div class="profile-picture">
          <img src={{user.profilePicture}} width="100"
            height="100"
            class="rounded-circle"/>
      </div>
      <div class="message-header">
        <span class="name">{{this.sender.firstName}} {{this.sender.lastName}}</span>
        <div class="date-sent">{{this.createdAt}}</div>
      </div>

      <div class="post-body">
        <p class="message">
          {{this.message}}
        </p>
      </div>
    </div>
  {{/each}}
{{/if}}

Answer №1

Absolutely. That is accurate. In the case of an empty array, it should trigger the else statement because a length of 0 equates to being falsy.

Your current code reads as follows:

{{#if messages.length}}
    Display this if the array is not empty because
    message.length is not zero
{{#else}}
    Display this if the array is empty
    because message.length equals zero
{{/if}}

Thus, it is functioning correctly.

If your intention is the opposite, you can either switch the code within the if and else blocks, or swap #if with #unless.

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

Having trouble with javascript regex for date validation?

I am facing an issue with using JavaScript regex to validate date inputs. It is identifying valid dates as invalid, and I'm not sure what the problem is: /^([0-9]d{2})+(\.|-|\/)+([0-9]d{2})+(\.|-|\/)+([0-9]d{4})+$/ The date forma ...

Is it possible for arrow functions to be hoisted within a class in JavaScript?

class App { constructor() { this.canvas = document.createElement('canvas'); document.body.appendChild(this.canvas); this.ctx = this.canvas.getContext('2d'); this.pixelRatio = window.devicePixelRatio > 1 ? 2 : 1; ...

I am unable to locate the appropriate TypeScript type for the `displayName` attribute when it is used as a prop for the `type` component

Having trouble finding the correct type as mentioned in the title. After inspecting with DevTools, I have confirmed that every component I am programmatically looking at has Component.type.displayName. For anything that is not an ElementType, the type is a ...

Node.js Sparse Array Memory Usage Explained

I created a program that generates arrays and noticed an interesting behavior: var results = []; var i = 1; while (true) { console.log(i++); results.push([]); } However, when I modify the program to create sparse arrays instead of empty ones, it cra ...

The mouseup event fails to trigger upon dropping a component with React-dnd

Currently, I am working on a project that requires drag and drop functionality using the React-dnd package. While I have been able to successfully implement this feature, I am facing an issue with the target component where draggable items are supposed to ...

Sorting and Uploading Images made Easy with Drag-and-Drop Functionality

Currently, I am developing a webpage and exploring the option of implementing a drag-and-drop image upload system that allows users to remove and sort images before uploading. I am seeking your opinion on this matter. I am concerned about potential issue ...

Is there a more effective method for detecting changes in a class variable in JavaScript, aside from using setInterval()?

Is there a more readable way to monitor changes of a class variable from its instance? Although I can use setInterval() to achieve this, the code becomes quite difficult to read. let calibrator = new Calibrator("hardwareName"); calibrator.connect(); let ...

Alter the shape of the semi-circle to be more elongated and ellipt

Check out my jsfiddle: http://jsfiddle.net/c4upM/103/ I have managed to create a gray arc and a blue/green arc. My goal is to make these arcs more Elliptic, like this: However, my attempts have not been successful so far. I came across this example: h ...

Always make sure to call for files using their respective names in

Here is how my project structure looks like: . ├── node_modules ├── package.json ├── www │ ├── css │ ├── js │ ├── file.js │ ├── folder │ ├── file2.js │ ├─ ...

I encountered a request timeout H12 error on my app after deploying it to Heroku

Recently, I was working on a small URL shortener project as a practice exercise. It runs fine locally, but when I tried to deploy it to Heroku, I encountered an H12 request timeout error. Can someone assist me in identifying where I went wrong? My code inc ...

Unable to retrieve the value property from document.getElementById as it is null

Can someone help me with reading the input field value in my code? <input type="text" name="acadp_fields[1200]" class="text" placeholder="" value="December 26, 1969"> Here is the code snippet I am us ...

Challenges with React Native's AsyncStorage

When I try to access data stored in asyncStorage using the 'getToken' and 'getMail' functions in the code snippet below, I encounter an issue where the data appears empty when I initially open the page on the emulator. However, upon sav ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2 While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this thro ...

Create Open Graph meta tags dynamically using the MEAN stack, including Angular 2+

I'm currently working on creating unique OG tags for specific item-detail pages. I am using the meta module for Angular from https://github.com/nglibs/meta to generate these meta tags, which work perfectly fine in browsers. However, when it comes to F ...

Encountering a Module node browserify issue

I recently attempted to utilize the Dyson module node from https://github.com/webpro/dyson#installation. However, upon executing the 'dyson' command, I encountered the following error in my terminal. $ dyson Prueba/ module.js:491 throw err ...

Having difficulty retrieving additional arguments within createAsyncThunk when dispatched

When attempting to update the user thunk action by passing an axios instance as an extra argument, I am encountering difficulties in accessing the extra argument. Despite being able to access other fields such as getState</coode> and <code>disp ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

waiting to display information until it is necessary

I am currently working on optimizing my website for improved loading speed and responsiveness. Users can scroll through up to 4k images, apply filters, and sort them based on their preferences. Below is the code snippet for my filtering function: function ...