Variables in JavaScript

Like many other programming languages, we can define variables. There are 3 ways to declare variables in Java Scripts.

  • var
  • let
  • const

Var

This is old way to declare variables and in the modern code you will not see anywhere this method and we also recommend not to use this. But in the interview, you may be asked what is the difference between var and let. Even though it is not necessary to use in modern code base, you need to answer this kind of question. Also, it’s better to know what is var for good understand of JavaScript.

Var is non blocked scope that means you can get the values that is declared inside or outside of any function. So mostly programmer will not use this variable declaration.

Example:
var = "any text here"

Let

let was introduced in ES6 and now you can see this in all modern codebase. Unlike Var, this is blocked scope, means you cannot use this outside of a function if you declare it inside of a function. But mostly use the const inside of let unless if you are planning to reassign. But you can use const or let in your JavaScript code.

In let you can declare a variable without storing any data inside it. you can simply assign a variable and later you can reassign any primitive or reference values into it.

Example:
let= "any text here"

Const

Const is also introduced in ES6 and it is the most common way to declare variables in JavaScript or any other frameworks. const is blocked scope so you cannot get the values outside of function if you declare a variable inside. You might get confused initially but slowly you will understand.

By keep practicing you will become master in JavaScript but 90% of beginners will not keep practicing the after learning new code. because beginners will think they already understood everything, but when you attend interview, you might face some trouble. So, keep practicing.

Rules for giving naming variables

You can give any name to a variable but it should start with alphabets, underscore and dollar symbol. Number is allowed in variable declaration but only after the 1st letter in JavaScript. Other than these you are not allowed to use any other characters.


Post a Comment

Previous Post Next Post