1

Hopefully you will answer it !

var myform = document.getElementById("myform"),
saveBtn = document.getElementById("submit");
saveBtn.addEventListener("click", saveInfo);

var saveInfo = function (e){
    e.preventDefault();
    var dateValue = document.getElementById("inputdeadline").value;
    var todoValue = document.getElementById("textarea").value;
    todoValue = todoValue.replace(/\n/g,"   ");
    if ( dateValue > 24 || dateValue <= 0) {
        myform.reset();
        return false;
    };
    if (!(todoValue)) {
        myform.reset();
        return false;
    };
    var todoObj = {
        todoValue,
        dateValue
    };
    if (localStorage.getItem("localTodoItem") === null) {
        var todoArray = [];
        todoArray.push(todoObj);
        todoArray.sort(function (a, b) {
            return a.dateValue - b.dateValue;
        });
        localStorage.setItem("localTodoItem", JSON.stringify(todoArray));
    } else {
        var todoArray = JSON.parse(localStorage.getItem("localTodoItem"));
        todoArray.push(todoObj);
        todoArray.sort(function (a, b) {
            return a.dateValue - b.dateValue;
        });
        localStorage.setItem("localTodoItem", JSON.stringify(todoArray));
    };
    showTodoItems();
    myform.reset();
};

Here when I am using function declaration for this saveInfo function it is correctly doing all functionalities but when I am using function expression it just reload the page that's it nothing happening. Please help me. If you need more clarification about code please visit github.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
janaravi
  • 106
  • 1
  • 8

1 Answers1

2

This is because function declarations are hoisted, whereas function expressions are not. You're using saveInfo before the expression is executed, which would work for a declaration but not an expression.

Function declaration hoisting on MDN

MrCode
  • 63,975
  • 10
  • 90
  • 112