Block Scope II
Mari kita lihat contoh lain dari cakupan blok, sebagaimana didefinisikan dalam blok
if:
const colorOfSky = () => {
const dusk = true;
let color = 'blue';
if (dusk) {
let color = 'pink';
console.log(color); // pink
}
console.log(color); // blue
};
colorOfSky(); // blue
console.log(color); // ReferenceError
Di sini, Anda akan melihat:
- Kami membuat variabel
duskdi dalam fungsicolorOfSky(). - Setelah pernyataan
if, kita mendefinisikan blok kode baru{}braces. Disini kita menetapkan nilai baru untuk variabelcolorjika statemenifbernilaitrue. - Dalam blok
if, variabelcolormemiliki nilaipink, meskipun diluar blokif, dalam badan fungsi, variabelcolorbernilaiblue.
Block scope is a powerful tool in JavaScript, since it allows us to define variables with precision, and not pollute the global namespace.
1.
Remove the statement that erroneously logs the value of the
lightWavesvariable to the console outside of the function block.
2.
Let's continue by adding another variable to the
visibleLightWaves()function. Beneath the lightWavesvariable, using let, add a variable region and set it equal to 'The Arctic'.
3.
Beneath the
region variable, create an if statement that checks if the region is the 'The Arctic'.
4.
Inside the
if block, define a new variable lightWaves and set it equal to 'Northern Lights'.
5.
Beneath the variable in the
if block, use console.log() to log the value of the block variable inside the if block.
Notice the ouput. Inside the
if block console.log(lightWaves) logs the value Northern Lights to the console. Outside the if block, but still within the function, the same statement logs Moonlight to the console.
Tidak ada komentar:
Posting Komentar