Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 8 additions & 64 deletions problems/scope/problem.md
Original file line number Diff line number Diff line change
@@ -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`.
63 changes: 8 additions & 55 deletions problems/scope/problem_es.md
Original file line number Diff line number Diff line change
@@ -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`.
71 changes: 8 additions & 63 deletions problems/scope/problem_fr.md
Original file line number Diff line number Diff line change
@@ -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`.
69 changes: 8 additions & 61 deletions problems/scope/problem_it.md
Original file line number Diff line number Diff line change
@@ -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`.
70 changes: 8 additions & 62 deletions problems/scope/problem_ja.md
Original file line number Diff line number Diff line change
@@ -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` で採点できます。
Loading