Fundamentals of JavaScript
Fundamentals of JavaScript
JavaScript is the most popular programming language in the world, making it a programmer's
great choice. Once you learn JavaScript, it helps you develop great front-end and back-end
software using different JavaScript based frameworks like jQuery, Node.JS, etc.
JavaScript is everywhere, it comes installed on every modern web browser and so to learn
JavaScript, you really do not need any special environment setup. For example, Chrome, Mozilla
Firefox, Safari, and every browser you know as of today, supports JavaScript.
JavaScript helps you create really beautiful and crazy fast websites. You can develop your
website with a console like look and feel and give your users the best Graphical User
Experience.
JavaScript usage has now extended to mobile app development, desktop app development, and
game development. This opens many opportunities for you as JavaScript Programmer.
Due to high demand, there is tons of job growth and high pay for those who know JavaScript.
You can navigate over to different job sites to see what having JavaScript skills looks like in the
job market.
Great thing about JavaScript is that you will find tons of frameworks and Libraries already
developed which can be used directly in your software development to reduce your time to
market.
JavaScript is in all over the world, and companies like Google, Meta, Microsoft, PayPal,
LinkedIn, etc. also use JavaScript.
Furthermore, JavaScript has more than 1.5 lakh libraries. It is also growing.
A huge community of JavaScript is available on the internet with students, developers, and
mentors. So anyone can easily get support.
JavaScript Applications
As mentioned before, JavaScript is one of the most widely used programming languages (Front-
end as well as Back-end). It has its presence in almost every area of software development. I'm
going to list few of them here:
Client side validation − This is really important to verify any user input before submitting it to
the server and JavaScript plays an important role in validating those inputs at front-end itself.
Manipulating HTML Pages − JavaScript helps in manipulating HTML page on the fly. This
helps in adding and deleting any HTML tag very easily using JavaScript and modify your HTML
to change its look and feel based on different devices and requirements.
User Notifications − You can use JavaScript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
Back-end Data Loading − JavaScript provides Ajax library which helps in loading back-end
data while you are doing some other processing. This really gives an amazing experience to your
website visitors.
Presentations − JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-
based slide presentation.
Server Applications − Node JS is built on Chrome's JavaScript runtime for building fast and
scalable network applications. This is an event based library which helps in developing very
sophisticated server applications including Web Servers.
Machine learning − Developers can use the ML5.js library to complete the task related to
machine learning.
Game Developments − JavaScript contains multiple libraries and NPM packages to design
graphics for the game. We can use HTML, CSS, and JavaScript with libraries to develop the
games.
Mobile applications − We can use frameworks like React Native to build feature-rich mobile
applications.
Internet of Things (IoT) − JavaScript is used to add functionality to devices like smartwatches,
earbuds, etc.
Data visualization − JavaScript contains the libraries like D3.js to visualize the data efficiently.
The D3.js is also used to prepare high-quality charts to visualize the data.
Cloud computing − We can use JavaScript in serverless computing platforms like Cloudflare
and AWS lambda to write and deploy functions on the cloud.
This list goes on, there are various areas where millions of software developers are happily using
JavaScript to develop great websites and other software.
Basic JavaScript Example
Below is a basic JavaScript example that will print "Getting started with JavaScript tutorial"
on the webpage. You can edit this example and execute it by clicking on the " Edit & Run"
button.
<script>
document.write("Getting started with JavaScript tutorial");
</script>
History of JavaScript
JavaScript is developed by Brendan Eich, a computer scientist and programmer at Netscape
Communications Corporation. The initial name of the JavaScript was the 'Mocha'. After that, it changed
to 'LiveScript', and then 'JavaScript'.
Between 1996 and 1997, the European Computer Manufacturers Association (ECMA) standardized
JavaScript. After that, 3 revisions of the JavaScript have been done.
In ES5 (2009), Node.js was introduced to use JavaScript as a server-side language. The ES6 (2015) was a
significant revision of JavaScript, introducing advanced features into JavaScript.
Currently, JavaScript has reached the version ES14. ES14 (ECMAScript 2023) the 14th version, was
released in June 2023.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML but can include programs that interact with the user,
control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts.
For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form
field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid they
would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other
actions that the user initiates explicitly or implicitly.
The Popular client-side libraries for JavaScript development are ReactJS, NextJS, Vue JS, Angular JS,
etc.
Server-Side JavaScript
In the early days, JavaScript was used for front-end development to add behaviors to HTML pages. Since
2009, JavaScript is also used as a server-side programming language to build scalable and dynamic web
applications.
Node.js is one of the best and most popular JavaScript runtime environments for building the server of
applications using JavaScript.
Using Node.js, we can execute the JavaScript code outside the browser and manage the server task. The
server tasks can be an interaction with the database, APIS, file handling, or maybe network
communication. Due to the event-driven architecture of Node.js, it is faster than other server-side
programming languages.
Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the server. This
saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have
forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over them with a
mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and
sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important
features −
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reasons.
JavaScript cannot be used for networking applications because no such support is available.
JavaScript doesn't have any multi-threading capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.
JavaScript Features
JavaScript is a highly popular and widely-used programming language for web development. It has a
variety of features that make it powerful and flexible. Some of these features include being dynamic,
lightweight, interpreted, functional, and object-oriented.
Many open-source JavaScript libraries are available, facilitating the utilization of JavaScript in both
frontend as well as backend development. Let's highlight some of the key features of JavaScript.
1.Easy Setup
We don’t need a particular editor to start writing the JavaScript code. Even anyone can write JavaScript
code in Notepad. Also, JavaScript can be executed in the browser without any interpreter or compiler
setup.
You can use the <script > tag to add JavaScript in the HTML file. However, it also allows you to add
JavaScript to the web page from the external JavaScript file, having '.js' extension.
2. Browser Support
All browsers support JavaScript, as all modern browser comes with the built-in JavaScript execution
environment.
However, you can also use the window object to check whether the browser supports JavaScript or its
particular feature.
3. Dom Manipulation
JavaScript allows developers to manipulate the webpage elements. Also, you can control the browser.
It contains the various methods to access the DOM elements using different attributes and allows to
customize the HTML elements.
4. Event Handling
JavaScript allows you to handle the events used to interact with the web page.
For example, you can detect the mouse click on a particular HTML element using JavaScript and interact
with the HTML element.
Some other events also exist, like detecting the scrolling behavior of web page, etc. We will explore all
events in the JavaScript events chapter.
5. Dynamic Typing
JavaScript decides the type of variables at runtime. So, we dont need to care about variable data type
while writing the code, providing more flexibility to write code.
Also, you can assign the values of the different data types to a single variable. For example, if you have
stored the number value of a particular variable, you can update the variables value with the string.
6. Functional Programming
JavaScript supports the functional programming. In JavaScript, you can define the first-class function,
pure functions, closures, higher-order functions, arrow funcitons, function expresions, etc.
It mostly uses the functions as a primary building blocks to solve the problem.
7. Cross-platform Support
Each operating system and browser support JavaScript. So, it is widely used for developing websites,
mobile applications, games, desktop applications, etc.
8. Object-oriented Programming
JavaScript contains the classes, and we can implement all object-oriented programming concepts using
its functionality.
It also supports inheritance, abstraction, polymorphism, encapsulation, etc, concepts of Object-oriented
programming.
9. Built-in Objects
JavaScript contains built-in objects like Math and Date. We can use a Math object to perform
mathematical operations and a Date object to manipulate the date easily.
However, you can also manipulate the functionality of the built-in object.
10. Object Prototypes
In JavaScript, everything is an object. For example, array, function, number, string, boolean, set, map,
etc. are objects.
Each object contains the prototype property, which is hidden. You can use the prototype property to
achive inheritance or extend the functionality of class or object, by other objects functionality.
11. Global Object
JavaScript contains the global object to access the variables which are available everywhere.
To access global variables in the browser, you can use the window object, and in Node.js, you can use the
'global' keyword to access global variables.
Recently, global This keyword is introduced to access the global variables, and which is supported by the
most runtime environments.
12. Built-in Methods
JavaScript also contains the built-in methods for each object. Developers can use the built-in methods to
write efficient and shorter codes.
For example, the Array object contains the filter() method to filter array elements and the sort() method
to sort the array. The String object contains the replace() method to replace text in the string,
the trim() method to remove whitespaces from the string, etc.
13. Modular Programming
JavaScript allows you to write the code in different modules and connect them with the parent module. So
developers can write maintainable code.
By writing the code in a separate module, you can reduce the complexity of the code and reuse each
module whenever you require.
14. JSON
JSON stands for JavaScript object notation. It is a widely used data format to exchange data between
two networks. For example, server and client.
JavaScript also supports the JSON format to store the data.
15. Asynchronous Programming
JavaScript is a single-threaded programming language. To execute your code faster, you can
use asynchronous programming.
You can use promises in JavaScript to write asynchronous code, allowing us to handle multiple tasks
asynchronously.
16. Event-driven Architecture
The event-driven architecture of JavaScript allows developers to create interactive and responsive web
applications by handling a large user base concurrently.
Due to the vast features and applications of JavaScript, the front end of Facebook is built on JavaScript.
Netflix is built using the ReactJS framework of JavaScript. Similarly, Amazon, PayPal, Airbnb, LinkedIn,
Twitter, etc., are also built using JavaScript.
17. Server-side Support
The Node.js runtime environment of JavaScript is widely used to create the backend of the application, as
javaScript can also be used to create servers. It allows you to create a scalable backend for the
application.
JavaScript Placement in HTML File
There is flexibility to place JavaScript code anywhere in an HTML document. However, the
most preferred ways to include JavaScript in an HTML file are as follows −
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
You can follow the syntax below to add JavaScript code using the script tag.
JavaScript Syntax
JavaScript syntax comprises a set of rules that define how to construct a JavaScript code. JavaScript can
be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags
in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes
Language −This attribute specifies what scripting language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of
this attribute.
Type −This attribute is what is now recommended to indicate the scripting language in use and its value
should be set to "text/javascript". JavaScript has become default lannguage in HTML5, and modern
browsers, so now adding type is not required.
Open Compiler
Hello World!
JavaScript Values
In JavaScript, you can have two types of values.
JavaScript Literals
<html>
<body>
<script>
document.write(10); // Number Literal
document.write("<br />"); // To add line-break
document.write("Hello"); // String Literal
</script>
</body>
</html>
JavaScript Variables
var
let
const
You can use the assignment operator (equal sign) to assign values to the variable.
In the below code, variable a contains the numeric value, and variable b contains the text (string).
<html>
<body>
<script>
let a = 5; // Variable Declaration
document.write(a); // Using variable
document.write("<br>");
let b = "One";
document.write(b);
</script>
</body>
</html>
5
One
<script>
var1 = 10
var2 = 20
</script>
But when formatted in a single line as follows, you must use semicolons −
<script>
var1 = 10; var2 = 20;
</script>
It is a good programming practice to use semicolons.
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
In the code below, we compare the time and Time strings, which returns false.
Open Compiler
<html>
<body>
<script>
let a = "time";
let b = "Time";
document.write("a == b? " + (a == b));
</script>
</body>
</html>
a == b? false
Care should be taken while writing variable and function names in JavaScript.
JavaScript Keywords
JavaScript contains multiple keywords which we can use for a particular task. For example, the
function keyword can be used to define the function. The let, var, and const keywords can be
used to define variables.
Lets understand the use of the keyword via the example below.
Example
In this example, we used the function keyword to define the function. We used the var keyword
inside the function to define the sum variable.
Also, we used the let and const keywords outside the function to define two variables and
initialize them with values. After that, we called the function using the function name and passed
variables as an argument.
<html>
<body>
<script>
function getSum(first, second)
{
var sum = first * second;
document.write("The product of " + first + " and " + second + " is " + sum);
}
let first = 3;
const second = 4;
getSum(first, second);
</script>
</body>
</html>
JavaScript Identifiers
In JavaScript, identifiers are the name of variables, functions, objects, etc.
<script>
let p = 90;
</script>
<script>
function test() {
}
</script>
Here are the rules which you should follow to define valid identifiers.
Identifiers should always start with the alphabetical characters (A-Z, a-z), $(dollar sign), or _
(underscore).
It shouldn’t start with digits or hyphens.
The identifier can also contain digits except for the start of it.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-
line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
Example
<script>
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
</script>
Operators in JavaScript
JavaScript contains various arithmetic, logical, bitwise, etc. operators. We can use any operator
in JavaScript, as shown in the example below.
Example
In this example, we have defined var1 and va2 and initialized them with number values. After
that, we use the * operator to get the multiplication result of var1 and var2.
<html>
<body>
<script>
var1 = 10
var2 = 20
var3 = var1 * var2;
var4 = 10 + 20;
document.write(var3, " " ,var4);
</script>
</body>
</html>
200 30
Expressions in JavaScript
You can create expressions in JavaScript by combining the variable, values, and operators.
10 + 20;
a * b;
c / 2;
Example
In the below code, we have used the assignment and arithmetic expressions.
<html>
<body>
<script>
let a = 10;
let b = 2;
c = 10
d = 12
e=8
Using document.write()
In JavaScript, the simplest way to print "Hello World" is to use document.write() method. The
document.write() method writes the content (a string of text) directly to the HTML document or web
page. Lets look at the following −
<script>
document.write("Hello World)
</script>
We should write the document.write() within the <script> and </script> tags. We can place the <script>
inside the <head> or <body> section.
Example
Let's try to write a JavaScript program that prints the "Hello World!" to the document or web page. In the
below program, we placed the JavaScript code within the <head> section. You can try to put the
JavaScript part inside the <body> section and execute the program.
Open Compiler
<html>
<head>
<script>
document.write("Hello World");
</script>
</head>
<body>
</body>
<html>
The alert() is a window method that instruct the browser to display an alert box with the message. We can
write alert without passing any message to it.
<script>
alert("Hello World")
</script>
We can write alert() method as window.alert(). As window object is a global scope object, we can skip
the "window" keyword.
Example
Let's try an example showing "Hello World" in the alert box. Try to execute the program by putting the
<script> part within the <body> section.
Open Compiler
<html>
<head>
<script>
alert("Hello World");
</script>
</head>
<body>
</body>
<html>
Using console.log()
The console.log() is a very convenient method to print the message to web Console. It is very useful to
debug the JavaScript codes in the browsers. Let's look at the simple application of the console.log() to
print the "Hello World" to the web console.
<script>
Console.log("Hello World")
</script>
We can use the console.log to print strings or JavaScript objects. Here in above code snippet, we have
passed "Hello World" as a string argument to the console.log() method.
Example
<html>
<head>
<script>
console.log("Hello World");
</script>
</head>
<body>
<p> Please open the console before clicking "Edit & Run" button </p>
</body>
<html>
Hello World
Using innerHTML
The innerHTML property of an HTML element defines the HTML content of the element. We can use
this property to display the Hello World message. By changing the innerHTML property of the element,
we can display the message in HTML document or webpage.
To use innerHTML property of an element, we need to access that element first. We can use
document.getElementById() method to access the element. Let's look at a complete example.
Example
In the example below, we define a div element with id, "output". We access this element using the
document.getElementById("output"). Then we change the innerHTML property and display our message,
"Hello World".
<html>
<head>
<title>Using innerHTML property</title>
</head>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML = "Hello World";
</script>
</body>
<html>
JavaScript Variables
JavaScript variables are used to store data that can be changed later on. These variables can be thought of
as named containers. You can place data into these containers and then refer to the data simply by naming
the container.
Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the
variables in 4 ways −
<script>
Money = 10;
Name = "tutorialspoint";
</script>
Furthermore, you can use the var keyword to declare the variables as shown below.
<script>
var money;
var name;
</script>
You can also declare multiple variables with the same var keyword as follows −
<script>
var money, name;
</script>
Variable Initialization using the Assignment Operator
Storing a value in a variable is called variable initialization. You can initialize a variable at the time of
creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script>
var name = "Ali";
var money;
money = 2000.50;
</script>
Note: Use the var keyword only for declaration or initialization, once for the life of any variable name in
a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type.
Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of
value the variable will hold.
The value type of a variable can change during the execution of a program and JavaScript takes care of it
automatically.
<script>
var num = 765; // Number
var str = "Welcome"; // String
var bool = false; // Boolean
</script>
You will learn data types in detail in JavaScript Data Types chapter.
Here are some rules for the naming of the identifiers in JavaScript −
Valid characters − In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like
underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
Case sensitivity − Variable names are case sensitive. It means Name and name are different identifiers.
Unicode support − The identifiers can also contain the Unicode. So, developers may define variables in any language.
Reserve keywords − You should not use any of the JavaScript reserved keywords as a variable name. For
example, break or boolean variable names are not valid. Here, we have given a full list of the JavaScript revered keywords.
Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any
identifier with the digit.
Open Compiler
<html>
<head>
<title> Variables in JavaScript </title>
</head>
<body>
<script>
var _abc = "Hi!";
var $abc = "Hello!";
// var 9abc = "Bye!"; // This is invalid
document.write("_abc " + _abc + "<br>");
document.write("$abc = " + $abc + "<br>");
</script>
</body>
</html>
_abc Hi!
$abc = Hello!
Open Compiler
<html>
<body>
<script>
var num;
document.write("The value of num is: " + num + "<br/>");
</script>
</body>
</html>
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always
local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local
variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into
the following example.
Example
In the example below, we have defined the variable named myVar outside the function and initialized it with the 'global' value.
Also, we have defined the variable with the same identifier inside the checkscope() function and initialized it with the 'local'
value.
We print the myVar variable's value inside the function. So, the local variable takes preference over the global variable and prints
the 'local' in the output.
Open Compiler
<html>
<head>
<title> JavaScript Variable Scope Example</title>
</head>
<body onload = checkscope();>
<script>
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
</body>
</html>
local
Example
In the example below, we have defined the variables without using the var keyword. The name variable contains the value of the
string type, and the number variable contains the value of the float data type.
When we define the variables without using any keyword, JavaScript considers them global variables and can use them anywhere
inside the code.
Open Compiler
<html>
<head>
<title> Variables without var keyword </title>
</head>
<body>
<script>
name = "tutorialspoint"; // String type variable
number = 10.25; // Number type variable
document.write("name = " + name + ", number = " + number + "<br>");
</script>
</body>
</html>
Also, the identifier doesn't lose the previous value if we declare the variable using the var keyword with the value and re-declare
the same identifier without initialization. Lets understand it via the example below.
Example
In the example below, we have declared the age variable and initialized it with 10. Again, we have declared the age variable but
havent initialized it.
Still, it prints 10 in the output because it doesnt lose the previous initializations value. However, if we update the value of the age
variable, it successfully updates it.
Open Compiler
<html>
<head>
<title> Variables with var keyword </title>
</head>
<body>
<script>
var age = 10;
var age;
document.write("age = " + age + "<br>");
</script>
</body>
</html>
age = 10
JavaScript Data Types
Data types in JavaScript referes to the types of the values that we are storing or working with. One of the most fundamental
characteristics of a programming language is the set of data types it supports. These are the type of values that can be
represented and manipulated in a programming language.
JavaScript data types can be categorized as primitive and non-primitive (object). JavaScript (ES6 and higher) allows you to work
with seven primitive data types −
Strings of text e.g. "This text string" etc.
Numbers, eg. 123, 120.50 etc.
Boolean e.g. true or false.
null
undefined
BigInt
Symbol
BigInt and Symbol are introduced in ES6. In ES5, there were only five primitive data types.
In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in
detail in a separate chapter.
Object
Array
Date
Here, the JavaScript engine converts the second operand to a string and combines it using the '+' operator rather than adding
them.
JavaScript String
In JavaScript, the string is a sequence of characters and can be created using 3 different ways given below −
Example
In the example below, we have created strings using single quotes, double quotes, and backticks. In the output, it prints the same
result for all 3 strings.
Open Compiler
<html>
<head>
<title> JavaScript string </title>
</head>
<body>
<script>
let str1 = "Hello World!"; // Using double quotes
let str2 = 'Hello World!'; // Using single quotes
let str3 = `Hello World!`; // Using backticks
document.write(str1 + "<br>");
document.write(str2 + "<br>");
document.write(str3 + "<br>");
</script>
</body>
</html>
JavaScript Number
A JavaScript number is always stored as a floating-point value (decimal number).
JavaScript does not make a distinction between integer values and floating-point values.
JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
Example
In the example below, we demonstrate JavaScript numbers with and without decimal points.
Open Compiler
<html>
<head>
<title> JavaScript number </title>
</head>
<body>
<script>
let num1 = 10; // Integer
let num2 = 10.22; // Floating point number
document.write("The value of num1 is " + num1 + "<br/>");
document.write("The value of num2 is " + num2);
</script>
</body>
</html>
Example (Exponential notation of numbers)
JavaScript also support exponential notaion of numbers. We have explained this in the below example code −
Open Compiler
<html>
<head>
<title> JavaScript number Exponential notation </title>
</head>
<body>
<script>
let num1 = 98e4; // 980000
let num2 = 98e-4; // 0.0098
document.write("The value of num1 is: " + num1 + "<br/>");
document.write("The value of num2 is: " + num2);
</script>
</body>
</html>
JavaScript Boolean
In JavaScript, the Boolean data type has only two values: true or false.
Open Compiler
<html>
<head>
<title> JavaScript Boolean </title>
</head>
<body>
<script>
let bool1 = true;
let bool2 = false;
document.write("The value of the bool1 is " + bool1 + "<br/>");
document.write("The value of the bool2 is " + bool2 + "<br/>");
</script>
</body>
</html>
JavaScript Undefined
When you declare a variable but don't initialize it, it contains an undefined value. However, you can manually assign an
undefined value to the variable also.
Open Compiler
<html>
<head>
<title> JavaScript Undefined </title>
</head>
<body>
<script>
let houseNo; // Contains undefined value
let apartment = "Ajay";
apartment = undefined; // Assigning the undefined value
document.write("The value of the house No is: " + houseNo + "<br/>");
document.write("The value of the apartment is: " + apartment + "<br/>");
</script>
</body>
</html>
JavaScript Null
When any variable's value is unknown, you can use the null. It is good practice to use the null for the empty or unknown value
rather than the undefined one.
Open Compiler
<html>
<head>
<title> JavaScript null </title>
</head>
<body>
<script>
let houseNo = null; // Unknown house number
let apartment = "B-2";
appartment = null; // Updating the value to null
document.write("The value of the houseNo is: " + houseNo + "<br/>");
document.write("The value of the apartment is: " + apartment + "<br/>");
</script>
</body>
</html>
JavaScript Bigint
JavaScript stores only 64-bit long floating point numbers. If you want to store a very large number, you should use the Bigint.
You can create Bigint by appending n to the end of the number.
Open Compiler
<html>
<head>
<title> JavaScript Bigint </title>
</head>
<body>
<script>
let largeNum = 1245646564515635412348923448234842842343546576876789n;
document.write("The value of the largeNum is " + largeNum + "<br/>");
</script>
</body>
</html>
JavaScript Symbol
The Symbol data type is introduced in the ES6 version of JavaScript. It is used to create unique primitive, and immutable values.
The Symbol() constructor can be used to create a unique symbol, and you may pass the string as a parameter of the Symbol()
constructor.
Example
In the example below, we created the sym1 and sym2 symbols for the same string. After that, we compared the value
of sym1 and sym2, and it gave a false output. It means both symbols are unique.
Open Compiler
<html>
<head>
<title> JavaScript Symbol </title>
</head>
<body>
<script>
let sym1 = Symbol("123");
let sym2 = Symbol("123");
let res = sym1 === sym2;
document.write("Is sym1 and Sym2 are same? " + res + "<br/>");
</script>
</body>
</html>
JavaScript Object
In JavaScript, the object data type allows us to store the collection of the data in the key-value format. There are multiple ways
to define the object, which we will see in the Objects chapter.
Example
In the example below, we used the '{}' (Object literals) to create an obj object. The object contains the 'animal' property with the
string value, the 'legs' property with the number value, and the value of the 'color' variable is assigned to the 'hourseColor'
property.
The JSON.stringify() method converts the object to strings and shows it in the output.
Open Compiler
<html>
<head>
<title> JavaScript Object </title>
</head>
<body>
<script>
let color = "Brown";
const obj = {
animal: "Hourse",
legs: 4,
hourseColor: color
}
document.write("The given object is: " + JSON.stringify(obj) + "<br/>");
</script>
</body>
</html>
JavaScript Array
In JavaScript, the array is a list of elements of the different data types. You can create an array using two square brackets '[]' and
insert multiple comma seprated values inside the array.
Open Compiler
<html>
<head>
<title> JavaScript Array </title>
</head>
<body>
<script>
const colors = ["Brown", "red", "pink", "Yellow", "Blue"];
document.write("The given array is: " + colors + "<br/>");
</script>
</body>
</html>
JavaScript Date
You can use the JavaScript Date object to manipulate the date.
Example
In the example below, we used the Date() constructor to create a date. In the output, you can see the current date and time
according to your time zone.
Open Compiler
<html>
<head>
<title> JavaScript Date </title>
</head>
<body>
<script>
let date = new Date();
document.write("The today's date and time is: " + date + "<br/>");
</script>
</body>
</html>
Dynamic Types
JavaScript is a dynamically typed language like Python and Ruby. So, it decides the variable's data type at the runtime but not at
the compile time. We can initialize or reassign the value of any data type to the JavaScript variables.
Example
In the example below, we initialized the first variable with the string value. After that, we updated its values to the number and
boolean value.
Open Compiler
<html>
<head>
<title> JavaScript dynamic data type </title>
</head>
<body>
<script>
let first = "One"; // it is string
first = 1; // now it's Number
document.write("The value of the first variable is " + first + "<br/>");
first = true; // now it's Boolean
document.write("The value of the first variable is " + first + "<br/>");
</script>
</body>
</html>
Example
In the below example, we used the typeof operator to check the data type of the various variables.
Open Compiler
<html>
<head>
<title> typeof operator </title>
</head>
<body>
<script>
let num = 30;
let str = "Hello";
let bool = true;
document.write("The data type of num is: " + typeof num + "<br/>");
document.write("The data type of str is: " + typeof str + "<br/>");
document.write("The data type of bool is: " + typeof bool + "<br/>");
</script>
</body>
</html>
JavaScript Type Conversions
Type Conversions in JavaScript refer to the automatic or explicit process of converting data from one data type to another in
JavaScript. These conversions are essential for JavaScript to perform operations and comparisons effectively. JavaScript
variables can contain the values of any data type as it is a weakly typed language.
Please note that to convert a value to string using "+" operator, one operand should be string.
Open Compiler
<html>
<head>
<title>Implicit conversion to string </title>
</head>
<body>
<script>
document.write("100" + 24 + "<br/>");
document.write('100' + false + "<br/>");
document.write("100" + null+ "<br/>");
document.write("100" + undefined+ "<br/>");
</script>
</body>
</html>
Converting to Number (Implicit conversion)
When you use the string values containing the digits with the arithmetic operators except for the '+' operator, it converts operands
to numbers automatically and performs the arithmetic operation, which you can see in the example below.
Open Compiler
<html>
<head>
<title> Implicit conversion to Number </title>
</head>
<body>
<script>
document.write(('100' / 50) + "<br>");
document.write(('100' - '50') + "<br>");
document.write(('100' * true) + "<br>");
document.write(('100' - false) + "<br>");
document.write(('tp' / 50) + "<br>");
</script>
</body>
</html>
<html>
<head>
<title> Using undefined with a number and boolean value </title>
</head>
<body>
<script>
let num = 100 + undefined; // Prints NaN
document.write("The value of the num is: " + num + "<br>");
num = false * undefined; // Prints NaN
document.write("The value of the num is: " + num + "<br>");
</script>
</body>
</html>
Example
You can use the String() constructor function to convert a value to the string.You can also use typeof operator to check the type
of the resultant value.
Open Compiler
<html>
<head>
<title> Converting to string explicitly </title>
</head>
<body>
<script>
document.write(typeof String(100) + "<br/>");
document.write(typeof String(null)+ "<br/>");
document.write(typeof String(true) + "<br/>");
</script>
</body>
</html>
We can also use the toString() method of Number object to convert number to string.
const num = 100;
num.toString() // converts 100 to '100'
However, you can also use the below methods and variables to convert the string into numbers.
Sr.No Method /
Description
. Operator
3 + It is an unary operator.
Example
You can use the Number() constructor function or unary (+) operator to convert a string, boolean, or any other value to a number.
The Number() function also converts the exponential notation of a number to a decimal number.
Open Compiler
<html>
<head>
<title> Converting to string explicitly </title>
</head>
<body>
<script>
document.write(Number("200") + "<br/>");
document.write(Number("1000e-2") + "<br/>");
document.write(Number(false) + "<br/>");
document.write(Number(null) + "<br/>");
document.write(Number(undefined) + "<br/>");
document.write(+"200" + "<br/>");
</script>
</body>
</html>
Example
You can use the Boolean() constructor to convert values to the Boolean. All false values like 0, empty string, null, undefined,
etc., get converted to false and other values are converted to true.
Open Compiler
<html>
<head>
<title> Converting to string explicitly </title>
</head>
<body>
<script>
document.write(Boolean(100) + "<br/>");
document.write(Boolean(0) + "<br/>");
document.write(Boolean("") + "<br/>");
document.write(Boolean("Hi") + "<br/>");
document.write(Boolean(null) + "<br/>");
</script>
</body>
</html>
Number(date);
OR
date.getTime();
You can use the String() constructor or the toString() method to convert the date into a string.
Follow the syntax below to convert the date into the string.
String(date);
OR
date.toString();
Open Compiler
<html>
<head>
<title> Coverting date to string / number </title>
</head>
<body>
<script>
let date = new Date();
let numberDate = date.getTime();
document.write("The Numeric date is: " + numberDate + "<br/>");
let dateString = date.toString();
document.write("The string date is: " + dateString + "<br/>");
</script>
</body>
</html>