title: `select` vs `if then else` in wasm
body: <p>What is the difference between <code>if</code> and <code>select</code> in <a href="https://webassembly.org/" rel="noreferrer">wasm</a> and what is the best application of these commands?</p>
  
  <p>Example in <a href="https://webassembly.github.io/wabt/demo/wat2wasm/" rel="noreferrer">wat2wasm</a>:</p>
  
  <p>WAT code:</p>
  
  <pre class="lang-wasm prettyprint-override"><code>(module
    (func (export "Select") (param i32) (result i32)
      (select (i32.const 3)
              (i32.const 5)
              (local.get 0) ))
  
    (func (export "If") (param i32) (result i32)
      (if (result i32) (local.get 0)
          (then (i32.const  7))
          (else (i32.const 11)) )) )
  </code></pre>
  
  <p>JS code:</p>
  
  <pre class="lang-js prettyprint-override"><code>const wasmInstance = new WebAssembly.Instance(wasmModule, {});
  const { Select, If } = wasmInstance.exports;
  console.log(Select(1)); // =&gt;  3
  console.log(Select(0)); // =&gt;  5
  console.log(If(1));     // =&gt;  7
  console.log(If(0));     // =&gt; 11
  </code></pre>
  
  <p>According to the docs:</p>
  
  <p>The <code>select</code> operator selects one of its first two operands based on whether its third operand is zero or not.</p>
  
  <p>The <code>block</code>, <code>loop</code> and <code>if</code> instructions are structured instructions. They bracket nested sequences of instructions, called blocks, terminated with, or separated by, end or else pseudo-instructions. As the grammar prescribes, they must be well-nested. A structured instruction can produce a value as described by the annotated result type.</p>
  
  <p>however, the <code>select</code> operator may contain <code>block</code> and to execute a number of instructions.</p>
  
  <pre class="lang-js prettyprint-override"><code>(select (i32.const 3)
          (block (result i32) 
                 (i32.const 5) )
          (local.get 0) )
  </code></pre>