Skip to content

Instantly share code, notes, and snippets.

var i1 = 0;
while (i1 < 3) {
let i = i1; // 'i' is a block scoped variable,
// each code block have unique copy of it
setTimeout(() => { // timeout callback
console.log(i, i1);
}, i * 1000);
var i = 0;
while (i < 3) {
setTimeout(() => { // timeout callback
console.log(i);
}, i * 1000);
i++;
}
var i; // 'i' was declared with functional scope,
// so its declaration moved to the top of the file
for (i = 0; i < 3; i++) {
setTimeout(() => { // timeout callback
console.log(i);
}, i * 1000);
}
{ // start of the block scope
// TODO: try uncomment
// console.log(a);
// hoisting works differently for blocks scope, and it will throw an error:
// 'ReferenceError: Cannot access a before initialization'
let a = 1; // 'a' defined and we can start to use it
//
console.log(a);
// file scope
var a; // declaration of 'a' moved on top of the file and split from assignment
console.log(a); // so here 'a' is undefined, but declared,
// so it does not throw an error
a = 1; // now 'a' is assigned to 1
console.log(a);
function f1() { // f1 scope
// file scope
console.log(a); // you may be surprised, but this works and logs undefined
// this is because of the hoisting of definitions
// on top of the nearest function
var a = 1;
console.log(a);
function f1() { // f1 scope
console.log(a); // this is ok -- functions have access to parent scope
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
<?php
// somewhere in the module code
public function onBootstrap(EventInterface $event)
{
/** @var \Zend\Mvc\MvcEvent $event */
$application = $event->getApplication();
$application->getEventManager()->attach('dispatch', function(MvcEvent $event) use ($application) {
$factory = new \Zend\InputFilter\Factory();
$i = $factory->createInputFilter(array(
'password' => array(
'name' => 'password',
'required' => true,
'validators' => array(
array(
'name' => 'not_empty',
),
array(