'Can we write IF statement without else in javascript

I wrote some code to create an simple todo app in angular js. I have the following function code to remove the tasks from the list.

Javascript code

$scope.deleteTask =  function(){
    $scope.tasks.splice(this.$index, 1);
    if($scope.tasks.length < 1){
        $scope.noTask = true;
    }     
};

HTML code

    <li ng-repeat="task in tasks track by $index">{{task}}  <button ng- click="deleteTask()">x</button></li> </li>
    <p ng-show="noTask">No Tasks Available </p>

I wanted to show a message when there are no tasks in the list. i have achieved this using "if" statement. but i don't need an else here. i am not sure whether its the right way. what will be the proper way to achieve this



Solution 1:[1]

There is nothing wrong with your code.
You can use the if statement without the else.
In your case I would recommend writing it as follows to remove some unnecessary code:

<p ng-show="tasks.length==0">No Tasks Available </p>

Solution 2:[2]

As in any (?) other programming language you can omit else part if it's empty.

Just make sure that if you assign some value in if (true) than if it's not executed have default value for that variable:

var test = false;

if (Math.rand() < 0.5) {
    test = true;
} 

Also there is shorthand for if else (where you can't omit else part):

var test = Math.rand() < 0.5 ? "True value" : "False value";

Solution 3:[3]

I wanted to show a message when there are no tasks in the list. i have achieved this using "if" statement. but i don't need an else here. i am not sure whether its the right way. what will be the proper way to achieve this

You don't need an else statement, you can use ng-if.

The ng-if statement is also available without an else condition.

You should be able to use this angular code:

$scope.deleteTask =  function(){
    $scope.tasks.splice(this.$index, 1);
};

And this part for the HTML:

<li ng-repeat="task in tasks track by $index">{{task}}  
     <button ng-click="deleteTask()">x</button>
</li>
<p ng-show="noTask" ng-if="tasks.length == 0">No Tasks Available </p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Liam
Solution 2 Justinas
Solution 3 Liam