DEV Community

Cover image for Understanding Variables and Data Types in JavaScript
Anoop Rajoriya
Anoop Rajoriya

Posted on

Understanding Variables and Data Types in JavaScript

Welcome to the world of programming. If you are learning programming this is the essential thing you should master. Think you are shifting from current house to new one. You get many cardboard boxes and labeled them like library for books, foot-wears for shoes and slippers etc.

Just like it in the programming there are thing called variables just like you labels and the data types like your stuffs you putting into boxs labeled by there categories.


What variables are and why they are needed

In the computer programming, variables are the named or symbolic container which used to store data values within computer memroy. It act as a placeholder or label for information such as user input, component states or calculation which can be used or updated during the programm execution without that storing, manipulation data whould be nearly impossible.

Varialbes are essential for creating efficient or flexible programms:

  • Flexible and Reusable: instead of hard coding fixed value like 3+5 you can use a+b, allow to use same code for different data inputs.

  • Data Storage and Manipulation: programmes need to remember data like user names, game state, raw data form files. Variables allow developers to use store this in memory so it can be reused later.

  • Readability and Maintainability: using discriptive name make programm easy to read, understand so it can be updated in future reduce errors during debugging.

  • Managing Program Logic: variables used to manage the program flow logic such as using boolean state to decide which part of the code block should be execute during run time.

Note: Always use descirptive names like use user_name or userName instead of only name, for data you can use common naming cases like camelCase, snack_case, PascelCase, and kabab-case etc.

How to declare variables using var, let, and const

Inside a JavaScript "declare" variables just means of creating a box and giving it a name. There are three possible way to do this:

The Old Way

Using var keyword was a original way to declare variables. You seeing it many times in old codebase but modern developers rarly use it because of it's quirky behaviours which some times lead bugs in code.

// Syntax:
var userName;
Enter fullscreen mode Exit fullscreen mode

The Modern Way

There were let and const keywords released in js new version to reduce this quirky behaviours.

Use let when you know the vlaue of the variable need to be change later like playerScore in a game.

// Syntax:
let playerScore = 0;
Enter fullscreen mode Exit fullscreen mode

Use const this is short for constants. It used to declare variables with the fixed value which can not be changed in any cost within the program execution like userDOB.

// Syntax:
const userDOB = 1990;
Enter fullscreen mode Exit fullscreen mode

Note: Always avoid of using var keyword for declaring variables because that can lead potential errors in you code.

Primitive data types

Think when you bring some kitchen grocery, you never put item within wrong container like you never put oil in box or rice in bottle. You can do but naturally we did not do this. Just like it Javascript use proper data types for storing information within computer. There are some common primitive data types:

1. String Data Type

it's a sequence of characters. It's used to store textual informaiton in computer. Strings are immutable meaning it can not be changed after creating, but you can assingned new string to the same variable.

// Syntax:
const userEmail = "something@email.com"
Enter fullscreen mode Exit fullscreen mode

2.Number Data Type

it can be a interger or floating point numbers, JavaScript didn't differentiate between different kids of number it store all them as floating point number. It is also immutable data type. JavaScript also has a special type of numbers infinity and -inifinity both represent mathmetical infinities for positive side or negative side. NaN is also a number type which represent values those are Not a Number.

// Syntax:
const integer = 10;
const floating = 10.550;
const negative = -10;
const infy = infinity;
const negInfy = -infinity;
Enter fullscreen mode Exit fullscreen mode

3. Boolean Data Type

it use to represen true and false values majority used to run specific block of code.

// Syntax:
const isLogin = true;
const isAdmin false;
Enter fullscreen mode Exit fullscreen mode

4. Null Data Type

in JavaScript programmer explicitly use null data type to intenally represent absance of any object value of empty values. It only have one possible value null. The well-knowen quirky or historical bug is that using typeof operator with null give a string of object not null. This behaviour of JavaScript is maintain for backword compatibility to avoid breaking existing websites.

// Syntax:
let data = null
console.log(typof data) // "object"
Enter fullscreen mode Exit fullscreen mode

Truthy & Falsy values

Meaning of Truthy and Falsy is if we convert these values into Boolean Type the truthy values are converted into true and falsy values are converted into false. There are some values treat as falsy values those are:

  • Booelan value false
  • Number zero including 0.0 or -0
  • The big int zero value 0n
  • Empty string "", ''
  • Intentinoal absance of value null
  • Undefined
  • Not a number NaN

Excluding these, all values are treated as a truthy values.

5. Undefined Data Type

It also used to represent absence of a value like null do. Major different is JavaScript automatically assinged undefined to a varialbes has declare but not yet assinged explicitly value.

// Syntax:
let score;
console.log(score) // undefined
Enter fullscreen mode Exit fullscreen mode

Do It Your Self: Open browser go inside console tab in dev tools. Try to declaring some variables with differnet data types and try convert into boolean using ! operator. You understand the concept of truty or falsy values.

What is scope

Scope is the region where variables, function or objects are accessible and visible. It determin how the JavaScript engine looks for the identifires (names) in different part of you code. There are several types of scopes form a heirarchy known as Scope Chain

Scopes visualization with hallway analogy

1. Global Scope

Variables declare outside of any block or function resides in global scope. These variables are accessible for every one in the program. Think it like a light bulb in hallway so every one can see or use it in house.

2. Funciton (Local) Scope

Every function has its own scope. Declaring variables inside function its only accessible within that function, variables not visible outside that funciton or global scope.

3. Block Scope

It introduce in ES6 with the let and const keywords. The variables declared inside the block scope (area inside the curly bracket {}) are only accessible inside, not outside. It include if statement, loops and standalone blocks.

4. Module Scope

When using ES6 modules (via import or export), variables declare inside module are scoped to that specific file. They are not accessible globally or inside any other module unless explicitly exported.

5. Lexical Scope

It is known as Scope Chaining or Static Scope. It means the scope of variables determins by their physical location within sorce code at compile time, not where they are called in run time. When interpreter need to access the specific variable it following scope chain:

  1. It first find in current scope (innermost scope).
  2. If not found, then it move to the its parent scope.
  3. Continue untile it reach to the global scope.
  4. If variable is still not found, a ReferenceError is thrown.

Basic difference between var, let, and const

Each of these keyword has certain purpose and distinct scope. We shall examin the difference between the var, let and consts with example:

Var keyword

Var-declared variables are has function scoped. Which means they are accessible any where inside the function it declared. Here's an example of using var:

function verDeclaration(){
    if(true){
        var x = 10;
    }
    console.log(x) // 10
}
Enter fullscreen mode Exit fullscreen mode

In that example x is declared inside the if statement so it can accessible inside that. But it also accessible inside the entire verDeclaration function.

Let keyword

Let-declared variables has block scope. Which means let declaration limit the variable into block where they are specified. It specifically helpfull to prevent unintentional Hoisting or lowering the scope related errors.

Note: Hoisting is behaviour of JS whre declaration of variable or functions are apeared move to the top of their scope during compilation phase.

Lets see above example with let declaration:

function letDeclaration(){
    if(true){
        let y = 20;
    }
    console.log(y) // ReferenceError: y is not defined
}
Enter fullscreen mode Exit fullscreen mode

Here y is declared with let keyword means it have block scope so it only accessible within the if statement. Try to access y outside of that state will throws an ReferenceError: y is not defined.

Const keyword

Declareing variable with const keyword is also has block scope like let. It primarly helpfull for declaring variables those will not mutate. It also throws an ReferenceErrors if trying to access outside its scope.

Do It Your Self: Learn the way to execute JS code in browser (hint: use html file or console). Declare some variables like name, age, isStudnet. Print them in console use console.log() method. Try to change these values of with let and consts and observe the behaviours.


Understanding difference between let, const, and var is the essential fundation for web development. Eash developer should know these difference for writing bug free code. For learning these concepts i read articles like varialbes in JS, scopes in JS, Difference of let, const, and var,

Top comments (0)