Doubts with this function

Asked

Viewed 41 times

1

I have this code in javascript and want to ask some questions:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <h3>Faça uma saída de soma de 2 inteiros, ex: alert(2 + 2)</h3>
            </div>

            <div class="col-lg-3">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1">N1</span>
                    </div>
                    <input type="text" class="form-control" id="n1" placeholder="Digite o n1">
                </div>
            </div>

            <div class="col-lg-3">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1">N2</span>
                    </div>
                    <input type="text" class="form-control" id="n2" placeholder="Digite o n2">
                </div>
            </div>

            <div class="col-lg-1">
                <button class="btn btn-success">Somar</button>
            </div>

            <div class="col-lg-3">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1">Result</span>
                    </div>
                    <input type="text" class="form-control" id="result" placeholder="Result">
                </div>
            </div>

        </div>
    </div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="soma.js"></script>
</html>

JS

var result = document.querySelector("input#result");
var button = document.querySelector("button");
/* function add(n1, n2) { ---> Possui parâmetros
    n1 = document.querySelector("input#n1");
    n2 = document.querySelector("input#n2");
    result.value = parseInt(n1.value) + parseInt(n2.value);
    return result;
} */
function add(){
    var n1 = document.querySelector("input#n1");
    var n2 = document.querySelector("input#n2");
    result.value = parseInt(n1.value) + parseInt(n2.value);
}
button.onclick = function(){
    add();
}
  • It is the same function, but written in different ways, what situation should I use one function with parameters and another not?
  • I tested the function of parameters and return normally, but when I call this function, I do not specify any argument in it, but emits the same result, as it is possible (it is because the parameters are optional?)?
  • Javascript may not be the best tool for this type of question, but if we want to use strong typing, how could it be? If yes, what would be the way?
  • If I put one parseInt in result, he says the return should be number, but if I try to perform any of the functions, it returns nothing, why?

Reference: Wikipedia, Mozilla

2 answers

1


It is the same function, but written in different ways, what situation should I use one function with parameters and another not?

You should use a function with parameters when this function manipulates or changes a result.

Example

function soma(a, b) {
  console.log(a + b);
}

soma(2, 3); // Resultado 5
soma(3, 3); // Resultado 6
soma(6, 4); // Resultado 10

I tested the function of parameters and return normally, but when I call this function, I do not specify any argument in it, but emits the same result, as it is possible (it is because the parameters are optional?)?

The parameters are not optional, in which case both receive Undefined. As you can see in the section below, the console will show Undefined when not informed a value.

function soma(a, b) {
  console.log(`valor de A: ${a}`);
  console.log(`valor de B: ${b}`);
}

soma(); // Undefined
soma(1); // A = 1, B = undefined
soma(1,2) // Ambos tem valor;

Why it issued the same results?

Issued the same result because the parameters n1 and N2 are set inside the function, regardless of the value passed with or without parameter values will be overwritten.

Example

function soma(a, b) {
  a = 1;
  b = 3;
  
  console.log(`Valor de A: ${a}`);
  console.log(`Valor de B: ${b}`);
}

soma();
soma(5, 10);

Javascript may not be the best tool for this type of question, but if we want to use strong typing, how could it be? If yes, what would be the way?

Use Javascript’s 'use Strict' mode. Strict mode is a more rigorous way of interpreting language, which prohibits certain practices that have always been allowed.

If you want in the development environment to avoid these errors, I strongly recommend using typescript to use typing.

If I put a parseint in result, it says that the return should be number, but if I try to perform any of the functions, it returns nothing, why?

Why does your result is an object and not a possible data type to transform into number as a string for example.

0

Whoa, whoa, whoa, whoa.

It is the same function, but written in different ways, what situation should I use one function with parameters and another not? You have 2 functions that do the same task, but the difference is in what you pass in the function. For example, in your add() function, you are simply calling it to perform all the actions within it. In your other function add(n1, N2), you should already enter the values you want to add, example:

function add(n1, n2) {
    result.value = n1 + n2;
    return result;
}

Note that I don’t need to do the whole loop you built in your add(), because the numbers are already being reported in the function parameter, unlike the function without parameter that you need to rescue the data (it’s right the way you did).

I tested the function of parameters and return normally, but when I call this function, I do not specify any argument in it, but emits the same result, as it is possible (it is because the parameters are optional?)? Emits the same result, because you are performing the same treatment in both functions, however, when trying to call the function with parameters without passing the 2 required parameters, you will have an error, because you are not stating the data correctly.

Javascript may not be the best tool for this type of question, but if we want to use strong typing, how could it be? If yes, what would be the way? I believe that this question can be answered and exemplified in the following article, will give you a good idea of the types of typing and examples: http://felipequadros.com/programa%C3%A7%C3%A3o/b%C3%A1sico/beginner/general/theory/2016/06/05/typing-weak-strong-est%C3%A1tica-din%C3%A2mica-e-inferencia-de-tipo/

If I put a parseint in result, it says that the return should be number, but if I try to perform any of the functions, it returns nothing, why? I noticed that in your HTML you are informing the inputs as TEXT type, but if you are going to add, it should be NUMBER, so you do not need to perform the variable conversion, you can leave:

function add(){
    var n1 = document.querySelector("input#n1");
    var n2 = document.querySelector("input#n2");
    result.value = n1.value + n2.value;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.