Is there more than one way to use "if"?

Asked

Viewed 387 times

5

const sequence = {
    _id: 1,
    get id() { return this._id++ }
}

const produtos = {}

function salvarProduto(produto) {
    if (!produto.id) produto.id = sequence.id
    produtos[produto.id] = produto
    return produto
}

My doubt is in if of function salvarProduto(). I thought every function was created with this pattern if (expresao) {}m but in this example has no keys, why?

  • When if (not only if) has only one instruction it can be used without keys.

  • 1

    The keys {} are to denote a block of code. If there are multiple instructions on multiple lines they must be wrapped between keys. If there is only one instruction or more in a single row then you can do this variation if(condicao) instrucao1; instrucao2;

  • @Geeksilva This information is not correct: if(condicao) instrucao1; instrucao2; will always perform the instrucao2. Only the instrucao1 is covered by if.

3 answers

8


What is the if

The first thing you should understand is that the if is not a function, is a language command (this can be seen more in What are statements and operators? and What is the difference between functions and procedures?, although the ideal is a question that asks the difference between statement and expression, but has not).

There is a confusion that some people make because of the mandatory parentheses of the conditional expression. They are not the same parentheses that are used in functions, because it is recommended to put next to the identifier in a function funcao() and separated into a statement language standard (if (condicao)), becomes more readable.

Another common mistake is that people think there should be a comparison there within the condition. Actually there fits any possible expression of the language, provided that the final result is a boolean value for the command if can decide whether to execute a command below. Example Assign an expression to a variable.

Keys

The simplest way is to execute only one command so the normal is to have no keys.

The whole command structure has three parts. You have the word that defines the command (if), the conditional expression (what is in parentheses) and then the command that must be executed conditionally.

Technically has two statements there, but the if is a statement incomplete and needs another to perform properly, so it never ends with ;.

It happens that in many situations it is necessary to execute several commands together depending on condition. To establish that several commands together are one thing only you use a syntax of command block. These syntax are keys. The merging of several statements become one only by the keys. Of course there will continue to be several, but for the if only the block counts.

Note that the block has nothing to do with the if, by chance the block can be used there, but it is not something connected to the if. When you put the keys all those commands behave as if it were one thing and it is this thing only that will be executed if the condition is true.

Obviously keys can be used to create a block of just one statement (command), some people do so, others do not. It is a matter of taste in this case. It’s just not like when it has multiple lines belonging to the same block. See the difference:

if (false)
    console.log(1);
    console.log(2);

Note that only the first command after the if It belongs to him the second no, he is isolated. It is a bad way to write because indentation tricks, but it has no relevance in JS, only keys can create a block.

Now see with keys both belong to the if:

if (false) {
    console.log(1);
    console.log(2);
}

There’s even a phenomenon called dangling Else about it. What do you think happens here?

if (false)
    if (true)
        console.log(1);
else
    console.log(2);

Sounds weird, right? The else belongs to the if closer to him and not apparently. With the keys there is no danger:

if (false) {
    if (true) {
        console.log(1);
    } else {
        console.log(2);
    }
}

But if it indents right, it’s still legible:

if (false)
    if (true)
        console.log(1);
    else
        console.log(2);

That’s why I value indentation. Confusion only occurs in misspelled code.

Command block

Keys can be used in various situations, such as after the do, while, for, the function, or even with nothing. Yes, the block can come alone only to create scope for variables. Rare to be useful in Javascript (even less if not used let), but you could use it. What you hope will happen?

let x = 1;
{
   let x = 2;
   console.log(x);
}
console.log(x);

I put in the Github for future reference.

Style

I have adopted the style of when it is a line I do not use keys, but the command must come in the same line as the if, if it’s too much and you want to put in the other line, then you have to put in keys. And if you have a clear block there will always be keys.

I see some advantage in using the keys always even for a line, I used a lot, but experience showed me that it was not necessary, I had no problems. What I find strange is to put a single line and the keys all stacked on the same line, if you will use keys then make it look like a block, even if there is only one line in that block.

You can never put more than one statement as a single thing on the same line. Each ; is a statement, so I guess the ; should be mandatory, see about this.

Completion

In some ways programming is like riding Lego. You have several pieces that can fit together, use creativity to put the pieces together so that they fit. Some people have trouble programming because they don’t understand it, and they just follow cake recipes, they just copy what they saw assembled by other people. Understand what each piece of language is and you can create better toys.

  • 1

    Great placement on keys indicate command blocks! After all, if only executes the next instruction anyway (that with the keys the "next statement" is a block of instructions)! Very valid also the issue of indentation that the staff often does not understand how important it is!

  • @Guilhermec.Dalleprane cool see who appreciates the correct things, the detailing.

6

Yes. In Javascript, when you don’t put keys, only the next instruction is executed. Keys are only needed when you want to execute more than one if-conditioned instruction.

The instruction:

    let a = 1
    if (a == 1) 
        alert("É verdadeiro!")
    else
        alert("É falso!")

Is the same as:

let a = 1
if (a == 1) {
    alert("É verdadeiro!")
} else {
    alert("É falso!")
}

But... the instruction:

let a = 1
if (a == 1) {
    alert("Executa quando a é igual a 1")
    alert("Executa novamente quando a é igual a 1")
}
It’s not the same as:
let a = 1
if (a == 2)
    alert("Executa apenas se a é igual a 1")

alert("Executará independendo do valor de a") 
  

In the above case, the second Alert will always be executed (also note that the correct identation of the second Alert is following the identation of the if and not the instruction that is within it. Another way to write would be like in the question example, putting the statement right in front of the if, so:

let a = 1
if (a == 2) alert("Executa apenas se a é igual a 1")
   
alert("Executará independendo do valor de a") 

4

The instruction if is usually followed by keys. However, you can omit them if you want to execute only one expression if the condition is evaluated as true:

if (true) console.log(1); // 1
if (false) console.log(2);

Note that we end with a semicolon. If we use several statements in the same line, separated by a semicolon, only the first would be in the performance of the if, see:

if (false) console.log(1); console.log(2); console.log(3);

That’s why I always prefer to use the keys, they make clearer what is being done. The above code is equivalent to this:

if (false) {
  console.log(1);
}

console.log(2);
console.log(3);

To learn more, see this document.

Browser other questions tagged

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