Skip to content

Instantly share code, notes, and snippets.

@jsteenkamp

jsteenkamp/block-scope.js

Last active Oct 28, 2015
Embed
What would you like to do?
JavaScript and DOM question
'use strict';
// Solution using ES6 block scope
var list = document.createElement('UL');
for (var i = 1; i <= 5; i++) {
var item = document.createElement('LI');
item.appendChild(document.createTextNode('Item ' + i));
// ES6 block scope (var will not work)
let j = i;
item.onclick = function (ev) {
console.log('Item ' + j + ' is clicked.');
};
list.appendChild(item);
}
document.querySelector('body').appendChild(list);
'use strict';
// Solution using closure (callback)
var list = document.createElement('UL');
for (var i = 1; i <= 5; i++) {
// closure retains reference to creation environment and i
function createItem(i) {
var item = document.createElement('LI');
item.appendChild(document.createTextNode('Item ' + i));
item.onclick = function (ev) {
console.log('Item ' + i + ' is clicked.');
};
return item;
};
list.appendChild(createItem(i));
}
document.querySelector('body').appendChild(list);
'use strict';
// Solution using event delegation
var list = document.createElement('UL');
for (var i = 1; i <= 5; i++) {
var item = document.createElement('LI');
item.appendChild(document.createTextNode('Item ' + i));
// use data attribute to store value
item.setAttribute('data-item', i);
list.appendChild(item);
}
// get value from delegated event target element data attribute
list.onclick = function (ev) {
var i = ev.target.getAttribute('data-item');
console.log('Item ' + i + ' is clicked.');
};
document.querySelector('body').appendChild(list);

JavaScript and DOM

This question tests Web API (DOM) and JavaScript understanding.

You can provide the example answer below as a starting point or ask the candidate to start from scratch.

Three possible solutions are:

  • Closures
  • Event delegation
  • Block scope (ES6 requires additional tooling. Why?)

You can achieve block scope in ES5 using IIFE however I don't think it's a good option compared to others.

What are the pros/cons of each solution? Which do you think is the best?

Can you think of other solutions?

Question

Using JavaScript create an unordered list with 5 items.

When an item is clicked get the number of the item in the list and display it.

Answer

This answer does not work. Why? Can you fix it?

var list = document.createElement('UL');

for (var i = 1; i <= 5; i++) {

  var item = document.createElement('LI');
  item.appendChild(document.createTextNode('Item ' + i));

  var j = i;

  item.onclick = function (ev) {
    console.log('Item ' + j + ' is clicked.');
  };

  list.appendChild(item);
}

document.querySelector('body').appendChild(list);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment