Basic JavaScript: part 1.

Basic JavaScript: part 1.

Let's talk about variable- declarations, initialization, scope and hoisting.

Why do we use variables?

A variable is one of the most important concepts in programming. Variables in JavaScript and in programming language in general- are a means to store information and track it in an application. So, if I store a value in a data structure, I can call it a variable.

It is however worthy of note that different variables can hold the same value or point to the same value.

Variable Declaration

You do not specify the value of the variable. It just means some memory is allocated to store a value that can be assigned to the variable created.

Example-

var myFirstName;

Declaration Types

The different declaration types includes-

var - This is probably the most popular because not until ECMAScript6, there was no other alternative. Variables declared with var are available in the scope of the enclosing function. If there is no enclosing function then it's globally available.

function sayGreeting(){
var greeting = "Good Morning";
return greeting;
}
console.log(greeting);

This will cause an error- greeting is not defined, as the variable greeting is only available within the function sayGreeting. But this will work if the variable is declared globally that is in the same scope console.log(greeting) is located:

var greeting = "Good Morning";
function sayGreeting (){
return greeting;
}
console.log (greeting);

let - In modern JavaScript, we have the let. It's scope is not only limited to the enclosing function but also to its enclosing block statement. A block statement is everything within the curly braces- {}. let reduces the possibility of errors as variables are only available within a smaller scope unlike var.

Example:

var name = "Dumebi";
if (name= "Dumebi"){
let hi = "Hi Dumebi";
} else {
let hi = "Hello";
}
console.log (hi);

This will cause an ReferenceError: hi is not edited as hi is only available inside the enclosing block - in this case the if condition. But the following will work:

var name = "Dumebi";
if (name= "Dumebi"){
let hi = "Hi Dumebi";
console.log(hi);
} else {
let hi = "Hello";
console.log(hi);
}

const - A constant is not a variable. You assign a value while declaring it and it cannot be reassigned. Just like let, a const is limited to the scope of the enclosing block. When should we use const ? Use const when a value must remain unchanged during application run time. It was introduced to allow "immutable variables "

Variable Initialization

It means assigning a value to a variable at the time it's been declared If no value is assigned before declaration, it will return undefined.

var myFirstName = "Dumebi";

When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.

Variable Scoping

scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. It is controlled by the location of the variable declaration.

Types of scope -

• Global scope are those declared outside of a block or function.

• Local scope are those declared inside of a block or function.

What does this all mean? Any variable declared outside of a function belongs to the global scope and is accessible from anywhere in your code. Where as, any variable declared within a function is only accessible from that function and any nested functions and thus belongs to a local scope . (Local scope in Java Script is created by functions and it's also called a 'function scope').

Example

//initialize a global variable 
var vehicle = "lorry";

function transform (){
//initialize a local variable
var vehicle = "motorcycle";
console.log(vehicle);
}

//log the global and local variable
console.log (vehicle);
transform ();
console.log (vehicle);


Output:
lorry
motorcycle 
lorry

In the example above - We created a global vehicle variable and within a function, a local variable with the same name. In the console, we see that the variable's value is different depending on the scope.

We see that local variables are function scoped. Variables declared with var keyword are always function scoped.

The new keywords let and const are block - scoped.

Example to illustrate the difference between blocked and function scoped

var breathing = true;

let woman = "dead";

if (breathing) {
//initialize block scoped variable
let woman = "alive";
console.log(`She is breathing. Woman is currently ${woman}.`);
}

console.log(`She is not breathing. Woman is currently ${woman}.`);


Output:

She is breathing. Woman is alive.
She is not breathing. Woman is dead.

If we were to use var in place of let the output will be different. let us see how-

var woman = "dead";

if (breathing) {
//initialize block scoped variable
let woman = "alive";
console.log(`She is breathing. Woman is currently ${woman}.`);
}

console.log(`She is not breathing. Woman is currently ${woman}.`);


Output:

She is breathing. Woman is alive.
She is not breathing. Woman is alive.

what happened here?? The global variable and the block-scoped variable end up with the same value, dead. Because instead of creating a new local variable with var, it was reassigned the same variable in the same scope, as var does not recognize it to be part of a different, new scope.

Concerning it's duration - Local variables are created when a function starts and when the function is completed, it is deleted

Variable hoisting

Hoisting is a default behavior of JavaScript to move all declarations to the top of the current scope before code execution.

We know that any variable that is declared within a scope belongs to that scope but what goes on in the background is that irrespective of where variables are declared within a particular scope they are all moved to the top of the scope before any part of the code is executed. This is what we call- Hoisting.

JavaScript only hoists declarations and not initialization (assignment). The latter is left in place.

Undefined vs ReferenceError

In JavaScript, and undeclared variable is assigned the value undefined at execution ( it's type is Undefined)

Example-

console.log (x);  //use variable before declaring it
var x = 10;     


Output: undefined because the variable x has not been declared

In JavaScript, a ReferenceError is thrown when trying to access a previously undeclared variable.

Example-

console.log(x);   //use a variable before declaring it
x = 10;      //variable assignment without the var


Output: ReferenceError: x is not defined

Hoisting variables

Normally, JavaScript allows us to both declare and initialize our variable at the same time

Here-

var y = 75;

But do not forget that JavaScript declares first before initializing our variables and no undeclared variable exists until the code assigning them is executed. An undeclared variable becomes a global variable. Due to Hoisting of variables, output results in a console.log, reads undefined and not ReferenceError even in times, we console.log a variable that has not been defined prior to that.

Why? This is because hoisted variables are initialised with a value of undefined first of all.

For Global scoped variables Example:

console.log (h);
var h = 'hoisted';

Output: undefined

We expected this to throw a ReferenceError: h is not defined, as output but instead output is undefined .

Why?

This is what JavaScript code is interpreted as -

var h;
console.log (h);  //output: undefined
h = 'hoisted';

We see that JavaScript has hoisted the variable declaration

For Function scoped Variables Example-

function hoist () {
console.log (h);
var h = 'Hoisting is done'
}
hoist ();

What this is interpreted as -

function hoist () {
var h;
h = 'Hoisting is done'
}

hoist ();       //output: undefined

What we see in the above example is that the variable declaration, var h whose scope is in the function hoist() , is hoisted to the top of the function.

This pitfall in JavaScript answers why we can call a variable or function before assigning it a value or before declaring it.

Summary- points to note

  • An undeclared variable becomes a global variable.
  • A local variable is also known as a function scoped variable
  • It is good practice to avoid using global variables because its value can change at different points and introduce unknown results in the program
  • Hoisting happens to variable declaration and not assignment.
  • Hoisted variables are initialized with the value of undefined.
  • It is Good practice to declare and initialize the variable before using it as it properly delineates what the interpreter should do at runtime.

Happy coding!