Defining variables in JavaScript

Defining variables in JavaScript

A variable in JavaScript is an empty container that can be used to store anything. It can store a number, character(string), Boolean, array or object.

A variable in JavaScript can be declared using var keyword.

var myName = “Rudra”;

 

In the example above, we have created a variable “myName” and have an assigned it a value “Rudra” which is a string. Unlike other programming languages, we don’t have to specify data type for variables in JavaScript. It automatically takes the data type according to the value. Following are the data types supported by JavaScript variables:

Data Type Description Example
Undefined When a variable has not been assigned any value, then it has the value undefined. Undefined is set by JavaScript. var myName;

Here myName has the value undefined.

Null It represents intentional absence of any object value. Unlike undefined, it is assigned to a variable and not set by JavaScript. var tax = null;
Number A numeric digit that is represented without any quote around them. var myMarks = 90;
String It is a collection of characters. It is represented with quote marks. var myName = “Rudramani Pandey”;
Boolean It is true/false value and is written without quotes. It is often used as a flag: to represent if an action is done or not. var myHoliday = true;
Array It is a structure that allows to store multiple values into a single variable. It is represented by
[ ]. It is a list and the position of its items lies between 0 to n.
var mySubjects = [Maths, English, Science, JavaScript]
Object An object is a collection of properties. These properties can be added or removed. A JavaScript object is a mapping between keys and values separated by a colon. It can be created either using object literals i.e. { } or JavaScript keyword new. var employee = {name: “Rudra”, age: 25};

or

var employee = new Object();

employee.name = “Rudra”;

employee.age = 25;

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.