Friday, September 19, 2025
HomeLanguagesJavascriptHow to use if statements in Underscore.js templates ?

How to use if statements in Underscore.js templates ?

Underscore.js is a javascript library that provides helper functions in functional programming without extending the built-in objects. This package consists of 100 functions like map, filter, etc. 

We can install this by using npm.

npm install underscore

Syntax:

const _ = require('underscore');

Approach:

  • Write your markup code regarding the requirement.
  • We should always place the underscore.js code inside the <script> tag.
  • In this case, Write the if and else logic based upon a problem statement.
  • Once the code is error-free we can surf the file as usual.
  • In this way, we need to write the code in <script> tag;

Example: This example shows the use of the above-explained approach.

html




<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript"
                src=
    </script>
</head>
  
<body>
    <script type="text/javascript">
        <% if (typeof (number) != "undefined") {%>
            <span class="number"><%= number %></span>
            <%}
        else {
            print("Number doesn't exist");
        } %>
    </script>
</body>
</html>


Output:

Number doesn't exist
RELATED ARTICLES

Most Popular

Dominic
32301 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6666 POSTS0 COMMENTS
Nicole Veronica
11840 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11898 POSTS0 COMMENTS
Shaida Kate Naidoo
6781 POSTS0 COMMENTS
Ted Musemwa
7056 POSTS0 COMMENTS
Thapelo Manthata
6739 POSTS0 COMMENTS
Umr Jansen
6745 POSTS0 COMMENTS