Monday, 14 January 2019

JavaScript variable scope and hoisting

Variable scope and hoisting

Variable scope defines the places in our code where we can access our variable via reference to use or change their values. JavaScript has two main variable scopes which are function scope and block scope and these scopes are given based on how you define a variable. 

Before ECMAScript 2015 we only had one keyword to define a variable in JavaScript which is the var keyword. The var keyword defines a variable that exists in function scope. This is pretty self explanatory in that variables defined with the var keyword are accessible within the function they were defined. There are two terms typically used to identify a variables scope, these are local and global scope. Local scope is a variable that is defined inside its keyword defined scope therefore keeping its scope local to that function whereas global scope is a variable that is defined in the main body of the JavaScript code and can therefore be accessed anywhere within the JavaScript code. Below are two examples of function scope both local and global and how they can effect where you are able to access a defined variable.


The first example demonstration how trying to access a variable out of its scope will throw you an undefined error and the second example shows how there can be two variables with the same name that exist in different scopes and depending where you access the reference depends on which variable and therefore which value you will get; in this case we are trying to accessing a variable in the main body of the JavaScript code therefore it gets the reference to the global variable in the same scope.

Now moving on to ECMAScript 2015 and block scope we have two new keywords to define variables which gives them block scope, these keywords are let and const. Treat let as the block scope version of var however const is slightly different in that although the variable is also of block scope it is defined as a constant which means the value assigned can never be changed therefore you can still access this variable but you can never modify its value.

The key difference here with let and const opposed to var is that although they all share the same definition of a global scope in the main body of the JavaScript let and const variables have a local scope of block. This means the variables can only be accessed within the curly braces ({ }) they were defined. Below are a couple of examples demonstrating block scope using the let key word.



In the examples we see the main difference between function and block scoped variables. The first example shows how two variables with the same name are created in the main body of the JavaScript code and the variable when logged shows the the last defined variable overwrites the original due to both variables living in the same function scope. The second example is exactly the same except we now have the let keyword defining the variables so now only the variable defined in the main body of the JavaScript is being logged as the other variable has a block scope and is defined between curly braces ({ }) meaning our log only accesses the variable it knows defined in its same block scope in this case being the main body of the JavaScript. 

One final thing to demonstrate when it comes to JavaScript variables is what JavaScript does behind the scenes when variables are defined. The specific behind the scenes action I am referring to is variable hoisting which is an important thing to understand to save you the headache of not understanding why your variables and there values may appear to be incorrect at times. Variable hoisting is the means by which JavaScript creates your variables in memory by hoisting all your variables to the top of your defined scope. So for example if you create variables x and y inside a function with the var keyword assigned with number values although you yourself have created them anywhere you want in your function JavaScript will hoist the variable definition to the top of the function before any logical code. Bare in mind it is only the variable declaration and not the value assignment that is hoisted to the top of your scope. This can lead to both tricky bugs and tricky interview questions surrounding scopes and what you would expect to see outputted. See the example below to see hoisting in action and the problems it can create.



As you can see in the examples above logically you would think that trying to log a variable before you have defined it in your function would mean it would go through the next scope in this case the global scope to look for that variable. However with hoisting the variable definition is hoisted to the top of the function and the value assignment remains after the log so you now end up with an undefined error. Keep this in mind that it is a best practice to define all your variables and initial value assignments at the top of your scope.

That's all for today folks thanks for giving this a read and hopefully you have gained a few neat tips in particular hoisting which is not something that is explained very often with JavaScript. The next post will be here soon where I will be covering immutability. Stay tuned.

Sunday, 6 January 2019

JavaScript Variable Types

Variable Types

In JavaScript each variable you define will be assigned a type which then belongs to its own Object type and gives you access to type specific properties and methods. However not only do your variables have a data type they also have an access type. The data type determines what data your variable is defined as and therefore influences what properties and methods it has whereas the access type dictates how the variable is accessed and modified. 

JavaScript has 7 variable data types which are Number, String, Boolean, Symbol, Object, Null and Undefined. These variables also have one of two different memory types which are Primitive and Reference. Now I know you might be thinking "So where are Function and Array variables?" well these variables are defined as part of Object whereby a function is seen as an object that is callable and an array is seen as representation of a list or set that inherits from the Array.prototype object.

This raises the next point which people beginning JavaScript development may not grasp in that every variable in JavaScript is essentially an object that inherits from a particular types prototype which then gives these variables access to specific properties and methods. Lets take the Number type as an example, once you have defined a variable as a number you have access to built in Number.prototype methods such as parseInt(), toFixed() and isNaN(). Below I will demonstrate some variable types and their type.prototype inherited methods.



Now the second part regarding variable types is key to understanding future topics such as immutability which will be discussed in a future post soon. So when we say a variable is a primitive or reference type what we mean is it is either a variable that is directly accessed and modified by its value whereas a reference type is a type that simply points to a space in memory where values are stored and when you access this variable you are accessing its reference to where its stored in memory.

In JavaScript Objects are reference types and everything else is a primitive. A good way to explain the difference between primitive and reference types is to show the difference when trying to copy values to a new variable. If you create a number and then assign its value to a new number variable you then have two variables with the same number value however when you change one of their values only that variable is changed as it only cares about its own stored value being accessed and modified. With reference types however if you create an object and then assign another variable to the same value you have created two variables that due to reference type point to the same object that is stored in memory, therefore when you go to change a property in this object from either variable both will change as they are pointing to the same object in memory. Below is a quick demo of this.


This concludes the first blog for JavaScript development where the focus has been on the basics and fundamental concepts of variable and access types. Hope you enjoyed and stay tuned for the next post which will be focusing on variable scope.