How I ended up WASTING A DAY worth of time debugging !
Don't make this mistake, though !
I recently started my journey of Web Development and I was learning and implementing stuff at such a peak that I had to keep reminders on my phone to take a breaks ! Such an excitement.
AND THEN CAME JAVASCRIPT
Though I did not start learning JavaScript from basics (because of excitement), I was straightaway learning concepts from what was taught in the tutorials. And then, I stumbled upon an issue which I just couldn't understand a block of code and resolve.
The block of code I had wrote was
var url = "www.google.com";
function constructURL(input){
var ulr2 = url + "?" + "search= " + input;
}
constructURL("dog");
console.log(url2);
But, when I ran the code block on the browser console, it returned an error that url2
was not defined.
I just didn't understand why the error but I was sure about the logic behind it and what the output should be. Even Google was not able to point out where and why I was wrong, and I just didn't know how to ask someone about my doubt on why a block of code was not giving the result I wanted.
This small block of code, kept me wondering why it wasn't working. So I decided to go watch the tutorial again to understand where I went wrong, and somewhere in the middle, the instructor Sri Tanay Pratap mentioned about javascripttutorial.net and he said it was excellent website to learn JavaScript and also clarify doubts.
So, I decided to take a break from the project and started learning the JavaScript basics on that website and just after a few sub-sections, I landed on this section. This sectioned explained about variables in global scope, local scope and block scope.
AND, I went through it so clearly, that I was now able to understand why url2
was not defined and console.log(url2)
was not executed. It was because url2
was a variable inside the function, hence it was a local scope variable. Meaning, url2
only existed inside that particular function as a local variable and not outside as a global variable. This also made me understand why the instructor was declaring certain variables as global in the browser console, before executing a code based on it.
LESSON LEARNT: Learning the basics is extremely important, else it will result in such headaches!