Variables and Data types in JavaScript

There are 2 types of variables.

  1. Primitive Types
  2. Reference Types

List of Primitive Types

  1. boolean
  2. number
  3. string
  4. null
  5. undefined

We can check the type of variable using below syntax.
console.log( typeof <variable> );

You can use below methods to change the data types in JavaScript.

  1. toString() – You can convert any object to string using below method.
  2. Number() – You can convert the string into numbers using any of the below methods.
  3. parseInt()
  4. parseFloat()

Reference Types

All variables that point to the object in memory are called as reference types of variables.



All object variables are reference types.  Reference variables actually point to object in memory. That’s why it is called as reference variables.

When you execute below statement, you are not copying the obj2 into obj1. You are just making obj1 to refer to the object pointed to by obj2.
obj1 = obj2

Scope of variables

There are 2 types of variables.

  1. Global variables
  2. Local variables

Scope of the variable is determined based on where it is declared. Suppose you declare one variables – v1 at the top of script. Then it is a global variable. You can access it inside any function or anywhere in the script. Also if you do not use “var” keyword to declare a variable, it becomes global variable.

Local variables can be accessed only inside specific block. For example – If you create one variable inside a function, you will not be able to access it outside of that function.

You may also like...