What is Scope in Javascript?

kartik2406

Kartik Malik

Posted on November 18, 2018

What is Scope in Javascript?

Scope

While programming we often deal with data, we need to store and manipulate data to derive useful results. In this article, we will learn about variables in Javascript, what is the scope and how it affects your variables.

What is Scope in JS?

The scope is the region within which declared variables are accessible.

There are three levels of scope in JS:

  • Global: Variable is available throughout the program
  • Function level: Variable is available only in the function
  • Block level: Variable is available only in the declared code block. Statements if, for etc are examples of code blocks. You can create a code block without using these statements, just write your code inside {}. Having block level variables is useful since you can reuse the variable name in some other code block without worrying.

Javascript has 3 different keywords that allow you to declare(create) variables.
They are var, let, const. These keywords dictate the variables scope.

The var keyword creates a variable with function level scope if declared inside a function. The let, const keywords create a variable with block level scope. This way you won't accidentally override some global value. The const keyword has another speciality, using it you can create constants which are useful to store messages, math constants etc.

Do note that if you create a variable at top of your function using any of these keywords, it will be global since it's scope is the entire file

You can also create variables without using var, let const keywords. When you do this in strict mode(more on this in a later post) it will throw an error, but in the normal mode, it will create a global variable which will lead to bugs in the future.

What should I use?

To avoid unintentional bugs you should always use let for variables you intend to mutate and const for constants.

How to create variables?

The syntax to create (declare) a varible is = value. In case of let and var, assigning a value at declaration is not compulsary, but for const if you don't assign a value it will throw an error.

There are also few rules which govern the naming of your variables, check this link for more information.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
kartik2406
Kartik Malik

Posted on November 18, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About