DEV Community 👩‍💻👨‍💻

MurtazaNeher
MurtazaNeher

Posted on

Javascript Variables

JavaScript (JS) is a lightweight, interpreted compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages. In this blog I will discuss the variables used in JavaScript Language.

Firstly to discuss what actually are variable ? Variables are used to store data values. They are used to contain values which can be used later in the program for different operations and algorithms. A variable can only contain one value at a time, which can be of any data type. Meaning either a string, number, boolean, array, object, function or null or undefined.

Now, In JavaScript we have 3 keywords for variables, Const, var & let.
While var was the OG variable declaration in JS, const and let were introduced with ES6.

Var : Scope of var can be global or local depending on where is it declared. It means if any variable with var is declared outside function , it can be used throughout the program , while if it is declared inside the function it can only be used inside the function.

Hoisting of Var : Basic meaning of hoist is to pull something up or lift , hoisting is basically a mechanism where declarations of Variables and functions move to top of the scope wherever they are declared before code execution starts.
When var variables are hoisted to top they are initialized with value of "undefined".

Const : Const variable keyword was introduced with ES6 in 2015.
As the name of the keyword suggests const is used to define variables that are constant, it sounds a little bit oxymoronic but in other words we can say Const variables cannot be reassigned, if we declare a const array we can make changes in it but cannot reassign it. It also cannot be re-declared. Since const cannot be redeclared it has to initialized at the time of declaration .Const has a block scope which I will explain with use of a example.

const hello="murtaza";
{
const hello="how";
console.log(hello);
// returns "how"
}
console.log(hello);
//returns "murtaza
Enter fullscreen mode Exit fullscreen mode

Let : Just like const let is also a block scoped variable keyword. Let can be updated but it cannot be re-declared. Just like var and const , let declaration is hoisted to top , while var is initialized with "undefined" , const and let are not initialized,
so if we try a to use a variable with let keyword without initializing it , it will give "Reference Error".

greeting = 4;
console.log(greeting);
let greeting;
// it returns "error: Uncaught ReferenceError: Cannot access 'g' before initialization"
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
3monmon profile image
Simon

The fact that you can declare a function with var AFTER you already used it blows my mind...

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post