From 6fce01af98c9b22cfd0652a3da0ae60ae4d3f318 Mon Sep 17 00:00:00 2001 From: "shigeru.nakajima" Date: Mon, 30 Nov 2026 20:31:15 +0900 Subject: [PATCH] Teach block scope with one if statement --- problems/scope/problem.md | 72 ++++-------------------------- problems/scope/problem_es.md | 63 ++++----------------------- problems/scope/problem_fr.md | 71 ++++-------------------------- problems/scope/problem_it.md | 69 ++++------------------------- problems/scope/problem_ja.md | 70 ++++------------------------- problems/scope/problem_ko.md | 69 ++++------------------------- problems/scope/problem_nb-no.md | 68 ++++------------------------- problems/scope/problem_nl.md | 71 ++++-------------------------- problems/scope/problem_pt-br.md | 70 ++++------------------------- problems/scope/problem_ru.md | 75 ++++---------------------------- problems/scope/problem_uk.md | 68 ++++------------------------- problems/scope/problem_zh-cn.md | 68 ++++------------------------- problems/scope/problem_zh-tw.md | 68 ++++------------------------- problems/scope/solution.md | 11 ++++- problems/scope/solution_es.md | 9 +++- problems/scope/solution_fr.md | 9 +++- problems/scope/solution_it.md | 11 ++++- problems/scope/solution_ja.md | 9 +++- problems/scope/solution_ko.md | 9 +++- problems/scope/solution_nb-no.md | 9 +++- problems/scope/solution_nl.md | 9 +++- problems/scope/solution_pt-br.md | 11 ++++- problems/scope/solution_ru.md | 9 +++- problems/scope/solution_uk.md | 9 +++- problems/scope/solution_zh-cn.md | 9 +++- problems/scope/solution_zh-tw.md | 9 +++- solutions/scope/index.js | 23 +++------- 27 files changed, 217 insertions(+), 831 deletions(-) diff --git a/problems/scope/problem.md b/problems/scope/problem.md index f6303e98..3e31b530 100644 --- a/problems/scope/problem.md +++ b/problems/scope/problem.md @@ -1,72 +1,16 @@ -`Scope` is the set of variables, objects, and functions you have access to. +Scope determines which variables you can use at a given point in your code. The braces around the body of an `if` statement form a block. -JavaScript has two scopes: `global` and `local`. A variable that is declared outside a function definition is a `global` variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is `local`. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function. - -Functions defined inside other functions, known as nested functions, have access to their parent function's scope. - -Pay attention to the comments in the code below: +Copy this code into `scope.js`. ```js -const a = 4 // a is a global variable, it can be accessed by the functions below - -function foo () { - const b = a * 3 // b cannot be accessed outside foo function, but can be accessed by functions - // defined inside foo - function bar (c) { - const b = 2 // another `b` variable is created inside bar function scope - // the changes to this new `b` variable don't affect the old `b` variable - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Print fruit here. } -foo() // 4, 2, 48 +// Print fruit here. ``` - -IIFE, Immediately Invoked Function Expression, is a common pattern for creating local scopes. - -Example: -```js -(function () { // the function expression is surrounded by parentheses - // variables defined here - // can't be accessed outside -})() // the function is immediately invoked -``` -## The challenge: - -Create a file named `scope.js`. - -In that file, copy the following code: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8; - })() - })() - })() -})() -``` - -Use your knowledge of the variables' `scope` and place the following code inside one of the functions in `scope.js` -so the output is `a: 1, b: 8, c: 6` -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Check to see if your program is correct by running this command: - -```bash -javascripting verify scope.js -``` +Replace each comment with `console.log(fruit)`. Before running the code, predict what each line will print. Run `node scope.js` to check your prediction, then run `javascripting verify scope.js`. diff --git a/problems/scope/problem_es.md b/problems/scope/problem_es.md index a380f778..48237c48 100644 --- a/problems/scope/problem_es.md +++ b/problems/scope/problem_es.md @@ -1,63 +1,16 @@ -El `scope` o ámbito es el conjunto de variables, objetos y funciones a las que tienes acceso. +El ámbito determina qué variables puedes usar en cada punto del código. Las llaves que rodean el cuerpo de un `if` forman un bloque. -JavaScript tiene dos ámbitos: `global` y `local`. Una variable que es declarada fuera de la definición de una función es una variable `global`, y su valor es accesible y modificable a través de tu programa. Una variable que es declarada dentro de la definición de una función es una variable `local`. Se crea y se destruye cada vez que se ejecuta la función, y no se puede acceder a su valor ni modificarlo por ningún código fuera de la misma. - -Las funciones definidas dentro de otras funciones, conocidas como funciones anidadas, tienen acceso al ámbito de su función padre. - -Presta atención a los comentarios en el siguiente código: +Copia este código en `scope.js`. ```js -const a = 4 // es una variable global, puede ser accedida por las siguientes funciones +const fruit = 'apple' -function foo () { - const b = a * 3 // b no puede ser accedida por fuera de la función foo, pero puede ser accedida - // por las funciones definidas dentro de foo - function bar (c) { - const b = 2 // otra variable `b` es creada dentro del ámbito de la función bar - // los cambios a esta nueva `b` no afectan a la vieja variable `b` - console.log(a, b, c) - } - - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Muestra fruit aquí. } -foo() // 4, 2, 48 -``` -IIFE, Immediately Invoked Function Expression( Expresión de Función Invocada Inmediatamente ), es un patrón común para crear ámbitos locales. -Por ejemplo: -```js -(function () { // La expresión de la función está entre paréntesis - // las variables definidas aquí - // no pueden ser accedidas por fuera -})() // la función es inmediatamente invocada +// Muestra fruit aquí. ``` -## El ejercicio: - -Crea un archivo llamado `scope.js`. - -En ese archivo, copia el siguiente código: -```js -const a = 1; const b = 2; const c = 3; -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() -``` - -Usa tu conocimiento sobre el ámbito de las variables y ubica el siguiente código dentro de alguna de las funciones -en `scope.js` para que la salida sea `a: 1, b: 8, c: 6` -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` +Sustituye cada comentario por `console.log(fruit)`. Antes de ejecutar el código, predice qué mostrará cada línea. Compruébalo con `node scope.js` y verifica tu solución con `javascripting verify scope.js`. diff --git a/problems/scope/problem_fr.md b/problems/scope/problem_fr.md index e6e0f298..4f54d32e 100644 --- a/problems/scope/problem_fr.md +++ b/problems/scope/problem_fr.md @@ -1,71 +1,16 @@ -Le `scope` est l'ensemble de variables, d'objets et de fonctions auxquels vous avez accès. +La portée détermine quelles variables sont accessibles à un endroit du code. Les accolades qui entourent le corps d’un `if` forment un bloc. -Le JavaScript a deux scopes : le scope `global` et le scope `local`. Une variable qui est déclarée hors d'une fonction est une variable `globale` et sa valeur est accessible et modifiable à travers tout le programme. Une variable qui est déclarée dans une fonction est `locale`. Elle est créée et détruite à chaque fois que la fonction est exécutée, et n'est pas accessible en dehors de cette fonction. - -Les fonctions définies à l'intérieur d'autres fonctions, aussi connues en tant que fonctions imbriquées ( _nested_ ), ont accès au scope de leur fonction parent. - -Soyez attentif aux commentaires dans le code suivant : +Copiez ce code dans `scope.js`. ```js -const a = 4 // a est une variable globale, elle est accessible dans les fonctions ci-dessous - -function foo () { - const b = a * 3 // b n'est pas accessible hors de la fonction foo mais l'est - // dans les fonctions déclarées à l'intérieur de foo +const fruit = 'apple' - function bar (c) { - const b = 2 // une autre variable `b` est créée à l'intérieur du scope de la fonction - // les changements apportés à cette nouvelle variable `b` n'ont pas d'effet sur - // l'ancienne variable `b` - console.log(a, b, c) - } - - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Affichez fruit ici. } -foo() // 4, 2, 48 +// Affichez fruit ici. ``` -IIFE, Immediately Invoked Function Expression, est un schéma commun pour créer des scopes locaux : - -```js -(function () { // l'expression `function` est entourée par des parenthèses - // les variables définies ici - // ne sont pas accessibles en dehors -})() // la fonction est appelée immédiatement -``` -## Le défi : - -Créez un fichier nommé `scope.js`. - -Dans ce fichier, copiez le code suivant : -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() -``` - -Utilisez vos connaissances des `scopes` de variables et placez le code suivant à l'intérieur d'une fonction de `scope.js` afin d'obtenir la sortie `a: 1, b: 8, c: 6` -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Vérifiez si votre programme est correct en exécutant la commande : - -```bash -javascripting verify scope.js -``` +Remplacez chaque commentaire par `console.log(fruit)`. Avant de lancer le programme, essayez de prévoir ce que chaque ligne affichera. Vérifiez votre prédiction avec `node scope.js`, puis votre solution avec `javascripting verify scope.js`. diff --git a/problems/scope/problem_it.md b/problems/scope/problem_it.md index 17c8c103..de60f75b 100644 --- a/problems/scope/problem_it.md +++ b/problems/scope/problem_it.md @@ -1,69 +1,16 @@ -Lo `scope` o ambito è l'insieme di variabili, oggetti e funzioni a cui hai accesso. +L’ambito determina quali variabili puoi usare in un dato punto del codice. Le parentesi graffe che racchiudono il corpo di un `if` formano un blocco. -JavaScript possiede due ambiti: `globale` e `locale`. Una variabile dichiarata fuori da qualsiasi definizione di funzione è una variabile `globale`, e il suo valore è accessibile e modificabile all'interno dell'intero programma. Una variabile dichiarata dentro una definizione di funzione è `locale`. Viene creata e distrutta ogni volta che la funzione viene eseguita, e non può essere acceduta da codice esterno alla funzione. - -Le funzioni definite all'interno di altre funzioni, note come funzioni annidate, hanno accesso all'ambito della propria funzione genitrice. - -Presta attenzione ai commenti nel codice seguente: +Copia questo codice in `scope.js`. ```js -const a = 4 // a è una variabile globale, può essere acceduta dalle funzioni seguenti - -function foo () { - const b = a * 3 // b non può essere acceduta fuori dalla funzione foo, ma può essere acceduta dalle funzioni - // definite all'interno di foo - function bar (c) { - const b = 2 // un'altra variabile `b` è creata all'interno dell'ambito della funzione bar - // i cambiamenti a questa nuova variabile `b` non hanno effetto sulla variabile `b` precedente - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Stampa fruit qui. } -foo() // 4, 2, 48 -``` -IIFE, _Immediately Invoked Function Expression_ ovvero espressione di funzione invocata immediatamente, è un pattern comune per creare ambiti locali -esempio: -```js -(function () { // l'espressione di funzione è circondata da parentesi - // le variabili definite qui - // non possono essere accedute dall'esterno -})() // la funzione è invocata immediatamente -``` -## La sfida: - -Crea un file dal nome `scope.js`. - -In questo file, copia il codice seguente: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// Stampa fruit qui. ``` -Usa la tua comprensione dell'`ambito` delle variabili e posiziona il codice seguente dentro una delle funzioni in `scope.js` -in maniera tale che il risultato sia `a: 1, b: 8,c: 6` -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Verifica che il tuo programma sia corretto eseguendo questo comando: - -```bash -javascripting verify scope.js -``` +Sostituisci ogni commento con `console.log(fruit)`. Prima di eseguire il codice, prova a prevedere cosa stamperà ciascuna riga. Controlla con `node scope.js`, poi verifica la soluzione con `javascripting verify scope.js`. diff --git a/problems/scope/problem_ja.md b/problems/scope/problem_ja.md index d3523c53..8ee778b9 100644 --- a/problems/scope/problem_ja.md +++ b/problems/scope/problem_ja.md @@ -1,70 +1,16 @@ -「スコープ」は参照できる変数・オブジェクト・関数の集合です。 +スコープとは、コードのある場所でどの変数を参照できるかを表すものです。`if` の処理を囲む波括弧 `{` と `}` の部分をブロックと呼びます。 -JavaScriptには、二つのスコープがあります。グローバルとローカルです。 -関数定義の外側で定義した変数はグローバルスコープです。プログラムのどこからでも参照して変更することができます。 -関数定義の内側で定義した変数はローカルスコープです。関数が実行されるときに作られ、関数が終了すると破棄されます。 -関数外のプログラムからは参照できません。 - -他の関数の中で定義した関数を「ネストした関数」と呼びます。「ネストした関数」からは親関数のスコープを参照できます。 - -次のソースコードのコメントを読んでください... +次のコードを `scope.js` にコピーしてください。 ```js -const a = 4 // a はグローバル変数です。下の全ての関数から参照できます。 - -function foo () { - const b = a * 3 // b は foo 関数の外からは参照できません。 foo 関数の中で定義した関数 bar からは参照できます。 +const fruit = 'apple' - function bar (c) { - const b = 2 // bar 関数の中でもう一つ b 変数を定義します - // 新しい b を変更しても、元の b 変数は変わりません。 - console.log(a, b, c) - } - - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // ここで fruit を表示してください。 } -foo() // 4, 2, 48 -``` - -即時実行関数式 (Immediately Invoked Function Expression : IIFE) という共通パターンで、ローカルスコープを作れます。 -例えば... - -```js -(function () { // 関数式をカッコで括ります - // 変数はここで定義します - // 関数の外からは参照できません -})() // 関数を即座に実行します -``` - -## やってみよう - -`scope.js`ファイルを作りましょう。 -ファイルの中に、次のソースコードをコピーしましょう... - -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// ここで fruit を表示してください。 ``` -変数のスコープを活用しましょう。次のコードを関数の中に配置してください。`scope.js` の中の関数です。 -そして、目指す出力は `a: 1, b: 8,c: 6` です。 - -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` +2つのコメントをそれぞれ `console.log(fruit)` に置き換えてください。実行する前に、1行目と2行目に何が表示されるか予想しましょう。`node scope.js` で予想を確かめてから、`javascripting verify scope.js` で採点できます。 diff --git a/problems/scope/problem_ko.md b/problems/scope/problem_ko.md index a53e2bdc..fe366b44 100644 --- a/problems/scope/problem_ko.md +++ b/problems/scope/problem_ko.md @@ -1,69 +1,16 @@ +스코프는 코드의 특정 위치에서 어떤 변수를 사용할 수 있는지를 결정합니다. `if` 문의 본문을 감싸는 중괄호는 블록을 만듭니다. -`스코프`는 접근할 수 있는 변수, 객체, 함수의 집합입니다. - -JavaScript에는 `전역`과 `지역` 두 개의 스코프가 있습니다. 함수 선언 밖에 선언된 변수는 `전역` 변수이고, 그 값은 프로그램 전체에서 접근하고 수정할 수 있습니다. 함수 선언 안에 선언된 변수는 `지역` 변수입니다. 지역 변수는 함수가 실행 될 때마다 만들어지고 파괴되고, 함수 밖의 코드에서 접근할 수 없습니다. - -다른 함수 안에 선언된 함수(중첩 함수)는 부모 함수의 스코프에 접근 할 수 있습니다. - -아래 코드의 주석을 잘 읽어보세요. +다음 코드를 `scope.js`에 복사하세요. ```js -const a = 4 // 전연 변수 아래에 있는 함수에서 접근 가능 - -function foo () { - const b = a * 3 // b는 foo 함수 밖에서 접근할 수 없지만, foo 함수 안에서 - - function bar (c) { - const b = 2 // bar 함수 스코프 안에서 생성한 다른 `b` 변수 - // 새로 만든 `b` 변수를 변경해도 오래된 `b` 변수에는 영향이 없음 - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // 여기서 fruit를 출력하세요. } -foo() // 4, 2, 48 -``` -즉시 실행하는 함수식(IIFE, Immediately Invoked Function Expression)은 지역 스코프를 만드는 일반적인 패턴입니다. -예제: -```js -(function () { // 함수식은 괄호로 둘러 쌈 - // 변수 선언은 여기서 - // 밖에서 접근할 수 없음 -})() // 함수는 즉시 실행됨 -``` -## 도전 과제: - -`scope.js`라는 파일을 만듭니다. - -이 파일에 다음 코드를 복사합니다. -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// 여기서 fruit를 출력하세요. ``` -변수의 `스코프`에 관한 지식을 활용해 다음 코드를 `scope.js` 안의 함수 안에 넣어 `a: 1, b: 8,c: 6`를 출력하게 하세요. -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -이 명령어를 실행해 프로그램이 올바른지 확인하세요. - -```bash -javascripting verify scope.js -``` +두 주석을 각각 `console.log(fruit)`로 바꾸세요. 실행하기 전에 각 줄에 무엇이 출력될지 예상해 보세요. `node scope.js`로 예상이 맞는지 확인한 다음 `javascripting verify scope.js`로 채점하세요. diff --git a/problems/scope/problem_nb-no.md b/problems/scope/problem_nb-no.md index c7bf2645..9765f26b 100644 --- a/problems/scope/problem_nb-no.md +++ b/problems/scope/problem_nb-no.md @@ -1,68 +1,16 @@ -`Scope` er de variablene, objektene og funksjonene du har tilgang til. +En variabels virkefelt bestemmer hvor i koden du kan bruke den. Klammeparentesene rundt innholdet i en `if`-setning danner en blokk. -JavaScript har to scope: `global` og `lokal`. En variabel som er deklarert utenfor en funksjon er en `global` variabel. Dens verdi er tilgjengelig og kan endres gjennom hele programmet ditt. En variabel som er deklarert inni en funksjon er `lokal`. Den lages og fjernes hver gang funksjonen kjøres og variabelen kan ikke nås av kode som er utenfor funksjonen. - -Funksjoner som er definert inni andre funksjoner, kjent som nøstede funksjoner, har tilgang til scopet til den ytre funksjonen den er deklarert i. - -Følg nøye med på kommentarene i koden under: +Kopier denne koden til `scope.js`. ```js -const a = 4 // a er en global variabel, den kan nås av funksjonene under - -function foo () { - const b = a * 3 // b kan ikke nås utenfor foo funksjonen, men kan nås av funksjoner - // definert inni foo - function bar (c) { - const b = 2 // enda en `b` variabel blir lagd i bar funksjonens scope - // endringer på den nye `b` variabelen endrer ikke den ytre `b` variabelen - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Skriv ut fruit her. } -foo() // 4, 2, 48 -``` -IIFE, Immediately Invoked Function Expression, er et pattern for å lage lokale scope -eksempel: -```js -(function () { // funksjonsuttrykket omgis av paranteser - // variabler defineres her - // kan ikke nås utenfor denne funksjonen -})() // funksjonen kjøres med engang -``` -## Oppgaven: - -Lag en fil som heter `scope.js`. - -Kopier inn følgende kode i den filen: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// Skriv ut fruit her. ``` -Bruk din kunnskap om variablenes `scope` og sett inn følgende kode i en av funksjonene som finnes i 'scope.js' slik at det skrives ut `a: 1, b: 8, c: 6` på skjermen: -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Se om programmet ditt er riktig ved å kjøre kommandoen: - -```bash -javascripting verify scope.js -``` +Bytt ut hver kommentar med `console.log(fruit)`. Hva tror du hver linje vil skrive ut? Kjør `node scope.js` for å se om du gjettet riktig, og sjekk løsningen med `javascripting verify scope.js`. diff --git a/problems/scope/problem_nl.md b/problems/scope/problem_nl.md index 5c82e602..332112d8 100755 --- a/problems/scope/problem_nl.md +++ b/problems/scope/problem_nl.md @@ -1,71 +1,16 @@ -`Scope` noem je de variabele, objecten en functions waar je toegang toe hebt. +Het bereik van een variabele bepaalt waar in de code je die kunt gebruiken. De accolades rond de inhoud van een `if` vormen een blok. -JavaScript kent twee scopes: `global` en `local`. Een variabele die is gedeclareerd buiten een function definitie is een `globale` variabele, en die variabele is toegankelijk en aanpasbaar in alle programma code. Een variabele die is gedefinieerd binnen een function is `local`. De variabele wordt elke keer aangemaakt en weer verwijderd als de function wordt uitgevoerd, en kan niet worden benaderd door code buiten de function. - -Functions die worden gedefinieerd binnen andere functions, we noemen dat nested functions, hebben toegang tot de scope van de bovenliggende function. - -Let goed op de opmerkingen in de onderstaande code: +Kopieer deze code naar `scope.js`. ```js -const a = 4 // a is een globale variabele, deze is toegankelijk via de onderstaande functions: - -function foo () { - const b = a * 3 // b is niet toegankelijk buiten de foo-function, maar is toegankelijk via functions - // die gedefinieerd zijn binnen foo - function bar (c) { - const b = 2 // een andere `b` variable is gedefinieerd in de bar function scope - // de veranderingen aan deze nieuwe `b` variabele hebben geen effect op de andere `b` variabele - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Toon fruit hier. } -foo() // 4, 2, 48 +// Toon fruit hier. ``` - -IIFE, Immediately Invoked Function Expression, is een veelgebruikte manier om een local scope te maken. - -Voorbeeld -```js -(function () { // de function (zonder naam) bevindt zich binnen haakjes. - // variabelen die hier worden gedefinieerd - // kunnen niet worden benaderd van buiten de function -})() // de function wordt direct aangeroepen / uitgevoerd -``` -## De uitdaging: - -Maak een nieuw bestand met de naam `scope.js`. - -Kopieer onderstaande code in je nieuwe bestand: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8; - })() - })() - })() -})() -``` - -Gebruik je nieuwe kennis over de `scope` van variabelen en zet onderstaande code binnen één van de functions in je `scope.js` zodat dit de uitvoer wordt: `a: 1, b: 8, c: 6` -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Controleer of je programma goed werkt met dit commando: - -```bash -javascripting verify scope.js -``` +Vervang elke commentaarregel door `console.log(fruit)`. Voorspel eerst wat elke regel zal tonen. Kijk met `node scope.js` of je voorspelling klopt en controleer je oplossing met `javascripting verify scope.js`. diff --git a/problems/scope/problem_pt-br.md b/problems/scope/problem_pt-br.md index 75719812..fdb9712e 100644 --- a/problems/scope/problem_pt-br.md +++ b/problems/scope/problem_pt-br.md @@ -1,70 +1,16 @@ -`Escopo` é o conjunto de variáveis, objetos, e funções dos quais temos acesso. +O escopo determina quais variáveis você pode usar em cada ponto do código. As chaves que envolvem o corpo de um `if` formam um bloco. -O JavaScript tem dois escopos: `global` e `local`. Uma variável que é declarada fora da definição de uma função é uma variável `global`, e o seu valor pode ser acessado e modificado á partir de qualquer parte do seu programa. Uma variável que é declarada dentro da definição de uma função é `local`. Ela é criada e destruída toda vez que a função é executada, e não pode ser acessada por qualquer código fora da função. - -Funções definidas dentro de outras funções, conhecidas como funções aninhadas, tem acesso ao escopo da função pai. - -Preste atenção nos comentários do código abaixo: +Copie este código para `scope.js`. ```js -const a = 4 // uma variável global, pode ser acessada pelas funções abaixo - -function foo () { - const b = a * 3 // b não pode ser acessada fora da função, mas pode ser acessada pelas funções - // definidas dentro da função foo - function bar (c) { - const b = 2 // uma outra variável `b` é criada dentro do escopo da função bar - // as mudanças dessa nova variável `b` não afeta a outra variável `b` - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Mostre fruit aqui. } -foo() // 4, 2, 48 -``` -IIFE, Immediately Invoked Function Expression (Expressão de Função Executada Imediatamente em tradução livre), é um padrão bastante usado para criar escopos locais. - -Exemplo: -```js -(function () { // a expressão da função é cercada por parênteses - // as variáveis definidas aqui - // não podem ser acessadas do lado de fora -})() // a função é executada imediatamente +// Mostre fruit aqui. ``` -## Desafio: - -Crie um arquivo chamado `scope.js`. - -Nesse arquivo, copie o seguinte código: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() -``` - -Utilize seus conhecimentos sobre `escopo` de variáveis e posicione o seguinte código dentro de uma das funções no 'scope.js' -fazendo o resultado ser `a: 1, b: 8,c: 6` -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Verifique se o seu programa está correto executando o comando: - -```bash -javascripting verify scope.js -``` +Substitua cada comentário por `console.log(fruit)`. Antes de executar o código, tente prever o que cada linha vai mostrar. Confira com `node scope.js` e verifique sua solução com `javascripting verify scope.js`. diff --git a/problems/scope/problem_ru.md b/problems/scope/problem_ru.md index 32c3f4c9..e84edb5a 100644 --- a/problems/scope/problem_ru.md +++ b/problems/scope/problem_ru.md @@ -1,75 +1,16 @@ -`Область видимости` описывает множество переменных, объектов, а также функций, к которым есть непосредственный доступ. +Область видимости определяет, какие переменные доступны в данном месте программы. Фигурные скобки вокруг тела `if` образуют блок. -JavaScript обладает двумя областями видимости: `глобальной` и `локальной`. Переменная, объявленная снаружи функции, является `глобальной` переменной. Она доступна и изменяема из любого места вашей программы. При объявлении переменной внутри функции мы получаем `локальную` переменную. Она создаётся и удаляется каждый раз при вызове функции. К такой переменной нельзя получить доступ извне функции. - -Функции, объявленные внутри других функций, известные также как вложенные (дочерние) функции, имеют доступ к области видимости родительской функции. - -Обратите внимание на комментарии к приведённому ниже коду: +Скопируйте этот код в файл `scope.js`. ```js -const a = 4 // это глобальная переменная, она доступна для функций ниже - -function foo () { - const b = a * 3 // к переменной `b` нет доступа снаружи функции `foo`, но к - // этой переменной имеют доступ функции, объявленные внутри `foo` - function bar (c) { - const b = 2 // ещё одна переменная `b` создана внутри области видимости - // функции `bar`, модификации этой новой переменной `b` никак не - // отразятся на объявленной выше переменной `b` - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Выведите fruit здесь. } -foo() // 4, 2, 48 -``` - -Непосредственно выполняемая функция-выражение (IIFE) -- распространённый паттерн создания локальной области видимости. - -Например: - -```js -(function () { // объявление функции окружено круглыми скобками - // переменные, объявленные здесь, - // не будут доступны снаружи -})() // функция сразу же вызывается -``` - -## Условия задачи - -Создайте файл `scope.js`. - -Скопируйте в него следующий код: - -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// Выведите fruit здесь. ``` -Используя полученные знания об `областях видимости`, разместите приведённый ниже код внутри одной из функций, объявленных в `scope.js` так, чтобы на выходе получилось `a: 1, b: 8, c: 6`. - -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Чтобы удостовериться в правильности решения задачи, запустите следующую команду из терминала: - -```bash -javascripting verify scope.js -``` +Замените каждый комментарий на `console.log(fruit)`. До запуска попробуйте предсказать, что появится в каждой строке. Проверьте догадку командой `node scope.js`, а затем проверьте решение командой `javascripting verify scope.js`. diff --git a/problems/scope/problem_uk.md b/problems/scope/problem_uk.md index 770553bf..6d757340 100644 --- a/problems/scope/problem_uk.md +++ b/problems/scope/problem_uk.md @@ -1,68 +1,16 @@ -`Область видимості (Scope)` — це множина змінних, об’єктів та функцій до яких ви маєте доступ. +Область видимості визначає, які змінні доступні в певному місці програми. Фігурні дужки навколо тіла `if` утворюють блок. -JavaScript має дві області видимості: `глобальну` та `локальну`. Змінні, що оголошені поза визначенням функції є `глобальною` змінною, тож її значення буде доступне для читання та модифікації у всій вашій програмі. Змінну, яка оголошена всередині визначення функції, називають `локальною`. Вона створюється та знищується кожного разу коли функція виконується і її значення не можна отримати поза цієї функції. - -Функції, які визначені всередині інших функцій, також відомі як вкладені (nested) функції, мають доступ до області видимості їх батьківських функцій. - -Зверніть увагу на коментарі у цьому прикладі: +Скопіюйте цей код у файл `scope.js`. ```js -const a = 4 // a є глобальною змінною, її значення можна отримати з функцій нижче - -function foo () { - const b = a * 3 // b не можу бути доступною поза функцією foo, але доступна у - // функціях, оголошених всередині foo - function bar (c) { - const b = 2 // інша змінна `b` створена всередині функції bar зміна значення - // цієї змінної `b` не вплине на попередню змінну `b` - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // Виведіть fruit тут. } -foo() // 4, 2, 48 -``` -Функції миттєвого (негайного) виклику, або «самовикликаючі» функцій (IIFE, Immediately Invoked Function Expression) є загальною практикою для створення локальних областей видимості -Приклад: -```js -(function () { // вираз функції оточений круглими дужками - // змінні оголошені тут - // не будуть доступними ззовні -})() // функція відразу ж викликається -``` -## Завдання: - -Створити файл `scope.js`. - -До цього файлу скопіювати такий код: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// Виведіть fruit тут. ``` -Використайте ваші знання про `область видимості` змінних та помістіть код нижче в таку функцію зі 'scope.js', щоб результат був рядок `a: 1, b: 8,c: 6`: -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -Перевірте вашу відповідь запустивши команду: - -```bash -javascripting verify scope.js -``` +Замініть кожен коментар на `console.log(fruit)`. Перед запуском спробуйте передбачити, що з’явиться в кожному рядку. Перевірте свій прогноз командою `node scope.js`, а потім перевірте розв’язок командою `javascripting verify scope.js`. diff --git a/problems/scope/problem_zh-cn.md b/problems/scope/problem_zh-cn.md index 074329e8..82f7679e 100644 --- a/problems/scope/problem_zh-cn.md +++ b/problems/scope/problem_zh-cn.md @@ -1,68 +1,16 @@ -`作用域` 就是你能访问到的变量、对象以及函数的集合。 +作用域决定了你在代码的某个位置能使用哪些变量。包围 `if` 语句体的一对花括号构成一个代码块。 -JavaScript 有两种类型的作用域:`全局` 以及 `局部`。函数外声明的变量是一个 `全局` 变量,它的值可以在整个程序中被访问和修改。函数内声明的变量是 `局部` 的,它随着函数的调用而被创建,随着函数的结束而被销毁。它不能在函数外被访问。 - -在函数中定义的函数,也叫嵌套函数,可以访问到外层函数的作用域。 - -注意下面的代码: +将下面的代码复制到 `scope.js`。 ```js -const a = 4 // a is a global variable, it can be accesed by the functions below - -function foo () { - const b = a * 3 // b cannot be accesed outside foo function, but can be accesed by functions - // defined inside foo - function bar (c) { - const b = 2 // another `b` variable is created inside bar function scope - // the changes to this new `b` variable don't affect the old `b` variable - console.log(a, b, c) - } +const fruit = 'apple' - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // 在这里输出 fruit。 } -foo() // 4, 2, 48 -``` -立即函式(IIFE, Immediately Invoked Function Expression)是用来创建局部作用域的常用方法。 -例子: -```js -(function () { // the function expression is surrounded by parenthesis - // variables defined here - // can't be accesed outside -})() // the function is immediately invoked -``` -## 挑战: - -创建名为 `scope.js` 的文件。 - -在文件中复制粘贴下面的代码: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +// 在这里输出 fruit。 ``` -依你对 `作用域` 的理解,将下面这段代码插入上述代码里,使得代码的输出为 `a: 1, b: 8,c: 6`。 -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -通过运行以下命令检查你的程序是否正确: - -```bash -javascripting verify scope.js -``` +把两处注释分别替换为 `console.log(fruit)`。运行前,先猜猜每一行会输出什么。用 `node scope.js` 检验你的猜想,再用 `javascripting verify scope.js` 检查答案。 diff --git a/problems/scope/problem_zh-tw.md b/problems/scope/problem_zh-tw.md index f3c4d0a7..caa11fd7 100644 --- a/problems/scope/problem_zh-tw.md +++ b/problems/scope/problem_zh-tw.md @@ -1,68 +1,16 @@ -`作用域` 就是你能訪問到的變數、物件以及函式的集合。 +作用域決定了你在程式碼的某個位置可以使用哪些變數。包住 `if` 敘述主體的一對大括號構成一個區塊。 -JavaScript 有兩種類型的作用域:`全域` 以及 `區域`。函式外宣告的變數是一個 `全域` 變數,它的值可以在整個程式中被存取和修改。函式內宣告的變數是 `區域` 的,它隨著函式的呼叫而被建立,再隨著函式的結束而被銷毀。它不能在函式以外被存取。 - -在函式中定義的函式,也叫巢狀函式,可以存取到外層函式的作用域。 - -注意下面的程式碼: +將以下程式碼複製到 `scope.js`。 ```js -const a = 4 // a 是一個全域變數,它可以被下面的函式存取 - -function foo () { - const b = a * 3 // b 不能夠在 foo 函式以外被存取,但是可以被定義於 foo 內部的其他函式存取 +const fruit = 'apple' - function bar (c) { - const b = 2 // 另一個新的 `b` 變數被建立在 bar 函式的作用域內 - // 對這個新的 `b` 變數的改變並不會影響到舊的 `b` 變數 - console.log(a, b, c) - } - - bar(b * 4) +if (fruit === 'apple') { + const fruit = 'orange' + // 在這裡輸出 fruit。 } -foo() // 4, 2, 48 -``` -立即函式(IIFE, Immediately Invoked Function Expression)是用來建立區域作用域的常用方法。 -範例: -```js -(function () { // 這個函式語法被一組小括號括起來 - // 在這裡定義的變數 - // 不能夠在這個函式外被存取 -})() // 這個函式立即被執行 +// 在這裡輸出 fruit。 ``` -## 挑戰: - -建立一個名為 `scope.js` 的檔案。 - -在該檔案中複製貼上以下的程式碼: -```js -const a = 1; const b = 2; const c = 3; - -(function firstFunction () { - const b = 5; const c = 6; - (function secondFunction () { - const b = 8; - - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() -``` - -依你對 `作用域` 的理解,將下面這段程式碼插入上述程式碼裡,使得程式碼的輸出為 `a: 1, b: 8,c: 6`。 -```js -console.log(`a: ${a}, b: ${b}, c: ${c}`); -``` - -透過執行以下指令來檢查你的程式是否正確: - -```bash -javascripting verify scope.js -``` +將兩處註解分別換成 `console.log(fruit)`。執行前,先猜猜每一行會輸出什麼。用 `node scope.js` 檢驗你的猜測,再用 `javascripting verify scope.js` 檢查答案。 diff --git a/problems/scope/solution.md b/problems/scope/solution.md index a2db4379..bfc01b0a 100644 --- a/problems/scope/solution.md +++ b/problems/scope/solution.md @@ -1,8 +1,15 @@ --- -#EXCELLENT! +# EXCELLENT! -You got it! The second function has the scope we were looking for. +```text +orange +apple +``` + +The condition reads the outer `fruit`, whose value is `'apple'`. Inside the block, `const fruit = 'orange'` declares a separate variable. The first log reads that inner variable. After the closing brace, the second log reads the outer variable, which still holds `'apple'`. + +What would the first line print if you removed the inner declaration? Try it: both lines now print `apple` because both read the outer variable. Now move on to a more challenging Javascript workshopper **Functional Javascript**: diff --git a/problems/scope/solution_es.md b/problems/scope/solution_es.md index c4416387..34d3501b 100644 --- a/problems/scope/solution_es.md +++ b/problems/scope/solution_es.md @@ -2,7 +2,14 @@ # EXCELENTE! -Lo hiciste! La segunda función tiene el ámbito que estabamos buscando. +```text +orange +apple +``` + +La condición lee la variable externa `fruit`, que vale `'apple'`. Dentro del bloque, `const fruit = 'orange'` declara otra variable. La primera línea muestra su valor. Después de la llave de cierre, la segunda línea lee la variable externa, que sigue valiendo `'apple'`. + +¿Qué mostraría la primera línea si quitaras la declaración interna? Pruébalo: ambas líneas muestran `apple` porque leen la variable externa. Ejecuta `javascripting` en la consola para seleccionar el siguiente ejercicio. --- diff --git a/problems/scope/solution_fr.md b/problems/scope/solution_fr.md index 4a0d3eee..4bb8b35f 100644 --- a/problems/scope/solution_fr.md +++ b/problems/scope/solution_fr.md @@ -2,7 +2,14 @@ # EXCELLENT ! -C'est bon ! La seconde fonction possède le `scope` que nous recherchons. +```text +orange +apple +``` + +La condition lit la variable extérieure `fruit`, qui vaut `'apple'`. Dans le bloc, `const fruit = 'orange'` déclare une autre variable. Le premier affichage utilise cette variable intérieure. Après l’accolade fermante, le second utilise la variable extérieure, qui vaut toujours `'apple'`. + +Que se passerait-il si vous supprimiez la déclaration intérieure ? Essayez : les deux lignes affichent `apple`, car elles lisent la variable extérieure. Exécutez `javascripting` dans la console pour choisir le prochain défi. diff --git a/problems/scope/solution_it.md b/problems/scope/solution_it.md index b0fffd22..34be3aac 100644 --- a/problems/scope/solution_it.md +++ b/problems/scope/solution_it.md @@ -1,8 +1,15 @@ --- -#ECCELLENTE! +# ECCELLENTE! -Ce l'hai fatta! La seconda funzione possiede l'ambito che cercavamo. +```text +orange +apple +``` + +La condizione legge la variabile esterna `fruit`, che vale `'apple'`. Nel blocco, `const fruit = 'orange'` dichiara una variabile distinta. La prima stampa legge la variabile interna. Dopo la graffa di chiusura, la seconda legge quella esterna, che vale ancora `'apple'`. + +Cosa stamperebbe la prima riga se eliminassi la dichiarazione interna? Prova: entrambe le righe stampano `apple` perché leggono la variabile esterna. Esegui `javascripting` nella console per scegliere la prossima sfida. diff --git a/problems/scope/solution_ja.md b/problems/scope/solution_ja.md index e8228a5b..1b08df57 100644 --- a/problems/scope/solution_ja.md +++ b/problems/scope/solution_ja.md @@ -2,7 +2,14 @@ # 素晴らしい! -やるね! 二番目の関数が、求めていたスコープを持っています。 +```text +orange +apple +``` + +`if` の条件で参照するのは、値が `'apple'` の外側の変数です。ブロック内の `const fruit = 'orange'` は、同じ名前の別の変数を宣言します。最初の表示ではこの内側の変数を参照します。閉じ波括弧の後では外側の変数を参照するので、2行目には元の値の `apple` が表示されます。 + +内側の宣言を消したら、1行目は何になるでしょう? 試してみると、どちらも外側の変数を参照するので、2行とも `apple` になります。 コンソールで `javascripting` コマンドを実行します。次の課題を選択しましょう。 diff --git a/problems/scope/solution_ko.md b/problems/scope/solution_ko.md index 02d94b34..842f707a 100644 --- a/problems/scope/solution_ko.md +++ b/problems/scope/solution_ko.md @@ -2,7 +2,14 @@ # 훌륭해요! -해냈습니다! 두 번째 함수는 우리가 찾는 스코프를 가지고 있습니다. +```text +orange +apple +``` + +조건식은 값이 `'apple'`인 바깥쪽 변수 `fruit`를 읽습니다. 블록 안의 `const fruit = 'orange'`는 같은 이름의 새 변수를 선언합니다. 첫 번째 출력문은 안쪽 변수를 읽습니다. 닫는 중괄호 다음에 있는 두 번째 출력문은 여전히 값이 `'apple'`인 바깥쪽 변수를 읽습니다. + +안쪽 선언을 지우면 첫 줄에 무엇이 출력될까요? 직접 해 보세요. 두 출력문 모두 바깥쪽 변수를 읽으므로 두 줄 모두 `apple`이 출력됩니다. 다음 과제로 가시려면 콘솔에서 `javascripting`을 실행하세요. diff --git a/problems/scope/solution_nb-no.md b/problems/scope/solution_nb-no.md index 903400cd..9319817f 100644 --- a/problems/scope/solution_nb-no.md +++ b/problems/scope/solution_nb-no.md @@ -2,7 +2,14 @@ # UTMERKET! -Du skjønte det! Den andre funksjonen har det scopet vi lette etter. +```text +orange +apple +``` + +Betingelsen leser den ytre variabelen `fruit`, som har verdien `'apple'`. Inne i blokken deklarerer `const fruit = 'orange'` en egen variabel. Den første utskriften bruker den indre variabelen. Etter den avsluttende klammeparentesen bruker den andre utskriften den ytre variabelen, som fortsatt har verdien `'apple'`. + +Hva ville den første linjen skrive ut hvis du fjernet den indre deklarasjonen? Prøv selv. Begge linjene skriver ut `apple` fordi begge leser den ytre variabelen. Kjør kommandoen `javascripting` i terminalen for å velge neste oppgave. diff --git a/problems/scope/solution_nl.md b/problems/scope/solution_nl.md index b1fd79d4..fa008181 100644 --- a/problems/scope/solution_nl.md +++ b/problems/scope/solution_nl.md @@ -2,7 +2,14 @@ # EXCELLENT! -Goed gedaan! De tweede function heeft de scope die we zochten. +```text +orange +apple +``` + +De voorwaarde leest de buitenste variabele `fruit`, met de waarde `'apple'`. Binnen het blok declareert `const fruit = 'orange'` een aparte variabele. De eerste aanroep leest die binnenste variabele. Na de sluitaccolade leest de tweede aanroep de buitenste variabele, die nog steeds de waarde `'apple'` heeft. + +Wat zou de eerste regel tonen als je de binnenste declaratie weghaalt? Probeer het: beide regels tonen `apple` omdat ze allebei de buitenste variabele lezen. Ga nu verder met een meer uitdagende Javascript workshopper **Functional Javascript**: diff --git a/problems/scope/solution_pt-br.md b/problems/scope/solution_pt-br.md index 92253b43..36ab3695 100644 --- a/problems/scope/solution_pt-br.md +++ b/problems/scope/solution_pt-br.md @@ -1,8 +1,15 @@ --- -#EXCELENTE! +# EXCELENTE! -Você pegou o jeito! A segunda função tem o escopo que procurávamos. +```text +orange +apple +``` + +A condição lê a variável externa `fruit`, cujo valor é `'apple'`. Dentro do bloco, `const fruit = 'orange'` declara outra variável. A primeira chamada lê a variável interna. Após a chave de fechamento, a segunda chamada lê a variável externa, que continua com o valor `'apple'`. + +O que a primeira linha mostraria se você removesse a declaração interna? Experimente: as duas linhas mostram `apple` porque ambas leem a variável externa. Execute javascripting no console para escolher o próximo desafio. diff --git a/problems/scope/solution_ru.md b/problems/scope/solution_ru.md index e8fdd9ae..e53dd5f5 100644 --- a/problems/scope/solution_ru.md +++ b/problems/scope/solution_ru.md @@ -2,7 +2,14 @@ # НЕВЕРОЯТНО! -У вас получилось! Именно вторая функция обладает нужной нам областью видимости. +```text +orange +apple +``` + +В условии используется внешняя переменная `fruit` со значением `'apple'`. Внутри блока `const fruit = 'orange'` объявляет отдельную переменную. Первый вызов выводит значение внутренней переменной. После закрывающей скобки второй вызов читает внешнюю переменную, значение которой по-прежнему равно `'apple'`. + +Что выведет первая строка, если убрать внутреннее объявление? Попробуйте: в обеих строках появится `apple`, потому что оба вызова читают внешнюю переменную. Запустите `javascripting` в консоли и выберите следующую задачу. diff --git a/problems/scope/solution_uk.md b/problems/scope/solution_uk.md index 8597bbf8..2b7c0f02 100644 --- a/problems/scope/solution_uk.md +++ b/problems/scope/solution_uk.md @@ -2,7 +2,14 @@ # ЧУДОВО! -Ви зробили це! Друга функція має саме таку область видимості, яку ми шукали. +```text +orange +apple +``` + +В умові використовується зовнішня змінна `fruit` зі значенням `'apple'`. Усередині блоку `const fruit = 'orange'` оголошує окрему змінну. Перший виклик виводить значення внутрішньої змінної. Після закривної дужки другий виклик читає зовнішню змінну, значення якої й далі дорівнює `'apple'`. + +Що виведе перший рядок, якщо прибрати внутрішнє оголошення? Спробуйте: в обох рядках з’явиться `apple`, бо обидва виклики читають зовнішню змінну. Запустіть 'javascripting' в консолі, щоб обрати наступне завдання. diff --git a/problems/scope/solution_zh-cn.md b/problems/scope/solution_zh-cn.md index 5dd3f843..872c2c30 100644 --- a/problems/scope/solution_zh-cn.md +++ b/problems/scope/solution_zh-cn.md @@ -2,7 +2,14 @@ # 真棒! -第二个函数的作用域就是我们要找的。 +```text +orange +apple +``` + +条件表达式读取的是外层变量 `fruit`,它的值是 `'apple'`。在代码块中,`const fruit = 'orange'` 声明了另一个同名变量。第一次输出读取的是内层变量。右花括号之后,第二次输出读取的是外层变量,它的值仍然是 `'apple'`。 + +如果删掉内层变量的声明,第一行会输出什么?试一试:两行都会输出 `apple`,因为两次读取的都是外层变量。 运行 `javascripting` 并选择下一个挑战。 diff --git a/problems/scope/solution_zh-tw.md b/problems/scope/solution_zh-tw.md index dfc80fc3..b51dc420 100644 --- a/problems/scope/solution_zh-tw.md +++ b/problems/scope/solution_zh-tw.md @@ -2,7 +2,14 @@ # 真棒! -第二個函式的作用域就是我們要找的。 +```text +orange +apple +``` + +條件式讀取的是外層變數 `fruit`,它的值是 `'apple'`。在區塊內,`const fruit = 'orange'` 宣告了另一個同名變數。第一次輸出讀取的是內層變數。右大括號之後,第二次輸出讀取的是外層變數,它的值仍然是 `'apple'`。 + +如果刪掉內層變數的宣告,第一行會輸出什麼?試試看:兩行都會輸出 `apple`,因為兩次讀取的都是外層變數。 運行 `javascripting` 並選擇下一個挑戰。 diff --git a/solutions/scope/index.js b/solutions/scope/index.js index 41e450f2..019d2fd1 100644 --- a/solutions/scope/index.js +++ b/solutions/scope/index.js @@ -1,19 +1,8 @@ -/* eslint-disable no-unused-vars */ +const fruit = 'apple' -const a = 1; const b = 2; const c = 3; +if (fruit === 'apple') { + const fruit = 'orange' + console.log(fruit) +} -(function firstFunction () { - const b = 5; const c = 6; - - (function secondFunction () { - const b = 8 - console.log('a: ' + a + ', b: ' + b + ', c: ' + c); - (function thirdFunction () { - const a = 7; const c = 9; - - (function fourthFunction () { - const a = 1; const c = 8 - })() - })() - })() -})() +console.log(fruit)