JSFiddle - React, Tailwind, and code Playground

by chriswt

HTML

<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

<ul class="list2">
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
  <li>Text</li>
</ul>

<form name="myForm" action="" novalidate>
  <label>
        <input name="username" placeholder="Name" type="text" required>
    </label>
  <label>
        <input name="email" placeholder="Email" type="email" required>
    </label>
  <button>Submit</button>
</form>

JavaScript

/***********************************************\
 * Mozio JavaScript challenge
 * Browser support is irrelevant here, but any comments on specific
 * methods you use is a plus to show deeper understanding of the language
\***********************************************/

/**
 * Task 1: Write a function that repeats the String
 * with the following output:
 * 'Mozio'.repeatString(3); // 'MozioMozioMozio';
 */

// For information, String.prototype.repeat was added to ECMAScript 2015.
String.prototype.repeatString = function(count) {
  var res = ''
  for (var i = 0; i < count; i++) {
    res += this;
  }

  return res;
}


console.log('Mozio'.repeatString(3));

/**
 * Task 2: Could you find a way to optimize the following code?
 */

function logContent(event) {
  if (event.target.matches('li')) {
    console.log(event.target.innerHTML);
  }
}

// Add the event listener to the parent instead of adding it to each element, 
var list = document.querySelector(".list");
list.addEventListener('click', logContent, false);

/**
 * Task 3: Inspect the output in the console from clicking an
 * item from ".list2", each index is the same
 * Explain why, and also fix the problem to log the correct index
 */

/**
 * Answer: The i variable is modified outside the event listener function.
 * A solution would be to create a "closure", a wrapper function that gives
 * the inner function a private environment that only it can access. 
 * This way, we would have a reference to the correct index value.
 * Alternatively, we can calculate the index in a different way:
 */

var list2 = document.querySelector(".list2");
list2.addEventListener('click', function(event) {
  var el = event.target;
  const index = Array.from(el.parentElement.children).indexOf(el)
  console.log('My index:', index);
}, false);

/**
 * Task 4: Explain why the logs happen in the following order:
 * one, three, two
 */
(function() {
  console.log('one');
  setTimeout(function() {
    console.log('two');
  }, 0);
 ...