// глобальная переменная, которую мы попытаемся дальше получить
var bar = 42;
// Мозг предполагает, что до объявления bar в теле функциии глобальный bar будет доступен
function simple_define() {
alert(bar);
var bar = 10;
alert(bar);
}
// Но это не так. Функция выше на самом деле выглядит вот так
function real_define() {
var bar;
alert(bar);
bar = 10;
alert(bar);
}
// А что же с условиями? Разве они не создают локальные области видимости?
function define_inside_if() {
if (true) {
var bar = -10;
}
alert(bar);
}
// Ну а циклы?
function define_inside_while() {
do {
var bar = 10;
} while (false);
alert(bar);
}
// И переменные из for?
function define_inside_for() {
for (var bar = 0; bar < 10; bar++);
alert(bar);
}
/*
* Да. Это особенность js - компилятор собирает все объявления переменных текущей области видимости
* и выделяет под них все требуемые ресурсы сразу при входе в функцию.
*/
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.