Menu Close
    Hire us Request quote Reading list Switch to dark mode

    Variable’s scope and Hoisting in JavaScript

    Curious about scope of variables? Wanna understand how actually JS variables work? You must read this blog.

    Variable Scope
    A variable’s scope is the context in which the variable exists. The scope specifies from where you can access a variable and whether you have access to the variable in that context.

    Instead of block-level scope, JS has the function-level scope. What does this mean exactly? let’s go through an example of No block-level scope

    as ( if statement ) has block-level scope so it has access to the global variable and will override codeWrittenBy variable.

    function-level scope

    Here, the function changeName has its own scope and you can create a local variable with the same name. Moreover, if you are not making this variable local then this variable will access to the global variable. see below:-

    Note:- As functionchangeName is a self-invoking function, so we don’t need to call it. Get more knowledge about the self-invoking functions here.

    We should always define the scope of the variables and try to access the local ones. We must try to write functions that may not affect the value of global variables.

    Variable Hoisting

    . . .
    Subscribe Articles

    Just enter your email below to subscribe and receive weekly updates about the most interesting similar articles.

    You need to accept conditions to receive letters.
    You've Subscribed!

    Share article via

    . . .

    All the variables in javascript are hoisted to the top of the function, let’s understand with the help of an example.

    This is because the declaration of the variable name was done on the top of the function and assigned to the value undefined therefore we are getting undefined as the result of the first console.log

    NOTE:- The syntax I have used for string concatenation inside the console.log is known as template literal. Explore more on template literals here.

    functions in JS are hoisted too but there is a difference, functions have their definition but variable have the default value (undefined). That’s why we are able to call any function before their declaration.

    NOTE:- You should try to use anonymous functions most of the time instead of the named functions.
    As a result, you will call the function’s definition into the memory when it is actually needed.

    Thanks for reading me. I hope this blog would help you with a better understanding of the JS variable’s scope and hoisting. Please share your reviews on this, which will support me to write more.

    Until next time. 👋

    . . .


    Add Your Comment

    Be the first to comment.

    Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again