0% found this document useful (0 votes)
4 views

Unit 5th Javascript

JavaScript is a lightweight, cross-platform programming language primarily used for web development, enabling both client-side and server-side applications. It features dynamic typing, object-oriented programming, and can be linked to HTML files either internally or externally. JavaScript has various applications, including web development, server applications, and game development, but it also faces limitations such as security risks and performance issues.

Uploaded by

nigjay4411
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 5th Javascript

JavaScript is a lightweight, cross-platform programming language primarily used for web development, enabling both client-side and server-side applications. It features dynamic typing, object-oriented programming, and can be linked to HTML files either internally or externally. JavaScript has various applications, including web development, server applications, and game development, but it also faces limitations such as security risks and performance issues.

Uploaded by

nigjay4411
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

# Introduction to JavaScript

# What is JavaScript?

JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled


programming language. It is also known as the scripting language for webpages. It is
well-known for the development of web pages, and many non-browser environments
also use it.

JavaScript is a weakly typed language (dynamically typed). JavaScript can be used for
Client-side developments as well as Server-side developments. JavaScript is both an
imperative and declarative type of language. JavaScript contains a standard library of
objects, like Array, Date, and Math, and a core set of language elements like operators,
control structures, and statements.

Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML
form and respond to user events such as mouse clicks, form input, and page navigation.
Useful libraries for the client side are AngularJS, ReactJS, VueJS, and so many others.

Server-side: It supplies objects relevant to running JavaScript on a server. For if the


server-side extensions allow an application to communicate with a database, and
provide continuity of information from one invocation to another of the application, or
perform file manipulations on a server. The useful framework which is the most famous
these days is node.js.

Imperative language – In this type of language we are mostly concerned about how it is
to be done. It simply controls the flow of computation. The procedural programming
approach, object, oriented approach comes under this as async await we are thinking
about what is to be done further after the async call.

Declarative programming – In this type of language we are concerned about how it is to


be done; basically, here logical computation requires. Her main goal is to describe the
desired result without direct dictation on how to get it as the arrow function does.
# How to Link JavaScript File in HTML?

JavaScript can be added to HTML file in two ways:

Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the
<script> tag. The <script> tag can either be placed inside the <head> or the <body>
tag according to the requirement.

External JS: We can write JavaScript code in other files having an extension.js and then
link this file inside the <head> tag of the HTML file in which we want to add this code.

Syntax:

<script>
// JavaScript Code
</script>

# History of JavaScript

It was created by Brendan Eich in 1995. He was an engineer at Netscape. It was


originally going to be named LiveScript but was renamed. Unlike most programming
languages, JavaScript language has no concept of input or output. It is designed to run as
a scripting language in a host environment, and it is up to the host environment to
provide mechanisms for communicating with the outside world. The most common host
environment is the browser.

# Features of JavaScript

According to a recent survey conducted by Stack Overflow, JavaScript is the most


popular language on earth. With advances in browser technology and JavaScript having
moved into the server with Node.js and other frameworks, JavaScript is capable of so
much more. Here are a few things that we can do with JavaScript:

 JavaScript was created in the first place for DOM manipulation. Earlier websites
were mostly static, after JS was created dynamic Web sites were made.
 Functions in JS are objects. They may have properties and methods just like other
objects. They can be passed as arguments in other functions.
 Can handle date and time.
 Performs Form Validation although the forms are created using HTML.
 No compiler is needed.
# Applications of JavaScript

 Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.
 Web Applications: With technology, browsers have improved to the extent that a
language was required to create robust web applications. When we explore a map
in Google Maps then we only need to click and drag the mouse. All detailed view is
just a click away, and this is possible only because of JavaScript. It uses Application
Programming Interfaces (APIs) that provide extra power to the code. The Electron
and React are helpful in this department.
 Server Applications: With the help of Node.js, JavaScript made its way from client
to server and Node.js is the most powerful on the server side.
 Games: Not only in websites, but JavaScript also helps in creating games for
leisure. The combination of JavaScript and HTML 5 makes JavaScript popular in
game development as well. It provides the EaseJS library which provides solutions
for working with rich graphics.
 Smartwatches: JavaScript is being used in all possible devices and applications. It
provides a library PebbleJS which is used in smartwatch applications. This
framework works for applications that require the Internet for their functioning.
 Art: Artists and designers can create whatever they want using JavaScript to draw
on HTML 5 canvas, and make the sound more effective also can be used p5.js
library.
 Machine Learning: This JavaScript ml5.js library can be used in web development
by using machine learning.
 Mobile Applications: JavaScript can also be used to build an application for non-web
contexts. The features and uses of JavaScript make it a powerful tool for creating
mobile applications. This is a Framework for building web and mobile apps using
JavaScript. Using React Native, we can build mobile applications for different
operating systems. We do not require to write code for different systems. Write
once use it anywhere!

# Limitations of JavaScript

 Security risks: JavaScript can be used to fetch data using AJAX or by manipulating
tags that load data such as <img>, <object>, <script>. These attacks are called
cross-site script attacks. They inject JS that is not part of the site into the visitor’s
browser thus fetching the details.
 Performance: JavaScript does not provide the same level of performance as offered
by many traditional languages as a complex program written in JavaScript would
be comparatively slow. But as JavaScript is used to perform simple tasks in a
browser, so performance is not considered a big restriction in its use.
 Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, and client and
server-side objects otherwise it would be difficult for them to write advanced
scripts using JavaScript.
 Weak error handling and type checking facilities: It is a weakly typed language as
there is no need to specify the data type of the variable. So wrong type checking is
not performed by compile.
 Why JavaScript is known as a lightweight programming language ?
 JavaScript is considered lightweight due to the fact that it has low CPU usage, is
easy to implement, and has a minimalist syntax. Minimalist syntax as in, has no
data types. Everything is treated here as an object. It is very easy to learn because
of its syntax similar to C++ and Java.
 A lightweight language does not consume much of your CPU’s resources. It doesn’t
put excess strain on your CPU or RAM. JavaScript runs in the browser even though
it has complex paradigms and logic which means it uses fewer resources than
other languages. For example, NodeJs, a variation of JavaScript not only performs
faster computations but also uses fewer resources than its counterparts such as
Dart or Java.
 Additionally, when compared with other programming languages, it has fewer in-
built libraries or frameworks, contributing as another reason for it being
lightweight. However, this brings a drawback in that we need to incorporate
external libraries and frameworks.

# Is JavaScript Compiled or Interpreted or both?

JavaScript is both compiled and interpreted. In the earlier versions of JavaScript, it used
only the interpreter that executed code line by line and shows the result immediately.
But with time the performance became an issue as interpretation is quite slow.
Therefore, in the newer versions of JS, probably after the V8, the JIT compiler was also
incorporated to optimize the execution and display the result more quickly. This JIT
compiler generates a bytecode that is relatively easier to code. This bytecode is a set of
highly optimized instructions.
The V8 engine initially uses an interpreter, to interpret the code. On further executions,
the V8 engine finds patterns such as frequently executed functions, and frequently used
variables, and compiles them to improve performance.

# Objects in Javascript
Objects in JavaScript are the most important data type and form the building blocks for
modern JavaScript. Unlike primitive data types (Number, String, Boolean, null, undefined,
and symbol), which hold a single value, objects can hold multiple values as properties.
This makes objects incredibly useful for grouping related data and operations, leading to
more organized and maintainable code.

# What Are Objects in JavaScript?

In JavaScript, an object is a collection of related data and functions, known as properties


and methods, respectively. Properties are “key: value” pairs that store data, while
methods are functions associated with the object that can manipulate its properties.

Syntax

new Object(value)
Object(value)
let object_name = {
key_name : value,
}

Example:
const o = new Object ();
o.foo = 42;
console.log(o);
// {foo: 42}

Output{ foo: 42 }

Example: In this example “name”, “location”, and “established” are all “keys” and
“Vivekananda School”, “Delhi” and 1971 are values of these keys respectively. Each of
these keys is referred to as properties of the object. An object in JavaScript may also
have a function as a member, in which case it will be known as a method of that object.
Here “displayinfo” is a method of the school object that is being used to work with the
object’s data, stored in its properties.

javascript
let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
displayInfo: function () {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}
school.displayInfo();
Output: Vivekananda School was established in 1971 at Delhi

Objects are more complex and each object may contain any combination of these
primitive data-types as well as reference data-types.

An object is a reference data type. Variables that are assigned a reference value are
given a reference or a pointer to that value. That reference or pointer points to the
location in memory where the object is stored. The variables don’t actually store the
value.

Loosely speaking, objects in JavaScript may be defined as an unordered collection of


related data, of primitive or reference types, in the form of “key: value” pairs. These
keys can be variables or functions and are called properties and methods, respectively,
in the context of an object.

An object can be created with figure brackets {…} with an optional list of properties. A
property is a “key: value” pair, where a key is a string or a symbol (also called a
“property name”), and the value can be anything including numbers, strings, booleans,
functions, arrays, or even other objects. .

# Objects as Reference Types

Objects in JavaScript are reference types. This means that when you assign an object to
a variable, the variable holds a reference (or pointer) to the memory location where the
object is stored, not the actual object itself.

# JavaScript Object Properties

Properties are defined as key-value pairs, where the key is a string or symbol and the
value can be any data type, including numbers, strings, booleans, functions, arrays, or
other objects.

Example: Below is the example of object properties.

javascript

let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
20: 1000,
displayInfo: function () {
console.log (`The value of the key 20 is ${school['20']}`);
}
}
school.displayInfo();

Output: The value of the key 20 is 1000

But more on the bracket notation later. Property names can also be strings with more
than one space separated words. In which case, these property names must be enclosed
in quotes:

let school = {
"School name": "Vivekananda School",
}

Example: In this example, we are accessing ‘Vivekananda’ from ‘Vivekananda School’.

javascript

// Bracket notation
let school = {
name: 'Vivekananda School',
displayInfo: function () {
console.log (`${school.name.split(' ')[0]}`);
}
}
school.displayInfo(); // Vivekananda

Output: Vivekananda
In the above code, we made use of bracket notation and also split method provided by
JavaScript which you will learn about in the strings article.

# Inherited Properties

JavaScript objects can inherit properties from their prototypes. These are known as
inherited properties. To check if a property is an object’s own property (not inherited),
you can use the hasOwnProperty method.

Example:

JavaScript

let school = {
"name": "Vivekananda School" };
console.log(school.hasOwnProperty("name"));
console.log(school.hasOwnProperty("toString"));

Output:

true
false

# Property Attributes

In JavaScript, each property has attributes that define its behavior:

 value: The property’s value.


 writable: When true, the property’s value can be changed
 enumerable: When true, the property can be iterated over by “for-in” enumeration.
Otherwise, the property is said to be non-enumerable.
 configurable: If false, attempts to delete the property, change the property to be
an access-or property, or change its attributes (other than [[Value]], or changing
[[Writable]] to false) will fail.

# Example of Property Attributes:

javascript

let person = {
name: "John"
};
Object.defineProperty(person, 'name', {
writable: false,
enumerable: true,
configurable: false
});

# Accessing Object Members

Object members (properties or methods) can be accessed using dot notation or bracket
notation.

(objectName.memberName);

Example: Below is the example of accessing object members.

javascript
let school = {
name: "Vivekanada",
location: "Delhi",
established: 1971,
20: 1000,
displayinfo : function () {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}

console.log(school.name);

console.log(school.established);

Output: Vivekanada
1971

# Bracket Notation

Syntax:

objectName["memberName"]

Example: Below is the example of Bracket Notation.

javascript

let school = {
name: "Vivekanada School",
location: "Delhi",
established: 1995,
20: 1000,
displayinfo: function () {
document.write(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}

// Output: Vivekanada School


console.log(school['name']);

// Output: 1000
console.log(school ['20']);

Output:

Vivekanada School
1000

Unlike dot notation, the bracket keyword works with any string combination, including,
but not limited to multi-word strings.

somePerson.first name // invalid


somePerson["first name"] // valid

Unlike dot notation, bracket notation can also contain names that are the results of any
expressions variables whose values are computed at run-time.

let key = "first name" somePerson[key] = "Name Surname"

Similar operations are not possible while using the dot notation.

# Iterating Over All Keys of an Object

To iterate over all enumerable properties of an object, you can use the for…in loop. This
loop will iterate over both the object’s own properties and any enumerable properties it
has inherited.

Example: Below is the example.

javascript

let person = {
gender: "male"
}

let person1 = Object.create(person);


person1.name = "Adam";
person1.age = 45;
person1.nationality = "Australian";

for (let key in person1) {


// Output: name, age, nationality
// and gender
console.log(key);
}
Output:

name
age
nationality
gender

# Deleting Properties

To delete a property of an object, use the delete operator. Note that you cannot delete
inherited properties or non-configurable properties.

Example: Below is the example of deleting properties.

javascript

let obj1 = {
propfirst : "Name"
}

// Output : Name
console.log(obj1.propfirst);
delete obj1.propfirst

// Output : undefined
console.log(obj1.propfirst);

Output

Name
undefined

Example: In this example, we cannot delete inherited properties or non-configurable


properties

javascriptlet obj1 = {
propfirst : "Name"
}
// Output : Name
console.log(obj1.propfirst)
let obj2 = Object.create(obj1);

// Output : Name
console.log(obj2.propfirst);

// Output : true.
console.log (delete obj2.propfirst);

// Surprisingly Note that this will return true


// regardless of whether the deletion was successful

// Output : Name
console.log(obj2.propfirst);

Output:

Name
Name
true
Name

# JavaScript Events
JavaScript Events are actions or occurrences that happen in the browser. They can be
triggered by various user interactions or by the browser itself.

Common events include mouse clicks, keyboard presses, page loads, and form
submissions. Event handlers are JavaScript functions that respond to these events,
allowing developers to create interactive web applications.

Syntax:

<HTML-element Event-Type = "Action to be performed">

# Common JavaScript Events

 Onclick: Triggered when an element is clicked.


 Onmouseover: Fired when the mouse pointer moves over an element.
 Onmouseout: Occurs when the mouse pointer leaves an element.
 Onkeydown: Fired when a key is pressed down.
 Onkeyup: Fired when a key is released.
 Onchange: triggered when the value of an input element changes.
 Onload: Occurs when a page has finished loading.
 Onsubmit: Fired when a form is submitted.
 Onfocus: Occurs when an element gets focus.
 Onblur: Fired when an element loses focus.

1. JavaScript Events Examples

Example 1: Here, we will display a message in the alert box when the button is clicked
using onClick() event. This HTML document features a button styled to appear in the
middle of the page. When clicked, the button triggers the `hiThere()` JavaScript function,
which displays an alert box with the message “Hi there!”.

html

<!doctype html>
<html>

<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>

<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>

</html>

Output:
Example 2: Here, we will change the color by pressing UP arrow key using onkeyup()
event. This code defines a JavaScript function `changeBackground()` that changes the
background color of an input box when the up-arrow key is pressed. RGB color values are
incremented with each key press, cycling through colors.

html

<!doctype html>
<html>

<head>
<script>
let a=0;
let b=0;
let c=0;
function changeBackground() {
let x=document.getElementById('bg');
x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;
c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>

<body>
<h4>The input box will change color when UP arrow key is pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write something"
style="color:#fff">
</body>

</html>
Output:

2. JavaScript Event Handlers

JavaScript event handlers are functions that are executed in response to specific events
occurring in the browser.

They can be attached to HTML elements using event attributes like onclick,
onmouseover, etc., or added dynamically using the addEventListener() method in
JavaScript.

Example: Here’s an example of a JavaScript event handler attached to an HTML button


element using the onclick attribute. This code demonstrates an event handler attached
to a button element. When the button is clicked, the `myFunction()` JavaScript function
is invoked, triggering an alert box displaying “Button clicked!”.

HTML

<!DOCTYPE html>
<html>
<head>
<title>Event Handler Example</title>
</head>
<body>

<button onclick="myFunction()">Click me</button>

<script>
// JavaScript function to handle the click event
function myFunction() {
alert("Button clicked!");
}
</script>

</body>
</html>
Output:

# Functions in JavaScript
A function in JavaScript is a reusable block of code that performs a specific task. You
define it once, and then you can run (or “call”) it whenever you need that task done in
your program.

A JavaScript function runs when it is “called” by some part of your code.

Syntax: The basic syntax to create a function in JavaScript is shown below.

function functionName(Parameter1, Parameter2, ...)


{
// Function body
}

To create a function in JavaScript, we have to first use the keyword function, separated
by the name of the function and parameters within parenthesis. The part of the function
inside the curly braces {} is the body of the function.

In javascript, functions can be used in the same way as variables for assignments, or
calculations.

# Why Functions?

 Functions can be used multiple times, reducing redundancy.


 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.

# Function Invocation

The function code you have written will be executed whenever it is called.

 Triggered by an event (e.g., a button clicks by a user).


 When explicitly called from JavaScript code.
 Automatically executed, such as in self-invoking functions.
# Function Definition

Before, using a user-defined function in JavaScript we have to create one. We can use
the above syntax to create a function in JavaScript.

A function definition is sometimes also termed a function declaration or function


statement. Below are the rules for creating a function in JavaScript:

 Every function should begin with the keyword function followed by,
 A user-defined function name that should be unique,
 A list of parameters enclosed within parentheses and separated by commas,
 A list of statements composing the body of the function enclosed within curly
braces {}.

Example: This example shows a basic declaration of a function in javascript.

JavaScript

function calcAddition(number1, number2) {


return number1 + number2;
}
console.log(calcAddition(6,9));

Output: 15

In the above example, we have created a function named calcAddition, this function
accepts two numbers as parameters and returns the addition of these two
numbers.Accessing the function with just the function name without () will return the
function object instead of the function result.

# There are three ways of writing a function in JavaScript:

1.Function Declaration: It declares a function with a function keyword. The function


declaration must have a function name.

Syntax:

function geeksforGeeks(paramA, paramB) {


// Set of statements
}

2.Function Expression

It is similar to a function declaration without the function name. Function expressions


can be stored in a variable assignment.
Syntax:

let geeksforGeeks= function(paramA, paramB) {


// Set of statements
}

Example: This example explains the usage of the Function expression.

JavaScript

const square = function (number) {


return number * number;
};
const x = square (4); // x gets the value 16
console.log(x);

Output: 16

3.Functions as Variable Values

Functions can be used the same way as you use variables.

Example:

// Function to convert Fahrenheit to Celsius


function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}

// Using the function to convert temperature


let temperatureInFahrenheit = 77;
let temperatureInCelsius = toCelsius(temperatureInFahrenheit);
let text = "The temperature is " + temperatureInCelsius + " Celsius";

# Arrow Function:

Arrow Function is one of the most used and efficient methods to create a function in
JavaScript because of its comparatively easy implementation. It is a simplified as well as
a more compact version of a regular or normal function expression or syntax.

Syntax:

let function_name = (argument1, argument2 ,) => expression

Example: This example describes the usage of the Arrow function.


JavaScript

const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {


return s.length;
});

console.log ("Normal way ", a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);

console.log ("Using Arrow Function ", a3); // [8, 6, 7, 9]

Output: Normal way [ 8, 6, 7, 9 ]

Using Arrow Function [ 8, 6, 7, 9]

# Function Parameters

Till now, we have heard a lot about function parameters but haven’t discussed them in
detail. Parameters are additional information passed to a function. For example, in the
above example, the task of the function calcAddition is to calculate the addition of two
numbers. These two numbers on which we want to perform the addition operation are
passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in JavaScript
can have any number of parameters and also at the same time, a function in JavaScript
cannot have a single parameter.

Example: In this example, we pass the argument to the function.

JavaScript

function multiply (a, b) {


b = typeof b!== "undefined"? b: 1;
return a * b;
}

console.log(multiply (69));
Output: 69

# Calling Functions

After defining a function, the next step is to call them to make use of the function. We
can call a function by using the function name separated by the value of parameters
enclosed between the parenthesis and a semicolon at the end. The below syntax shows
how to call functions in JavaScript:

Syntax:

functionName( Value1, Value2, ..);

Example: Below is a sample program that illustrates the working of functions in


JavaScript:

JavaScript

function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");

// creating a variable
let nameVal = "Admin";

// calling the function


console.log(welcomeMsg(nameVal));

Output: Hello Admin welcome to GeeksforGeeks

# Return Statement

There are some situations when we want to return some values from a function after
performing some operations. In such cases, we can make use of the return statement in
JavaScript. This is an optional statement and most of the time the last statement in a
JavaScript function. Look at our first example with the function named as calcAddition.
This function is calculating two numbers and then returns the result.

Syntax:

The most basic syntax for using the return statement is:

return value;

The return statement begins with the keyword return separated by the value which we
want to return from it. We can use an expression also instead of directly returning the
value.
# What is a JavaScript tag?
A JavaScript tag is a snippet of code embedded within a website’s HTML. It enables
various functionalities such as tracking user interactions, collecting data, and integrating
third-party services. These tags are crucial for web analytics, advertising, and enhancing
user experience by loading scripts dynamically based on user behavior or predefined
conditions. JavaScript tags can be placed in the head, body, or footer sections of a
webpage. This allows for flexible and precise control over when and how they execute.

# How do JavaScript tags work?

JavaScript tags work by inserting a small piece of JavaScript code into the HTML of a
webpage. When the page loads, the browser executes this code, which can perform
various functions. This includes sending data to analytics servers, loading additional
scripts, or modifying the content of the page dynamically. These tags can trigger based
on specific events such as page load, button clicks, or form submissions. By leveraging
the Document Object Model (DOM), JavaScript tags can interact with and manipulate the
structure and content of the webpage in real time.

# Types of JavaScript tags:

There are several types of JavaScript tags, each serving different purposes.

 Tracking tags collect data on user behavior and interactions for analytics tools
like Google Analytics.
 Advertising tags display and measure ads, integrating with platforms such as
Google Ads or Facebook Pixel.
 Social media tags facilitate content sharing and social engagement.
 Conversion tags track and report on specific user actions, such as making a
purchase or signing up for a newsletter.
 Custom tags are tailored to perform unique functions based on specific business
needs or technical requirements.

# JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:

var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

var a=10; a++; Now a =


++ Increment
11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

Identical (equal and of


=== 10==20 = false
same type)

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true


>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators are
as follows:

Operator Description Example

(10==20 & 20==33) =


& Bitwise AND
false

(10==20 | 20==33) =
| Bitwise OR
false

(10==20 ^ 20==33) =
^ Bitwise XOR
false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

Bitwise Right Shift with


>>> (10>>>2) = 2
Zero

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) =


false

(10==20 || 20==33) =
|| Logical OR
false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

var a=10; a+=20; Now a =


+= Add and assign
30

var a=20; a-=10; Now a =


-= Subtract and assign
10

var a=10; a*=20; Now a =


*= Multiply and assign
200

/= Divide and assign var a=10; a/=2; Now a = 5

var a=10; a%=2; Now a =


%= Modulus and assign
0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

Conditional Operator returns value based


(?:)
on the condition. It is like if-else.

Comma Operator allows multiple


, expressions to be evaluated as single
statement.

delete Delete Operator deletes a property from


the object.

In Operator checks if object has the given


in
property

checks if the object is an instance of given


instanceof
type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

checks what is returned in a generator by


yield
the generator's iterator.

# JavaScript Data Types


JavaScript is a loosely typed or dynamically typed language. It means does not need to
explicitly declare the data type of a variable. The JavaScript engine automatically
determines the data type based on the assigned value.

JavaScript data types are categorized into two parts i.e. primitive and non-primitive
types. The primitive data types include Number, String, Boolean, Null, Undefined, and
Symbol. Non-primitive types include Object, Array, and Function. The latest ECMAScript
standard defines eight data types out of which seven data types are
Primitive(predefined) and one complex or non-primitive.

# Primitive Data Type

The predefined data types provided by JavaScript language are known as primitive data
type. Primitive data types are also known as in-built data types.

 Number: JavaScript numbers are always stored in double-precision 64-bit binary


format IEEE 754.
 String: JavaScript Strings are made up of a list of characters, essentially an array of
characters.
 Boolean: represents a logical entity and can have two values: true or false.
 Null: this type has only one value: null.
 Undefined: A variable that has not been assigned a value is undefined.
 Symbol: Symbols return unique identifiers that can be used as property keys in
objects without colliding with other keys.
 BigInt: BigInt is a built-in object providing a way to represent whole numbers larger
than 253-1.
 This table summarizes the basic data types in JavaScript along with their
descriptions.

# Non-Primitive Data Types

The data types that are derived from primitive data types are known as non-primitive
data types. It is also known as derived data types or reference data types.

Object: It is the most important data type and forms the building blocks for modern
JavaScript. We will learn about these data types in detail in further articles.

# JavaScript Primitive Data Types Explanation and Examples

1. Number

The Number data type represents both integer and floating-point numbers.

The Number data type contains both integer and floating-point numbers. JavaScript does
not distinguish between integers and floats. Some special numbers in JavaScript are:
‘Infinity’, ‘-Infinity’, and ‘NaN’. The ‘NaN’ denotes a computational error.

let num = 2; // Integer


let num2 = 1.3; // Floating point number
let num3 = Infinity; // Infinity
let num4 = 'something here too'/2; // NaN

2. String

A String in JavaScript is a series of characters that are surrounded by quotes. There are
three types of quotes in Javascript, which are:

let str = "Hello There";


let str2 = 'Single quotes works fine';
let phrase = `can embed ${str}`;

There’s no difference between ‘single’ and “double” quotes in JavaScript. Backticks


provide extra functionality as with their help of them we can embed variables inside
them.

let name = "Mukul"; // embed a variable


alert( `Hello, ${name}!` ); // Hello, Mukul!

3. Boolean

The boolean type has only two values i.e. true and false.
let isCoding = true;
let isOld = false;

4. NULL

The special null value does not belong to any of the default data types. It forms a
separate type of its own which contains only the null value.

let age = null;

The ‘null’ data type defines a special value that represents nothing, or empty value.

5. Undefined

A variable that has been declared but not initialized with a value is automatically
assigned the undefined value. It means the variable exists, but it has no value assigned
to it.

let x; // x is declared but not defined


console.log(x); // Output: undefined

6. Symbol (Introduced in ES6)

Symbols are new primitive data types introduced as part of ES6. A Symbol is a unique
and immutable primitive value that is used as an identifier for object properties. Symbols
are primarily used for creating unique property keys in objects, ensuring there are no
conflicts with other properties.

let symbol1 = Symbol("Geeks")


let symbol2 = Symbol("Geeks")

// Each time Symbol() method


// is used to create new global Symbol
console.log(symbol1 == symbol2); // False (because symbols are always unique)

7. BigInt (Introduced in ES2020)

BigInt is a built-in object that provides a way to represent whole numbers greater than
253. The largest number that JavaScript can reliably represent with the Number primitive
is 253, which is represented by the MAX_SAFE_INTEGER constant.

let bigBin = BigInt("0b1010101001010101001111111111111111");


// 11430854655n
console.log(bigBin);
# JavaScript Non-Primitive Data Types Examples

1. Object

JavaScript objects are fundamental data structures used to store collections of data.
They consist of key-value pairs and can be created using curly braces {} or the new
keyword. Understanding objects is crucial, as everything in JavaScript is essentially an
object.

# Object Creation

Using the “object constructor” syntax

let person = new Object ();

Using the “object literal” syntax

let person = {};

Both these methods are correct, though it’s totally your call what to choose. We can also
put properties inside an Object.

2. Arrays

An Array is a special kind of object used to store an ordered collection of values, which
can be of any data type.

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


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

# Introduction to JavaScript Literals


JavaScript Literals are constant values that can be assigned to the variables called
literals or constants. JavaScript Literals are syntactic representations for different types
of data like numeric, string, Boolean, array, etc. data. Literals in JavaScript provide a
means of representing particular or some specific values in our program. For example,
var name = “john,” a string variable named name is declared and assigned a string
value “john.” The literal “john” represents the value of john for the variable name.
JavaScript supports different types of literals.

# What are the Types of JavaScript Literals?

Javascript literals hold different types of values. Examples of JavaScript Literals are given
below:

1. Integer Literals
Integer literals are numbers that must have a minimum of one digit (0-9). No blank or
comma is allowed within an integer. It can store positive numbers or negative numbers.
JavaScript supports integer literals in three different bases. The base 10 is Decimal
(Decimal numbers contain digits (0,9) ); examples for Decimal numbers are 234, -56,
10060. Second is base 8, Octal (Octal numbers contain digits (0,7) and leading 0
indicates octal), 0X 073, -089, 02003. Third is base 16, that is, Hexadecimal numbers
(Hexadecimal numbers contain (0,9) digits and (A, F) or (a, f) letters and leading 0x or 0X
indicate the number is hexadecimal); examples for hexadecimal numbers are 0X8b, –
0X89, 0X2003.

Let us understand with an example code.

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for numeric literals </title>
</head>
<body>
<h1>JavaScript Numbers </h1>
<p> Number can be written of any base.</p>
Decimal number : <b id="no1"></b><br>
Octal number : <b id="no2"></b><br>
Hexadecimal number : <b id="no3"></b><br>
<script>
document.getElementById("no1").innerHTML = 100.25;
</script>
<script>
document.getElementById("no2").innerHTML = 073;
</script>
<script>
document.getElementById("no3").innerHTML = 0X8b;
</script>
</body>
</html>

Output:
2. Floating Number Literals

Floating numbers are decimal or fraction numbers or can have an exponent part.
Examples of hexadecimal numbers are 78.90, -234.90, 78.6e4, etc.

Let us understand with an example code.

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for float literals </title>
</head>
<body>
<h1>JavaScript Float </h1>
<p> Float Examples are : </p>
1. <b id="no1"></b><br>
2. <b id="no2"></b><br>
3. <b id="no3"></b><br>
<script>
document.getElementById("no1").innerHTML = 100.25;
</script>
<script>
document.getElementById("no2").innerHTML = -78.34;
</script>
<script>
document.getElementById("no3").innerHTML = 56e4;
</script>
</body>
</html>

Output:

3. String Literals

A string literal are a sequence of zero or more characters. A string literal are either
enclosed in the single quotation or double quotation as (‘) and (“) respectively, and to
concatenate two or more strings, we can use the + operator. Examples for string are
“hello”, “hello world”, “123”, “hello” + “world” etc.

A list of special characters that can be used in JavaScript string are.

\b: Backspace.

\n: New Line

\t: Tab

\f: Form Feed

\r: Carriage Return

\\: Backslash Character (\)

\’: Single Quote

\ “: Double Quote

Let us understand with an example code –

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for float literals </title>
</head>
<body>
<h1>JavaScript String </h1>
<p> String Examples are : </p>
1. <b id="no1"></b><br>
2. <b id="no2"></b><br>
3. <b id="no3"></b><br>
4. <b id="no4"></b><br>
<script>
var str = "This is first string";
document.getElementById("no1").innerHTML = str;
</script>
<script>
var strobj = new String("This is string store as object");
document.getElementById("no2").innerHTML = strobj;
</script>
<script>
var str = "This is first string";
document.getElementById("no3").innerHTML = str.length;
</script>
<script>
var str = "This is first string";
document.getElementById("no4").innerHTML = str+" This is second string";
</script>
</body>
</html>

Output:

4. Array Literals

Array literals comprise a list of expressions or constant values, with each expression
referred to as an array element. An array literal contains a list of elements within square
brackets’ [ ]’. Suppose no value is a pass when it creates an empty array with zero
length. If elements are passed, its length is set to the number of elements passed. String
examples are var color = [ ], var fruits = [“Apple”, “Orange”, “Mango”, “Banana”] (an
array of four elements).

Let us understand with an example code.

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for float literals </title>
</head>
<body>
<h1>JavaScript Array </h1>
<p> Array Examples are : </p>
1. <b id="no1"></b><br>
2. <b id="no2"></b><br>
3. <b id="no3"></b><br>
4. <b id="no4"></b><br>
<script>
var fruits = ["Apple", "Orange", "Mango", "Banana"];
document.getElementById("no1").innerHTML = fruits;
</script>
<script>
document.getElementById("no2").innerHTML = fruits[0];
</script>
<script>
document.getElementById("no3").innerHTML = fruits[fruits.length - 1];
</script>
<script>
document.getElementById("no4").innerHTML = fruits.length;
</script>
</body>
</html>

Output:
5. Boolean Literals

Boolean literals in JavaScript have only two literal values, that are true and false.

Let us understand with an example code.

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for Boolean literals </title>
</head>
<body>
<h1>JavaScript Boolean </h1>
<p> Boolean Examples are : </p>
<script>
document.write('Boolean(12) is ' + Boolean(12));
document.write('<br>');
document.write('Boolean("Hello") is ' + Boolean("Hello"));
document.write('<br>');
document.write('Boolean(2 > 3) is ' + Boolean(2 > 3));
document.write('<br>');
document.write('Boolean(3 > 2) is ' + Boolean(3 > 2));
document.write('<br>');
document.write('Boolean(-12) is ' + Boolean(-12));
document.write('<br>');
document.write("Boolean('true') is " + Boolean('true'));
document.write('<br>');
document.write("Boolean('false') is " + Boolean('false'));
document.write('<br>');
document.write('Boolean(0) is ' + Boolean(0));
</script>
</body>
</html>

Output:

6. Object Literals

Object literals are collections of zero or more key-value pairs of a comma-separated list,
enclosed by a pair of curly braces ‘{ } ‘. Examples of an object literal with a declaration
are var userObject = { }, var student = { f-name : “John”, l-name : “D”, “rno”: 23,
“marks”: 60}

Let’s understand with an example code –

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for Object literals </title>
</head>
<body>
<h1>JavaScript Object </h1>
<p> Object Examples are : </p>
<p id= "no1"> </p>
<script>
// Create an object:
var student = {firstName:"John", lastName:"D", "rno" : 23, "marks" : 60 };
// Displaying some data from the object:
document.getElementById("no1").innerHTML =
student.firstName + " got " + student.marks + " marks.";
</script>
</body>
</html>

Output:

# Typecasting in Javascript?
Typecasting in JavaScript means converting one data type to another data type i.e., the
conversion of a string data type to Boolean or the conversion of an integer data type to
string data type. The typecasting in JavaScript is also known as type conversion or type
coercion.

# Types of conversions

The type casting is of two types in JavaScript. They are the implicit type conversions and
the explicit type conversions.

# Implicit type casting

The implicit type casting is the conversion of data type done due to the internal
requirement or automatic conversion by the compiler or the interpreter.

To understand the implicit conversion let us consider the example of the boolean values
(primitive).
JavaScript expects a boolean value in a conditional expression. So JavaScript will
temporarily convert the value in parentheses to a boolean to evaluate the if expression

Example

Open Compiler

val = 1;
if (val) {
console.log( 'yes, val exists' );
}

The values 0, -0, '' (empty string), NaN, undefined, and null, evaluate to false and all
other values evaluate to true, even empty arrays and objects.

# Implicit conversion with == operator

Type conversion is also performed when comparing values using the equal (==) and not
equal (!=) operators. So when you compare the number 125 with a string '125' using the
equals (==) operator, the expression evaluates to true −

console.log( 125 == '125' );

Type conversion is not performed when using the identical (===) and not identical (!
==) operators.

# Explicit type casting

The second type casting the explicit type casting is done forcefully by the developer for
the sake of a good line of code. In JavaScript the type casting can be done only for
strings, numbers and Boolean (object) data types.

Examples of the explicit type casting are methods parseInt(), parseFloat() and toString().

The parseInt() function converts its first argument to a string, parses that string, then
returns an integer or NaN.

The parseFloat() function parses an argument (converting it to a string first if needed)


and returns a floating point number.

The toString() method returns a string representing the object, i.e., it tries to convert
object to string.

Example
Following example demonstrates explicit type casting in JavaScript.

Open Compiler

let a = 1.015
console.log(a)
console.log(typeof a)
console.log(a.toString())
console.log(typeof a.toString())

# Typecasting in Strings

In JavaScript the strings are treated as objects. So, here in string type casting anything
like a number or a character given will be converted to a string. The String() is used to
convert any given value to string.

Syntax

The typecasting for a string can be done by using the following syntax.

String(input)
The String() method will take one parameter, i.e., the input which is to be converted to
string.

Example

Following is an example of this function −

Open Compiler

input = 25
console.log("The input value with its type is:",input,typeof(input))
console.log("Arithmetic operation before typecasting with its type is:", (10 + input),
typeof((10 + input)))
sInput = String(input)
console.log("After the type casting is done the type is:",sInput,typeof(sInput))
console.log("Arithmetic operation after typecasting with its type is:", (10 + sInput),
typeof(10 + sInput))

In the above example, the given input is a number and it does the addition of numbers
before type casting is done. But when the given input is converted to string by the
String() method, then instead of addition of the input with 10 it is concatenated as one of
the operands is a string even the other is a number. This shows that the type conversion
is done.

# Typecasting in Boolean

To convert the given input to boolean the Boolean() is used which takes the given value
as the parameter and converts it into the Boolean form. This method returns the Boolean
values ‘true’ or ‘false’ accordingly. It returns true if the input is at least a character, any
number except zero or if it an object. It returns false when the given input is an empty
string, zero undefined or a null value.

Example

Following is an example of the Boolean Typecasting with Boolean() in JavaScript −

Open Compiler

console.log("The cases where the method will return true")


console.log("The given input is rw",Boolean('rw'))
console.log("The given input is -3.6",Boolean(-3.6))
console.log("The given input is new Date()",Boolean(new Date()))
console.log("The cases where the method will return false")
console.log("The given input is number 0",Boolean(0) )
console.log("The given input is null value",Boolean(null) )
console.log("The given input is undefined",Boolean(undefined))
console.log("The given input is empty string",Boolean('') )

# Numeric Typecasting

To convert the given input to a number the Number() method is used. It takes one
parameter i.e., the input which is given to be converted to number. The conversions can
be done to float type or integer type.

To convert it in to Integer type, parseInt() method is used. To convert it in to Float type,


parseFloat() is used.

Syntax

Number(input)
parseInt(input)
parseFloat(input)

The three methods will take the given input as the parameter and converts respective of
the method used.

Example

This example demonstrates Number() typecasting in JavaScript −

Open Compiler

console.log("Input is 7.8.9 and after conversion",Number("7.8.9"))


console.log("Input is 6.6.6 and after conversion to float is",parseInt("6.6.6"))
console.log("Input is 6.6.6 and after conversion to float is",parseFloat("6.6.6"))

# JavaScript Arrays
An array in JavaScript is a data structure used to store multiple values in a single
variable. It can hold various data types and allows for dynamic resizing. Elements are
accessed by their index, starting from 0.

You have two ways to create JavaScript Arrays: using the Array constructor or the
shorthand array literal syntax, which is just square brackets. Arrays are flexible in size,
so they can grow or shrink as you add or remove elements.

# Basic Terminologies of JavaScript Array


 Array: A data structure in JavaScript that allows you to store multiple values in a
single variable.
 Array Element: Each value within an array is called an element. Elements are
accessed by their index.
 Array Index: A numeric representation that indicates the position of an element in
the array. JavaScript arrays are zero-indexed, meaning the first element is at index
0.
 Array Length: The number of elements in an array. It can be retrieved using the
length property.

# Declaration of an Array

There are basically two ways to declare an array i.e. Array Literal and Array Constructor.

1. Creating an Array using Array Literal

Creating an array using array literal involves using square brackets [] to define and
initialize the array. This method is concise and widely preferred for its simplicity.

Syntax:

let arrayName = [value1, value2, ...];

Example:

JavaScript

// Creating an Empty Array


let names = [];
console.log(names);

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React"];

console.log(courses);
Output[]
[ 'HTML', 'CSS', 'Javascript', 'React' ]

2. Creating an Array using JavaScript new Keyword (Array Constructor)

The “Array Constructor” refers to a method of creating arrays by invoking the Array
constructor function. This approach allows for dynamic initialization and can be used to
create arrays with a specified length or elements.

Syntax:

let arrayName = new Array();

Example:

javascript

// Creating and Initializing an array with values


let courses = new Array("HTML", "CSS", "Javascript", "React");
console.log(courses);

Output

[ 'HTML', 'CSS', 'Javascript', 'React' ]

# Basic Operations on JavaScript Arrays

1. Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the
arrays starts with 0.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React"];

// Accessing Array Elements


console.log(courses[0]);
console.log(courses[1]);

Output:

HTML
CSS

2. Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of array using the index
number.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing First Array Elements


let firstItem = courses[0];

console.log("First Item: ", firstItem);

Output:

First Item: HTML

3. Accessing the Last Element of an Array

We can access the last array element using [array.length – 1] index number.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing Last Array Elements


let lastItem = courses[courses.length - 1];

console.log("First Item: ", lastItem);

Output:

First Item: React

4. Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their corresponding


index.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React"];
console.log(courses);

courses[1]= "Bootstrap";
console.log(courses);

Output:

[ 'HTML', 'CSS', 'Javascript', 'React' ]


[ 'HTML', 'Bootstrap', 'Javascript', 'React' ]

5. Adding Elements to the Array

Elements can be added to the array using methods like push() and unshift().

The push() method add the element to the end of the array.

The unshift() method add the element to the starting of the array.

JavaScript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];

// Add Element to the end of Array


courses.push("Node.js");

// Add Element to the beginning


courses.unshift("Web Development");

console.log(courses);

Output:

[ 'Web Development', 'HTML', 'CSS', 'Javascript', 'React', 'Node.js' ]

6. Removing Elements from an Array

To remove the elements from an array we have different methods like pop(), shift(), or
splice().

 The pop() method removes an element from the last index of the array.
 The shift() method removes the element from the first index of the array.
 The splice() method removes or replaces the element from the array.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
console.log("Original Array: " + courses);

// Removes and returns the last element


let lastElement = courses.pop();
console.log("After Removing the last elements: " + courses);

// Removes and returns the first element


let firstElement = courses.shift();
console.log("After Removing the First elements: " + courses);

// Removes 2 elements starting from index 1


courses.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + courses);
Output:

Original Array: HTML,CSS,Javascript,React,Node.js


After Removing the last elements: HTML,CSS,Javascript,React
After Removing the First elements: CSS,Javascript,React
After Removing 2 elements starting from index 1: CSS

7. Array Length

We can get the length of the array using the array length property.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];

let len = courses.length;

console.log("Array Length: " + len);

Output:

Array Length: 5

8. Increase and Decrease the Array Length

We can increase and decrease the array length using the JavaScript length property.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];

// Increase the array length to 7


courses.length = 7;

console.log("Array After Increase the Length: ", courses);

// Decrease the array length to 2


courses.length = 2;
console.log("Array After Decrease the Length: ", courses)
OutputArray After Increase the Length: [ 'HTML', 'CSS', 'Javascript', 'React', 'Node.js', <2
empty items> ]
Array After Decrease the Length: [ 'HTML', 'CSS' ]

9. Iterating Through Array Elements

We can iterate array and access array elements using for loop and forEach loop.

Example: It is an example of for loop.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Iterating through for loop


for (let i = 0; i < courses.length; i++) {
console.log(courses[i])
}

Output:

HTML
CSS
JavaScript
React

Example: It is the example of Array.forEach() loop.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Iterating through forEach loop


courses.forEach(function myfunc(elements) {
console.log(elements);
});

Output:

HTML
CSS
JavaScript
React

10. Array Concatenation

Combine two or more arrays using the concat() method. It returns new array containing
joined arrays elements.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];
let otherCourses = ["Node.js", "Expess.js"];

// Concatenate both arrays


let concateArray = courses.concat(otherCourses);

console.log("Concatenated Array: ", concateArray);

Output:

Concatenated Array: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js', 'Expess.js' ]

11. Conversion of an Array to String

We have a builtin method toString() to converts an array to a string.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Convert array ot String


console.log(courses.toString());

Output:

HTML,CSS,JavaScript,React
12. Check the Type of an Arrays

The JavaScript typeof operator is used ot check the type of an array. It returns “object”
for arrays.

JavaScript

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Check type of array


console.log(typeof courses);

Output: object

# JavaScript Dialogue Boxes


Dialogue boxes are a kind of popup notification, this kind of informative functionality is
used to show success, failure, or any particular/important notification to the user.

JavaScript uses 3 kinds of dialog boxes:

 Alert
 Prompt
 Confirm

These dialog boxes can be of very much help in making our website look more attractive.

1.Alert Box:

An alert box is used on the website to show a warning message to the user that they
have entered the wrong value other than what is required to fill in that position.
Nonetheless, an alert box can still be used for friendlier messages. The alert box gives
only one button “OK” to select and proceed.
Example:

JavaScript

function Warning() {

alert ("Warning danger you have not filled everything");

console.log ("Warning danger you have not filled everything"); }

2.Confirm box:

A confirm box is often used if you want the user to verify or accept something. When a
confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the
user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false and will show null.
Example:

JavaScript

function Confirmation() { var Val = confirm("Do you want to continue ?");

if (Val == true) {

console.log(" CONTINUED!");

return true;

else {

console.log("NOT CONTINUED!");

return false;

} }

3.Prompt Box:

A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to
proceed after entering an input value. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the
Cancel button, the window method prompt() returns null.
Example:

JavaScript

function Value(){

var Val = prompt("Enter your name : ", "Please enter your name");

console.log("You entered : " + Val);

# DHTML in JavaScript
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.

The DHTML application was introduced by Microsoft with the release of the 4 th version of IE
(Internet Explorer) in 1997.

# Components of Dynamic HTML


DHTML consists of the following four components or languages:

 HTML 4.0
 CSS
 JavaScript
 DOM.

# HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It defines the
structure of a web page with various defined basic elements or tags.

# CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for controlling
the style and layout of the HTML elements on the web pages.
# JavaScript
JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell the
browser for performing an action.

# DOM
DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all elements in
HTML.

# Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):

 It is used for designing the animated and interactive web pages that are developed
in real-time.
 DHTML helps users by animating the text and images in their documents.
 It allows the authors for adding the effects on their pages.
 It also allows the page authors for including the drop-down menus or rollover
buttons.
 This term is also used to create various browser-based action games.
 It is also used to add the ticker on various websites, which needs to refresh their
content automatically.

# Features of DHTML
Following are the various characteristics or features of DHTML (Dynamic HTML):

 Its simplest and main feature is that we can create the web page dynamically.
 Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
 It provides the facility for using the events, methods, and properties. And, also
provides the feature of code reusability.
 It also provides the feature in browsers for data binding.
 Using DHTML, users can easily create dynamic fonts for their web sites or web
pages.
 With the help of DHTML, users can easily change the tags and their properties.
 The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.
# Difference between HTML and DHTML
Following table describes the differences between HTML and DHTML:

HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup


language)

1. DHTML is not a language, but it is a set


1. HTML is simply a markup language.
of technologies of web development.

2. It is used for creating and designing the


2. It is used for developing and creating
animated and interactive web sites or
web pages.
pages.

3. This markup language creates static 3. This concept creates dynamic web
web pages. pages.

4. It does not contain any server-side 4. It may contain the code of server-side
scripting code. scripting.

5. The files of HTML are stored with 5. The files of DHTML are stored with
the .html or .htm extension in a system. the .dhtm extension in a system.

6. A simple page which is created by a 6. A page which is created by a user using


user without using the scripts or styles the HTML, CSS, DOM, and JavaScript
called as an HTML page. technologies called a DHTML page.

7. This concept needs database


7. This markup language does not need
connectivity because it interacts with
database connectivity.
users.

Example

In the following example, we are changing the text of the element with id = "demo"
using the HTML DOM document.getElementById() method −

Open Compiler

<!DOCTYPE html>
<html>
<body>
<h1>Welcome to Tutorialspoint</h1>
<p id = "demo"> Text will be modified</p>
<script>
document.getElementById("demo").innerHTML = "Simply Easy Learning at your
fingertips...";
</script>
</body>
</html>

Example

In the example below, we are creating a function that will be invoked if we clicked the
button and it changes the background color of the text and displays the alert on the
screen.

Open Compiler

<!DOCTYPE html>
<html>
<head>
<style>
#demo{
display: flex;
margin: auto;
justify-content: center;
}
input{
display: flex;
margin: auto;
justify-content: center;
}
</style>
<h1 id = "demo"> Tutorialspoint </h1>
<input type = "submit" onclick = "btn()"/>
<script>
function btn() {
document.getElementById("demo").style.backgroundColor = "seagreen";
window.alert("Background color changed to seagreen");
}
</script>
</head>
</html>
# Dynamically changing text style and content:
To dynamically change text style and content in JavaScript, you can manipulate the DOM
(Document Object Model). Here's an example:

JavaScript

// Change text content


document.getElementById("myParagraph").textContent = "New text!";

// Change text style


document.getElementById("myHeading").style.color = "blue";
document.getElementById("myHeading").style.fontSize = "24px";

# Explanation:

Accessing Elements: We use document.getElementById() to get references to the HTML


elements we want to modify.

Changing Content: We use the textContent property to update the text within an
element.

Changing Style: We access the style property of an element to modify its CSS properties,
such as color and fontSize.

# Example with Event Listener:

JavaScript

const button = document.getElementById("myButton");


const textElement = document.getElementById("myText");

button.addEventListener("click", function() {
textElement.textContent = "Text changed!";
textElement.style.color = "red";
textElement.style.fontWeight = "bold";
});

This code changes the text content and style of an element when a button is clicked.

# Synchronous and Asynchronous in JavaScript


JavaScript is known for its ability to handle both synchronous and asynchronous
operations. Understanding how these two things work is important for writing efficient,
responsive, and user-friendly applications. In this article, we will see the differences
between synchronous and asynchronous JavaScript with clear examples to help you.

# What is Synchronous JavaScript?

In synchronous programming, operations are performed one after the other, in


sequence. So, basically each line of code waits for the previous one to finish before
proceeding to the next. This means that the program executes in a predictable, linear
order, with each task being completed before the next one starts.

Example: In this example, we have shown the synchronous nature of JavaScript.

javascript

console.log("Hi");
console.log("Geek");
console.log("How are you?");

Output:

Hi
Geek
How are you?

In the above code snippet, the first line of the code Hi will be logged first then the second
line Geek will be logged and then after its completion, the third line will be logged How
are you. So as we can see the codes work in a sequence. Every line of code waits for its
previous one to get executed first and then it gets executed.

In synchronous code, every statement waits for the previous one to finish before it runs.
This is straightforward and easy to follow, but it has some drawbacks, especially when
dealing with time-consuming tasks like fetching data from a server or reading a large
file. If such a task is included in the sequence, it will block the execution of the rest of
the code until it’s finished, leading to potential delays and a bad user experience.

# What is Asynchronous JavaScript?

Asynchronous programming, on the other hand, allows multiple tasks to run


independently of each other. In asynchronous code, a task can be initiated, and while
waiting for it to complete, other tasks can proceed. This non-blocking nature helps
improve performance and responsiveness, especially in web applications.

Example: In this example, we have shown the Asynchronous nature of JavaScript.


javascript

console.log("Hi");

setTimeout(() => {
console.log("Geek");
}, 2000);

console.log("End");

Output:

Hi
End
Geek

So, what the code does is first it logs in Hi then rather than executing the setTimeout
function it logs in End and then it runs the setTimeout function.

At first, as usual, the Hi statement got logged in. As we use browsers to run JavaScript,
there are the web APIs that handle these things for users. So, what JavaScript does is, it
passes the setTimeout function in such web API and then we keep on running our code
as usual. So it does not block the rest of the code from executing and after all the code
its execution, it gets pushed to the call stack and then finally gets executed. This is what
happens in asynchronous JavaScript.

# How Asynchronous JavaScript Works Behind the Scenes

To understand asynchronous behavior better, it’s important to know about the JavaScript
runtime environment, specifically the event loop and call stack:

 Call Stack: The call stack is where functions are executed in the order they’re
called. In synchronous operations, each function is added to the stack and
executed before moving to the next.

 Web APIs (in Browsers): Functions like setTimeout, HTTP requests, and event
listeners are handled by Web APIs in the browser. When an asynchronous function
like setTimeout is called, it is passed to these Web APIs, which manage the timing
without blocking the main call stack.

 Callback Queue: Once the Web API has finished its job (like waiting for the
timeout), it pushes the callback function (like the one in setTimeout) to the
callback queue.
 Event Loop: The event loop continuously checks the call stack. If it’s empty, it
pushes the functions from the callback queue onto the stack for execution. This is
why the delayed message “Geek” is logged after other code has finished.

You might also like