-1

i'm beginner on react(javascript), doing todo app, have a questions related to having a return inside if statement but returning nothing(if user writes nothing and press enter it does not count it), but when i take it away it will affect the behaviour of todo app. My question is what is the meaning of this part of the code if (!value) { return }
if there is no value it will return what ? and why taking away the 'return' it will change the behaviour of todo app ? here is code:

import React, { useState } from 'react';
import './App.css';

function Todo({ tod, index }) {
  return <div className="todo">{tod.text}</div>
}
function TodoForm({ addTodo }) {
  const [value, setValue] = useState('');
  console.log(value)

  const handleSubmit = e => {
    e.preventDefault();
    if (!value) {
      return
    }
    addTodo(value);
    setValue('');

  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        className="input"
        value={value}
        placeholder="Add Todo..."
        onChange={e => setValue(e.target.value)}

      />

    </form>
  )
}

function App() {
  const [todos, setTodos] = useState([
    {
      text: ' Learn by doing',
      isCompleted: false
    }
  ]);

  const addTodo = text => {
    const newTodos = [...todos, { text }];
    setTodos(newTodos);
  }

  return (
    <div className="app">
      <div className="todo-List">
        {todos.map((todo, index) =>
          <Todo key={index} index={index} tod={todo} />
        )}
        <TodoForm addTodo={addTodo} />
      </div>
    </div>
  )

}
export default App;

here i have javascript code where i'm trying to have same kind of statement as the code above ( if(!text){ return } ) here it does not matter if i have 'return' or dont have, it is the same both ways(why in previous example it was different ?) :

function myFunction(text) {
var text=document.getElementById('text').value

event.preventDefault();
console.log(text);

if(!text){
return 
}
else{
document.getElementById('demo').innerHTML = "Text typed: "+text; // if nothing
}}
<form onsubmit="myFunction()">
<input  type="text" id="text" >
</form>

<p id="demo"></p>

English is not my mother language so sorry for mistakes.

  • why am i getting downvoted ? i have code and question and also compared with same kind of other code –  Jul 27 '20 at 20:49
  • Looks like these downvotes were cleaned up - perhaps a misunderstanding. – kJs0 Jul 27 '20 at 21:05
  • The downvotes were not "cleaned up"; two people upvoted. See [When is it justifiable to downvote a question?](https://meta.stackoverflow.com/q/252677/215552). A modicum of research into the [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) statement would tell you what gets returned if no value is specified. One of the reasons for a downvote is "The question does not show any research effort..." Also, your two pieces of code are not equivalent; one uses are `return` in an `if` block with no `else` and the other uses `else`, which changes the flow. – Heretic Monkey Jul 27 '20 at 21:16
  • But that's just my guess; I have no idea, and votes are anonymous. – Heretic Monkey Jul 27 '20 at 21:18
  • @HereticMonkey i tried without else also and did not write anything just press enter and check from console its working but with the first code (react) when i dont write anything and press enter, nothing shows in console –  Jul 27 '20 at 22:58

2 Answers2

0

Copying your code in question here:

const handleSubmit = e => {
    e.preventDefault();
    if (!value) {
      return
    }
    addTodo(value);
    setValue('');

  }

This is considered a null check. What you're saying inside of that function is effectively "if this variable is true, don't proceed with the rest of the function and return as undefined". If your value variable equates to a value that is null or undefined in Javascript (attached link goes to a SO answer for the difference between null and undefined) then your ! operator will return true for the if statment again (as I said above) not running the rest of the function and returning undefined.

See this codepen here where if you toggle the variable "shouldRun" from true and false you'll either get the console log after the return, or undefined returned: https://codepen.io/kjscott27/pen/wvMbKJb?editors=1111

EDIT: I felt it was necessary to perhaps add additional sources for the difference between null and undefined. Additionally this resource has answers towards definitions of both terms directly from ECMA script and further reading, here in this other SO answer.

kJs0
  • 138
  • 1
  • 9
  • "if this variable is true, don't proceed with the rest of the function and return as undefined", but it is still proceeding with the rest as , addTodo(value); setValue(''); –  Jul 29 '20 at 11:24
  • You're checking the inverse of that variable here which makes sense because if value is true that means it has a value assigned to it. If value is empty (or false), the inverse check on value will return true and your function won't run. I would suggest reading up on what null checking is (as i mentioned in my answer). Also here's an additional answer from inside of SO regarding some [null checking in Javascript](https://stackoverflow.com/questions/6003884/how-do-i-check-for-null-values-in-javascript) – kJs0 Jul 29 '20 at 11:30
0

Adding onto kjs0's answer,

In Javascript, returning no value will be undefined. Example:

function myFunc() {
  return;
}

myFunc() // the returned value is undefined
ProAdam
  • 51
  • 5
  • so returning no value in javascript and returning no value in reactjs are different ? –  Jul 27 '20 at 21:20
  • ReactJs is a JavaScript library. In both spaces your return no value is `undefined`. Note, this is different from `return null` – ProAdam Jul 27 '20 at 21:21
  • so why in my first code it matters if i remove 'return' but in second code it does not ? –  Jul 27 '20 at 21:23
  • In your code, if you don't leave the function (return), it will continue to execute `addTodo`, and `setValue`. In the other code, this won't happen because it is escaped by the `else` statement – ProAdam Jul 27 '20 at 21:44
  • no if i leave it it will continue to execute addTodo and setValue and if i dont leave it and user press enter it will add one white to todo list. –  Jul 27 '20 at 22:53