×

Javascript Data Types

An Overview of JavaScript Data Types

In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in a programming language is quite important, as every programming language has its own predefined data types. For example, JavaScript has its own set of data types.

JavaScript is a client-side scripting language. Java and JavaScript are two entirely different programming languages, and one should not use the term for the other. The essential thing to know is that before learning JavaScript, it's best to start with HTML and CSS since both of them are basic in web development. JavaScript runs in the browser and, therefore, it has been built precisely for the browser environment. It is critical in front-end web development; it allows developers to create dynamic web pages.

Declaring Variables in JavaScript

Declaring a variable in JavaScript is done the following way:

var a = 10;

Look at the above code carefully. If you come from other programming languages like Java, you may notice that it does not explicitly declare the type of the variable. Also, once a variable is assigned with a value, it can be changed.

In Java, the declaration of a variable would appear as follows:

int a = 10;

// Reassignment of the same variable is not permitted

int a = 20; // This is prohibited in strictly typed languages.

When you declare a variable in Java, the compiler is being told that the variable is an integer type. In JavaScript, it's quite different. JavaScript is a dynamically typed language, so you just use the keyword var followed by the variable name. Then the value of the variable will automatically be adjusted by the JavaScript engine to suit the appropriate data type.

Additionally, JavaScript allows for value reassignment with a variable regardless of an existing assignment.

Due to these aspects of JavaScript, it is relatively confusing. Once one pays sufficient attention, these ideas are easily understandable.

Data Types in JavaScript

There are two types of variables in JavaScript-data type and user-defined. So, in sum, there exist five data types in JavaScript which are described in the following:

Number

The number is one of the primitive data types in JavaScript. Of special interest is that JavaScript uses a single data type for numbers. It does not distinguish between float, decimal, or double types like most programming languages.

Code

let n1 = 2;

console.log(n1)

let n2 = 1.3;

console.log(n2)

let n3 = Infinity;

console.log(n3)

let n4 = 'something here too' / 2;

console.log(n4)

Output

JavaScript Data Types

String

The string is one of the most basic data types in JavaScript. It is, in essence, a sequence of characters or a sequence of words. Let's look at the following example.

Code

let s1 = "Hello There";

console.log(s1);


let s2 = 'Single quotes work fine';

console.log(s2);

let s3 = `can embed ${s1}`;

console.log(s3);

Output

JavaScript Data Types

In JavaScript, there is no difference between 'single' quotes and "double" quotes. However, backticks have another functionality; they can be used to embed variables inside them.

At times, JavaScript may misinterpret quotes when they are nested. In such cases, the escape character is employed to ensure proper functionality.

Example: Consider the following example, which illustrates that a single quote can be used within double quotes and vice versa.

Code

let s1 = "Hello There";

console.log(s1);

let s2 = 'Single quotes work fine';

console.log(s2);

let s3= "it's an ice cream parlor";

console.log(s3)

let s4 = `can embed ${s1}`;

console.log(s4);

Output

JavaScript Data Types

Boolean

Boolean is one of the primitive data types in JavaScript. It can take two values: true and false. In JavaScript, Boolean values are used to evaluate conditions. This feature is very helpful in validating different scenarios in the language.

Code

let b1 = true;

console.log(b1); 

let b2 = false;

console.log(b2);

Output

JavaScript Data Types

Undefined

Undefined is a basic data type in JavaScript. It is any variable that can be declared but not assigned any value. Thus, such a variable automatically contains the default value of undefined within JavaScript. In short, it identifies a variable that does not have an assigned value.

Code

let a;

console.log(a);

Output

JavaScript Data Types

Null

In JavaScript, null is a primitive data type. There are times when it is imperative to assign the Null value if a particular value needs to be assigned as deliberately empty. For example, during runtime, there may be some condition that calls for user input, and for such a condition, the Null data type can be used.

Code

let age = null;

console.log(age)

Output

JavaScript Data Types

Non-Primitive Data Types in JavaScript

The non-primitive data types available in JavaScript include both Objects and Arrays. In addition, ECMAScript has added another data type known as Symbol.

Object

The Object data type is a core element of the JavaScript programming language. Objects can be created using object literal syntax, which is defined by key-value pairs.

In order to better understand this concept, one can analyze the following example.

Code

let javaTpoint = {

    type: "Company",

    location: "Noida"

}

console.log(javaTpoint.type)

console.log(javaTpoint.location)

Output

JavaScript Data Types

Arrays

An array is a special object which is defined to hold a sequential list of values, and it can store values of different data types.

Code

let a1 = [1, 2, 3, 4, 5];

console.log(a1);


let a2 = [1, "two", { name: "Object" }, [3, 4, 5]];

console.log(a2);

Output

JavaScript Data Types

Function

A function in JavaScript is a reusable piece of code that is defined specifically to execute a particular task when it is called.

Code

// Defining a function to greet a user

function greet(name) { return "Hello, " + name + "!"; }

// Calling the function

console.log(greet("Alice"));

Output

JavaScript Data Types

Date Object

JavaScript's Date object is designed for date and time management, and it supports the creation, manipulation, and formatting of date values.

Code

// Creating a new Date object for the current date and time

let currentDate = new Date();

// Displaying the current date and time

console.log(currentDate);

Output

JavaScript Data Types

Regular Expression

A Regular Expression (RegExp) in JavaScript is an object which is used to define patterns to search for text within strings.

Code

// Creating a regular expression to match the word "hello"

let pattern = /hello/;

// Testing the pattern against a string

let result = pattern.test("Hello, world!"); // Returns true because "Hello" matches the pattern

console.log(result);

Output

JavaScript Data Types

Conclusion

JavaScript data types are of utmost significance. As JavaScript is a loosely typed language, it gives its smart engine the flexibility to automatically decide the type of variable depending upon its value. Hence, one has to know about data types while learning JavaScript.


Related Topics

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.