Navigating Variable Scopes: A Journey into the World of JavaScript

Berk Subaşı
2 min readMar 13, 2024

--

Come, let’s take a peek into the mysterious world of JavaScript! Today, we’ll explore the secretive scopes of variables. Are you ready? Because this is going to be a bit magical!

Firstly, we have a function named createNumber. This function generates random numbers for us. But wait a minute... when we try to print the upperLimit variable to the console, we encounter an error. Why, you ask? Because this variable lives in its own little world inside that function, so we can't access it from the outside. Ah, variable scopes can be really sneaky sometimes!javascriptCopy code

function createNumber(upperLimit = 40){
return Math.ceil(Math.random() * upperLimit);
}
console.log(upperLimit); // We're getting an error here!// Generating numbers
var number1 = createNumber();
var number2 = createNumber();
var number3 = createNumber();
var number4 = createNumber();
var number5 = createNumber();
var number6 = createNumber();
console.log('Column: ' + number1 + ' ' + number2 + ' ' + number3 + ' ' + number4 + ' ' + number5 + ' ' + number6);

So, what should we do? Of course, we should set our variable a bit free! Let’s make it a global citizen and allow everyone to access it. Behold, a global superstar!

var upperLimit = 40;
function createNumber(upperLimit){
return Math.ceil(Math.random() * upperLimit);
}
console.log(upperLimit); // Now everything is fine!// Generating numbers
var number1 = createNumber();
var number2 = createNumber();
var number3 = createNumber();
var number4 = createNumber();
var number5 = createNumber();
var number6 = createNumber();
console.log('Column: ' + number1 + ' ' + number2 + ' ' + number3 + ' ' + number4 + ' ' + number5 + ' ' + number6);

And there you go, our variable is now a global rockstar! Whether inside the function or outside, everyone is gazing at it with admiration. This is yet another adventure in the magical world of variable scopes!

You see, in the world of JavaScript, anything is possible! A little flexibility, a little magic… and behold, the secrets of scope are unraveled! Now you can be the most scope-savvy coder in the world. Let’s continue to explore more in the coding world! 🚀✨

--

--