SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
JavaScript’s variables: scopes, environments, closures
Dr. Axel Rauschmayer
2ality.com
2014-03-30
CodeFest 2014
A few definitions
A few definitions
Scope of a variable
Where is the variable accessible?
function foo() {
var x;
}
foo() is direct scope of x.
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 3 / 32
A few definitions
Static versus dynamic
Adjectives for describing phenomena in programming languages:
Static: pertaining to the source code
⇒ The scope of a variable is static
function f() {
var x = 3;
... // no effect on scope of x
}
⇒ Variables in JavaScript are statically scoped (or lexically scoped)
Dynamic: at runtime
⇒ function calls are dynamic
function g() { }
function f() { g() }
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 4 / 32
A few definitions
var declarations are function-scoped
foo is accessible in all of main():
function main() {
{ // block starts
var foo = 4;
} // block ends
console.log(foo); // 4
}
ECMAScript 6: block-scoped variable declarations via let.
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 5 / 32
A few definitions
Nested scopes
Everything from outer scopes is accessible from inner scopes.
function foo(arg) {
function bar() {
console.log('arg: ' + arg);
}
bar();
}
console.log(foo('hello')); // arg: hello
Outer scope: foo()
Inner scope: bar()
arg is accessible in its direct scope foo() and the inner scope bar().
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 6 / 32
Environments
Environments
Environments: managing variables
Environments:
Data structure for storing variables
Maps from variable names to values
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 8 / 32
Environments
Dimensions of environments
Environments must support:
Fresh variables (local, parameters) per function call (dynamic
dimension).
Nested scopes (static dimension).
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 9 / 32
Environments
Dynamic dimension: calling functions
function fac(n) {
if (n <= 1) {
return 1;
}
return n * fac(n - 1);
}
For each invocation:
Allocate storage for parameters and local variables
Discard afterwards (usually)
Solution: stack of execution contexts (references to environments)
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 10 / 32
Environments
var foo = 'abc';
function fac(n) {
if (n <= 1) {
return 1;
}
return n * fac(n - 1);
}
// YOU ARE HERE
fac(2);
0
…fac
'abc'foo
Lexical environmentsExecution contexts
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 11 / 32
Environments
var foo = 'abc';
function fac(n) {
if (n <= 1) {
return 1;
}
return n * fac(n - 1);
}
fac(2);
1
0
…fac
'abc'foo
2n
Lexical environmentsExecution contexts
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 12 / 32
Environments
var foo = 'abc';
function fac(n) {
if (n <= 1) {
return 1;
}
return n * fac(n - 1);
}
fac(2);
2
1
0
…fac
'abc'foo
1n
Lexical environmentsExecution contexts
2n
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 13 / 32
Environments
Static (lexical) dimension: nested scopes
function f(x) {
var foo;
function g(y, z) {
var bar;
}
}
Environment: field outer points to
“surrounding” environment.
Search environment chain for
variables.
Function: property [[Scope]]
points to environment “in which”
function was created.
Function call: set up outer via
[[Scope]].
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 14 / 32
Environments
function f(x) {
var foo;
function g(y, z) {
var bar;
}
g(7, 1);
}
// YOU ARE HERE
f(2);
0 …f
Lexical environmentsExecution contexts
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 15 / 32
Environments
function f(x) {
var foo;
function g(y, z) {
var bar;
}
g(7, 1);
}
f(2);
1
0 …f
…g
undefinedfoo
2x
outer
Lexical environmentsExecution contexts
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 16 / 32
Environments
function f(x) {
var foo;
function g(y, z) {
var bar;
}
g(7, 1);
}
f(2);
2
1
0 …f
…g
undefinedfoo
2x
outer
Lexical environmentsExecution contexts
undefinedbar
1z
7y
outer
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 17 / 32
Closures
Closures
Closures: Functions Stay Connected to Their Birth Scopes
function createInc(startValue) {
return function (step) {
startValue += step;
return startValue;
};
}
# var inc = createInc(5);
# inc(1)
6
# inc(2)
8
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 19 / 32
Closures
What is a closure?
Closure = function + connection to birth scope
Via internal property [[Scope]] of functions
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 20 / 32
Closures
Example: closures
Step 1
function createInc(startValue) {
return function (step) {
startValue += step;
return startValue;
};
}
var inc = createInc(5);
0
undefinedinc
createInc
Lexical environmentsExecution contexts Functions
[[Scope]]
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 21 / 32
Closures
Step 2
function createInc(startValue) {
return function (step) {
startValue += step;
return startValue;
};
}
var inc = createInc(5);
1
0
undefinedinc
createInc
5startValue
outer
Lexical environmentsExecution contexts Functions
[[Scope]]
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 22 / 32
Closures
Step 3
function createInc(startValue) {
return function (step) {
startValue += step;
return startValue;
};
}
var inc = createInc(5);
0
inc
createInc
5startValue
outer
[[Scope]]
Lexical environmentsExecution contexts Functions
[[Scope]]
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 23 / 32
Closures
Step 4
function createInc(startValue) {
return function (step) {
startValue += step;
return startValue; }; }
var inc = createInc(5);
console.log(inc(1)); // 6
1
0
inc
createInc
5startValue
1step
outer
outer
[[Scope]]
Lexical environmentsExecution contexts Functions
[[Scope]]
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 24 / 32
Closures
Step 5
function createInc(startValue) {
return function (step) {
startValue += step;
return startValue;
};
}
var inc = createInc(5);
console.log(inc(1)); // 6
0
inc
createInc
5startValue
outer
[[Scope]]
Lexical environmentsExecution contexts Functions
[[Scope]]
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 25 / 32
Thank you!
Free online: speakingjs.com
Bonus: inadvertent sharing
Bonus: inadvertent sharing
Wrong: all functions share the same i
function f() {
var result = [];
for (var i=0; i<3; i++) {
var func = function () {
return i;
};
result.push(func);
}
return result;
}
console.log(f()[1]()); // 3
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 28 / 32
Bonus: inadvertent sharing
Right: one environment per function, with snapshot of i
function f() {
var result = [];
for (var i=0; i<3; i++) {
(function () { // step 1: IIFE
var pos = i; // step 2: copy
var func = function () {
return pos;
};
result.push(func);
}());
}
return result;
}
console.log(f()[1]()); // 1
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 29 / 32
Bonus: example
Bonus: example
Example: environments
Step 1
function myFunction(myParam) {
var myVar = 123;
return myFloat;
}
var myFloat = 1.3;
// Step 1
myFunction('abc'); // Step 2
0
1.3myFloat
myFunction
Chain of environments
(lexical)
Stack of execution
contexts (dynamic)
[[Scope]]
function (myParam)
...
}
Functions
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 31 / 32
Bonus: example
Step 2
function myFunction(myParam) {
var myVar = 123;
return myFloat;
}
var myFloat = 1.3;
// Step 1
myFunction('abc'); // Step 2
[[Scope]]
1
0
1.3myFloat
myFunction
myVar 123
'abc'myParam
outer
function (myParam)
...
}
Chain of environments
(lexical)
Stack of execution
contexts (dynamic)
Functions
Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 32 / 32

Weitere ähnliche Inhalte

Was ist angesagt?

Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automation
Positive Hack Days
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
dico_leque
 

Was ist angesagt? (20)

서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Slides
SlidesSlides
Slides
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
C# console programms
C# console programmsC# console programms
C# console programms
 
Templates
TemplatesTemplates
Templates
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 
Stacks
StacksStacks
Stacks
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automation
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
What is Pure Functional Programming, and how it can improve our application t...
What is Pure Functional Programming, and how it can improve our application t...What is Pure Functional Programming, and how it can improve our application t...
What is Pure Functional Programming, and how it can improve our application t...
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Loops in R
Loops in RLoops in R
Loops in R
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
 

Andere mochten auch

Scala: что, как и зачем?
Scala: что, как и зачем?Scala: что, как и зачем?
Scala: что, как и зачем?
Roman Timushev
 
7 кашкута
7 кашкута7 кашкута
7 кашкута
CodeFest
 
CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...
CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...
CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...
CodeFest
 

Andere mochten auch (20)

Лекция Android. Fragments, ActionBar, Drawer
Лекция Android. Fragments, ActionBar, DrawerЛекция Android. Fragments, ActionBar, Drawer
Лекция Android. Fragments, ActionBar, Drawer
 
Иван Величко
Иван ВеличкоИван Величко
Иван Величко
 
Настройка Apache и PHP
Настройка Apache и PHPНастройка Apache и PHP
Настройка Apache и PHP
 
Создание сайта на PHP
Создание сайта на PHPСоздание сайта на PHP
Создание сайта на PHP
 
Scala: что, как и зачем?
Scala: что, как и зачем?Scala: что, как и зачем?
Scala: что, как и зачем?
 
Getting it Booking right
Getting it Booking rightGetting it Booking right
Getting it Booking right
 
Дмитрий Стогов
Дмитрий СтоговДмитрий Стогов
Дмитрий Стогов
 
Денис Иванов
Денис ИвановДенис Иванов
Денис Иванов
 
Антон Турецкий
Антон ТурецкийАнтон Турецкий
Антон Турецкий
 
Внутри Stack Overflow
Внутри Stack OverflowВнутри Stack Overflow
Внутри Stack Overflow
 
Fp intro scala
Fp intro scalaFp intro scala
Fp intro scala
 
Эффективная, вовлеченная команда энтузиастов. А ты готов к этому?
Эффективная, вовлеченная команда энтузиастов. А ты готов к этому?Эффективная, вовлеченная команда энтузиастов. А ты готов к этому?
Эффективная, вовлеченная команда энтузиастов. А ты готов к этому?
 
Мультиплатформенная синхронизация структурированных данных
Мультиплатформенная синхронизация структурированных данныхМультиплатформенная синхронизация структурированных данных
Мультиплатформенная синхронизация структурированных данных
 
Чего стоит сделать стартап
Чего стоит сделать стартапЧего стоит сделать стартап
Чего стоит сделать стартап
 
7 кашкута
7 кашкута7 кашкута
7 кашкута
 
Рост курса валют vs рост числа пользователей. Как banki.ru пережил утроение н...
Рост курса валют vs рост числа пользователей. Как banki.ru пережил утроение н...Рост курса валют vs рост числа пользователей. Как banki.ru пережил утроение н...
Рост курса валют vs рост числа пользователей. Как banki.ru пережил утроение н...
 
Графика средствами PHP
Графика средствами PHPГрафика средствами PHP
Графика средствами PHP
 
CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...
CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...
CodeFest 2014. Christopher Bennage — CQRS Journey: scalable, available, and m...
 
Ставка на iBeacon. Новинки мобильной индустрии в реальной жизни
Ставка на iBeacon. Новинки мобильной индустрии в реальной жизниСтавка на iBeacon. Новинки мобильной индустрии в реальной жизни
Ставка на iBeacon. Новинки мобильной индустрии в реальной жизни
 
Design by Contracts in PHP
Design by Contracts in PHPDesign by Contracts in PHP
Design by Contracts in PHP
 

Ähnlich wie CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environments, closures

Evolution and Examples of Java Features, from Java 1.7 to Java 22
Evolution and Examples of Java Features, from Java 1.7 to Java 22Evolution and Examples of Java Features, from Java 1.7 to Java 22
Evolution and Examples of Java Features, from Java 1.7 to Java 22
Yann-Gaël Guéhéneuc
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesBuilding Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Guido Chari
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 

Ähnlich wie CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environments, closures (20)

Evolution and Examples of Java Features, from Java 1.7 to Java 22
Evolution and Examples of Java Features, from Java 1.7 to Java 22Evolution and Examples of Java Features, from Java 1.7 to Java 22
Evolution and Examples of Java Features, from Java 1.7 to Java 22
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesBuilding Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual Machines
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Java
JavaJava
Java
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 

Mehr von CodeFest

Mehr von CodeFest (20)

Alexander Graebe
Alexander GraebeAlexander Graebe
Alexander Graebe
 
Никита Прокопов
Никита ПрокоповНикита Прокопов
Никита Прокопов
 
Денис Баталов
Денис БаталовДенис Баталов
Денис Баталов
 
Елена Гальцина
Елена ГальцинаЕлена Гальцина
Елена Гальцина
 
Александр Калашников
Александр КалашниковАлександр Калашников
Александр Калашников
 
Ирина Иванова
Ирина ИвановаИрина Иванова
Ирина Иванова
 
Marko Berković
Marko BerkovićMarko Berković
Marko Berković
 
Денис Кортунов
Денис КортуновДенис Кортунов
Денис Кортунов
 
Александр Зимин
Александр ЗиминАлександр Зимин
Александр Зимин
 
Сергей Крапивенский
Сергей КрапивенскийСергей Крапивенский
Сергей Крапивенский
 
Сергей Игнатов
Сергей ИгнатовСергей Игнатов
Сергей Игнатов
 
Николай Крапивный
Николай КрапивныйНиколай Крапивный
Николай Крапивный
 
Alexander Graebe
Alexander GraebeAlexander Graebe
Alexander Graebe
 
Вадим Смирнов
Вадим СмирновВадим Смирнов
Вадим Смирнов
 
Константин Осипов
Константин ОсиповКонстантин Осипов
Константин Осипов
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Максим Пугачев
Максим ПугачевМаксим Пугачев
Максим Пугачев
 
Rene Groeschke
Rene GroeschkeRene Groeschke
Rene Groeschke
 
Иван Бондаренко
Иван БондаренкоИван Бондаренко
Иван Бондаренко
 
Mete Atamel
Mete AtamelMete Atamel
Mete Atamel
 

Kürzlich hochgeladen

在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
ydyuyu
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
nirzagarg
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
nilamkumrai
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Kürzlich hochgeladen (20)

Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 

CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environments, closures

  • 1. JavaScript’s variables: scopes, environments, closures Dr. Axel Rauschmayer 2ality.com 2014-03-30 CodeFest 2014
  • 3. A few definitions Scope of a variable Where is the variable accessible? function foo() { var x; } foo() is direct scope of x. Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 3 / 32
  • 4. A few definitions Static versus dynamic Adjectives for describing phenomena in programming languages: Static: pertaining to the source code ⇒ The scope of a variable is static function f() { var x = 3; ... // no effect on scope of x } ⇒ Variables in JavaScript are statically scoped (or lexically scoped) Dynamic: at runtime ⇒ function calls are dynamic function g() { } function f() { g() } Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 4 / 32
  • 5. A few definitions var declarations are function-scoped foo is accessible in all of main(): function main() { { // block starts var foo = 4; } // block ends console.log(foo); // 4 } ECMAScript 6: block-scoped variable declarations via let. Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 5 / 32
  • 6. A few definitions Nested scopes Everything from outer scopes is accessible from inner scopes. function foo(arg) { function bar() { console.log('arg: ' + arg); } bar(); } console.log(foo('hello')); // arg: hello Outer scope: foo() Inner scope: bar() arg is accessible in its direct scope foo() and the inner scope bar(). Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 6 / 32
  • 8. Environments Environments: managing variables Environments: Data structure for storing variables Maps from variable names to values Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 8 / 32
  • 9. Environments Dimensions of environments Environments must support: Fresh variables (local, parameters) per function call (dynamic dimension). Nested scopes (static dimension). Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 9 / 32
  • 10. Environments Dynamic dimension: calling functions function fac(n) { if (n <= 1) { return 1; } return n * fac(n - 1); } For each invocation: Allocate storage for parameters and local variables Discard afterwards (usually) Solution: stack of execution contexts (references to environments) Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 10 / 32
  • 11. Environments var foo = 'abc'; function fac(n) { if (n <= 1) { return 1; } return n * fac(n - 1); } // YOU ARE HERE fac(2); 0 …fac 'abc'foo Lexical environmentsExecution contexts Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 11 / 32
  • 12. Environments var foo = 'abc'; function fac(n) { if (n <= 1) { return 1; } return n * fac(n - 1); } fac(2); 1 0 …fac 'abc'foo 2n Lexical environmentsExecution contexts Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 12 / 32
  • 13. Environments var foo = 'abc'; function fac(n) { if (n <= 1) { return 1; } return n * fac(n - 1); } fac(2); 2 1 0 …fac 'abc'foo 1n Lexical environmentsExecution contexts 2n Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 13 / 32
  • 14. Environments Static (lexical) dimension: nested scopes function f(x) { var foo; function g(y, z) { var bar; } } Environment: field outer points to “surrounding” environment. Search environment chain for variables. Function: property [[Scope]] points to environment “in which” function was created. Function call: set up outer via [[Scope]]. Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 14 / 32
  • 15. Environments function f(x) { var foo; function g(y, z) { var bar; } g(7, 1); } // YOU ARE HERE f(2); 0 …f Lexical environmentsExecution contexts Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 15 / 32
  • 16. Environments function f(x) { var foo; function g(y, z) { var bar; } g(7, 1); } f(2); 1 0 …f …g undefinedfoo 2x outer Lexical environmentsExecution contexts Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 16 / 32
  • 17. Environments function f(x) { var foo; function g(y, z) { var bar; } g(7, 1); } f(2); 2 1 0 …f …g undefinedfoo 2x outer Lexical environmentsExecution contexts undefinedbar 1z 7y outer Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 17 / 32
  • 19. Closures Closures: Functions Stay Connected to Their Birth Scopes function createInc(startValue) { return function (step) { startValue += step; return startValue; }; } # var inc = createInc(5); # inc(1) 6 # inc(2) 8 Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 19 / 32
  • 20. Closures What is a closure? Closure = function + connection to birth scope Via internal property [[Scope]] of functions Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 20 / 32
  • 21. Closures Example: closures Step 1 function createInc(startValue) { return function (step) { startValue += step; return startValue; }; } var inc = createInc(5); 0 undefinedinc createInc Lexical environmentsExecution contexts Functions [[Scope]] Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 21 / 32
  • 22. Closures Step 2 function createInc(startValue) { return function (step) { startValue += step; return startValue; }; } var inc = createInc(5); 1 0 undefinedinc createInc 5startValue outer Lexical environmentsExecution contexts Functions [[Scope]] Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 22 / 32
  • 23. Closures Step 3 function createInc(startValue) { return function (step) { startValue += step; return startValue; }; } var inc = createInc(5); 0 inc createInc 5startValue outer [[Scope]] Lexical environmentsExecution contexts Functions [[Scope]] Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 23 / 32
  • 24. Closures Step 4 function createInc(startValue) { return function (step) { startValue += step; return startValue; }; } var inc = createInc(5); console.log(inc(1)); // 6 1 0 inc createInc 5startValue 1step outer outer [[Scope]] Lexical environmentsExecution contexts Functions [[Scope]] Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 24 / 32
  • 25. Closures Step 5 function createInc(startValue) { return function (step) { startValue += step; return startValue; }; } var inc = createInc(5); console.log(inc(1)); // 6 0 inc createInc 5startValue outer [[Scope]] Lexical environmentsExecution contexts Functions [[Scope]] Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 25 / 32
  • 26. Thank you! Free online: speakingjs.com
  • 28. Bonus: inadvertent sharing Wrong: all functions share the same i function f() { var result = []; for (var i=0; i<3; i++) { var func = function () { return i; }; result.push(func); } return result; } console.log(f()[1]()); // 3 Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 28 / 32
  • 29. Bonus: inadvertent sharing Right: one environment per function, with snapshot of i function f() { var result = []; for (var i=0; i<3; i++) { (function () { // step 1: IIFE var pos = i; // step 2: copy var func = function () { return pos; }; result.push(func); }()); } return result; } console.log(f()[1]()); // 1 Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 29 / 32
  • 31. Bonus: example Example: environments Step 1 function myFunction(myParam) { var myVar = 123; return myFloat; } var myFloat = 1.3; // Step 1 myFunction('abc'); // Step 2 0 1.3myFloat myFunction Chain of environments (lexical) Stack of execution contexts (dynamic) [[Scope]] function (myParam) ... } Functions Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 31 / 32
  • 32. Bonus: example Step 2 function myFunction(myParam) { var myVar = 123; return myFloat; } var myFloat = 1.3; // Step 1 myFunction('abc'); // Step 2 [[Scope]] 1 0 1.3myFloat myFunction myVar 123 'abc'myParam outer function (myParam) ... } Chain of environments (lexical) Stack of execution contexts (dynamic) Functions Dr. Axel Rauschmayer (2ality.com) JavaScript’s variables 2014-03-30 32 / 32