Skip to main content

Command Palette

Search for a command to run...

Scope, Hoisting

Updated
•4 min read•View as Markdown
Scope, Hoisting
D

Hi, I’m Divyanshi, a who loves building products. I’d love to combine my passion for learning with my software development skills to continue building personalized learning products for people.I am systematically organized, meticulous, diligent and conscientious self-starter, able to prioritize, plan and strategize effectively to accomplish multiple tasks and stay calm under pressure.With my prior knowledge and experience of project management and timed-completion, I move forward to discover and learn diversified challenges in the field of technology that just makes me learn more. Due to the diversity of our clients which included technology corporation,medical industry,foundations,I learn to adapt to changing environments,quickly learning new content & collaborate with people with different communication skills. Skills:Html, Css, Jquery, Javascript, Express, Node.js, Webpack, Basic AEM Fundamentals

Scope

The part of the program where a particular identifier such as a variable or a function name is visible or accessible. In JS, we have two different kinds of scope- global scope and function scope.

Global scope- If you define an identifier outside of all of your functions. That means the variables can be accessed everywhere within the program. It is available globally. All functions in your program can access variables defined in global scope.

Function Scope- If an identifier is defined inside of a function, it will be visible everywhere inside that function even inside other functions inside that function.

var a = 1; //a is global variable
function x() {
  var b = 2; //b is function variable accessible everywhere inside x , y and z
  function y() {
    var c = 3; // c is function variable accessible everywhere inside y and z
    function z() {
      var d = 4; // d is function variable accessible everywhere inside z
    }
    z();
  }
  y();
}

x();

Scope overriding or Shadowing

Ex-1
var x = 1;

function addTwo() {
  x = x + 2;
}

addTwo();
x = x + 1;
console.log(x);
Prints : 4

Ex-2
var x = 1;

function addTwo() {
  var x = x + 2;// it should be defined again to avoid shadowing
}

addTwo();
x = x + 1;
console.log(x);
Prints- 2

Global identifiers are a bad idea. They can lead to bad variable names, conflicting variable names, and messy code.

Hoisting

Hoisting is a phenomena in JavaScript by which you can access these variable and functions even before you have initialised it or you have put some value in it, you can access it without any error. Sometimes your JavaScript code will produce errors that may seem counterintuitive at first. Hoisting is another one of those topics that might be the cause of some of these tricky errors you're debugging.

In most programming languages, you have to declare a function before you can call it. Basically the idea is that code's read from top to bottom, so there's no way that we should be able to call this findAverage function, if it hasn't even been declared yet. Like literally, how can we call findAverage when the function is being declared lower than when the call's happening in the code. So this shouldn't work, right ?

findAverage(5,9);
function findAverage(x,y){
var ans=(x+y)/2;
return ans;
}
Print :
7

Well, actually it does and this is because of one really corky feature in JavaScript called hoisting. And it has to do with how JavaScript code is interpreted. Basically before any code is executed, all functions declarations are hoisted to the top of the current scope.

function findAverage(x,y){
var ans=(x+y)/2;
return ans;
}
findAverage(5,9);

I know this is weird, right? Now just to be clear, the code you write is actually not going to change. The code's still going to look exactly how you wrote it. Its just when the code is being interpreted when the function declaration is actually getting hoisted to the top. So still going to look the same and this function is actually going to get called and its going to return back the correct value.

Hoisting also happens with variable declarations, let's take a look at this simple example.

function sayHi(name) {
  console.log(greeting);
}
sayHi();
Prints
Uncaught ReferenceError: greeting is not defined

Because the variable greeting has not been defined or declared anywhere. How can we print out greeting if it doesn't exist? To fix this error, we can declare greeting pretty much anywhere in the function, ultimately we know it's going to get hoisted to the top of the function scope.

sayHi("Julia");

function sayHi(name) {
  console.log(greeting + " " + name);
  var greeting;
}
Prints:
undefined Julia // we haven't given greeting a value
sayHi("Julia");

function sayHi(name) {
var greeting;
  console.log(greeting + " " + name);
greeting = "Hello";
}
Prints :
undefined Julia

This is actually a bug because of hoisting. The variable greeting is getting hoisted to the top of the function scope, but the assignment is staying exactly where it is. Because the variable declaration is getting hoisted to the top. To avoid these bugs, JavaScript programmers usually declare functions at the top of their scripts, and variables at the top of their functions.The code looks and code behaves are consistent to each other.

function sayHi(name) {
  var greeting = "Hello";
  console.log(greeting + " " + name);
}

sayHi("Julia");
Prints :
Hello Julia

What you've learned so far:

  • JavaScript hoists function declarations and variable declarations to the top of the current scope.
  • Variable assignments are not hoisted.
  • Declare functions and variables at the top of your scripts, so the syntax and behavior are consistent with each other.

More from this blog