You are on page 1of 19

JavaScript

 Last Updated : 03 Nov, 2022

 Read
 Discuss
 Practice
 Video
 Courses
JavaScript (JS) is the world’s most popular lightweight, interpreted compiled programming
language. It is also known as a scripting language for web pages. It can be used for Client-
side as well as Server-side developments.

JavaScript can be added to your HTML file in two ways:


 Internal JavaScript: We can add JS code 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 JavaScript File: We can create a file with .js extension and paste the
JS code inside it. After creating the file, add this file in <script
src=”file_name.js”> tag inside <head> tag of the HTML file.
 Syntax: It is the basic syntax to write code.
<script>
    // JS Code
</script>
 Example 1: It is the basic example to embed JS code in an HTML file.
<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Basic Example to Describe JavaScript
    </title>
</head>
 
<body>
 
    <!-- JavaScript code can be embedded inside
        head section or body section -->
    <script>
        console.log("Welcome to GeeksforGeeks");
    </script>
</body>
 
</html>
 Output: The output will display on console.
 Welcome to GeeksforGeeks
 Example 2: This example describes a simple function and prints the values.

<script>

// Declare a variable and initialize it

// Global variable declaration

var Name = "Apple";

// Function definition

function MyFunction() {

// Local variable declaration

var num = 45;

// Console value of Global variable

console.log(Name);

// Console value of local variable

console.log("\n" + num);

// Function call

MyFunction();

</script>

Why JavaScript is used?

JavaScript is the most popular programming language for both client-side and server-side to
make interactive web pages. It is mainly used to develop websites and web-based applications.
 Creating Interactive Websites: JavaScript is used to make the web pages dynamic and
interactive. It means using JavaScript, we can change the web page content and styles
dynamically.
 Building Applications: JavaScript is used to make web and mobile applications. To
build the web and mobile apps, we can use most popular JavaScript frameworks like –
ReactJS, React Native, Node.js etc.
 Web Servers: We can make robust server applications using JavaScript. To be precise
we use JavaScript frameworks like Node.js and Express.js to build these servers.
 Game Development: JavaSCript can be used to design Browser games. In JavaScript,
lots of game engines available that provide frameworks for building games.

How JavaScript is different from HTML?

 JavaScript is an advanced programming language that makes web pages more


interactive and dynamic whereas HTML is a standard markup language that provides
the primary structure of a website.
 JavaScript simply adds dynamic content to websites to make them look good and
HTML work on the look of the website without the interactive effects and all.
 JavaScript manipulates the content to create dynamic web pages whereas HTML pages
are static which means the content cannot be changed.
 JavaScript is not cross-browser compatible whereas HTML is cross-browser
compatible.
 JavaScript can be embedded inside HTML but HTML can not be embedded inside
JavaScript.

Why to learn JavaScript ?

JavaScript is the most popular and hence the most loved language around the globe. Apart from
this, there are abundant reasons to learn it. Below are a listing of few important points:
 No need of compilers: Since JavaScript is an interpreted language, therefore it does not
need any compiler for compilations.
 Used both Client and Server-side: Earlier JavaScript was used to build client-side
applications only, but with the evolution of its frameworks namely Node.js and
Express.js, it is now widely used for building server-side applications too.
 Helps to build a complete solution: As we saw, JavaScript is widely used in both
client and server-side applications, therefore it helps us to build an end-to-end solution
to a given problem.
 Used everywhere: JavaScript is so loved because it can be used anywhere. It can be
used to develop websites, games or mobile apps, etc.
 Huge community support: JavaScript has a huge community of users and mentors
who love this language and take it’s legacy forward.

Learn more about JavaScript

 Introduction to JavaScript
 Where to put JavaScript code in an HTML Document ?
 Introduction to JavaScript Course
 Introduction to Object Oriented Programming in JavaScript
 Top 5 JavaScript Projects For Beginners
 How to Become a JavaScript Developer?
 7 JavaScript Concepts That Every Web Developer Should Know
 JavaScript Backend basics
 Advanced JavaScript Backend Basics
 Functional Programming in JavaScript
 Top 5 Reasons to Learn JavaScript

JavaScript Objects Complete Reference

This section contains the list of all properties and methods of all JavaScript objects.
 Array
 ArrayBuffer
 Atomics
 BigInt
 Boolean and dataView
 Date
 Error
 Function
 Generator
 Intl
 JSON
 Map
 Math
 Number
 Object
 JavaScript
 Proxy
 Reflect
 RegExp
 String
 Symbol
 WeakMap
 WeakSet
 Expressions

JavaScript Interview Questions

 JavaScript Interview Questions and Answers


 JavaScript Interview Questions and Answers | Set 1
 JavaScript Interview Questions and Answers | Set-2
 JavaScript Interview Questions and Answers | Set 3

JavaScript Practice Quiz

 JavaScript Course | Practice Quiz-1


 JavaScript Course | Practice Quiz-2
 JavaScript Course | Practice Quiz-3
JavaScript Questions

Please go through the JavaScript Examples link to see the wide collection of JavaScript


programming examples. The examples are categorized based on the topics, including objects,
functions, arrays, DOM, and many more.

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


programming language which is also known as the scripting language for
webpages. It is well-known for the development of web pages, many non-
browser environments also use it. JavaScript can be used for Client-
side developments as well as Server-side developments. Javascript is both
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. Like 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
concern about how it is to be done . It simply control the flow of
computation . The procedural programming approach , object,
oriented approach comes under this like async await we are
thinking what it is to be done further after async call.
Declarative programming – In this type of language we are

concern about how it is to be done , basically here logical
computation require . Here  main goal is to describe the desired
result without direct dictation on how to get it like  arrow function
do .
JavaScript can be added to your 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 file 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>
Example:
 HTML

<!DOCTYPE html>
<html lang="en">
   
<head>
    <title>
        Basic Example to Describe JavaScript
    </title>
</head>
   
<body>
   
    <!-- JavaScript code can be embedded inside
        head section or body section -->
    <script>
        console.log("Welcome to GeeksforGeeks");
    </script>
</body>
   
</html>

Output: The output will display on the console.


Welcome to GeeksforGeeks
History of JavaScript: It was created in 1995 by Brendan Eich while he was
an engineer at Netscape. It was originally going to be named LiveScript but
was renamed. Unlike most programming languages, the 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 another object. 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 is 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 its 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 the 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, 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 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 as lightweight due to the fact that it has low CPU
usage, is easy to implement and has a minimalist syntax. Minimalist syntax
as in, it 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
less resources than its counterparts such as Dart or Java.
Additionally, when compared with other programming languages, it has less
in-built libraries or frameworks, contributing as another reason for it to be
lightweight. However, this brings it a drawback 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, 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, frequently used variables, and compiles them to improve
performance.
JavaScript is best known for web page development but it is also used in a
variety of non-browser environments. You can learn JavaScript from the
ground up by following this JavaScript Tutorial and JavaScript Examples.

JavaScript Course | Printing Hello


World in JavaScript
We can put the script tag inside the ‘head’ or ‘body’ tag. Though it should be
noted that each choice of putting the ‘script’ tag has its own consequences.
For now, you can put the script tag anywhere you want.
Printing Hello World 
In order to print the famous ‘Hello World’ sentence to the screen, we can
make use of different methods that javascript provides. Most common are: 
 console.log()
 document.write()
 alert()
Each of the above method have different ways of outputting the content.
Though ‘document.write()’ is used when we want to print the content onto the
document which is the HTML Document. Also ‘console.log()’ is mainly used
when we are debugging javascript code and same thing with ‘alert()’.
Example:  

<!DOCTYPE HTML>

<html>

<head>

<title></title>

<!-- Script tag can also be placed here -->

</head>
<body>

<p>Before the script...</p>

<!-- Script tag inside the body -->

<script>

// write the javascript code inside it

</script>

<p>...After the script.</p>

</body>

</html>

Javascript

<script>
// using console.log
console.log('Hello World');
</script>

<!DOCTYPE html>

<html>

<body>
<h2>W3schools Online HTML editor</h2>

<p>Write and test your HTML code online.</p>

<script>

document.write("Hello Test!");

</script>

</body>

</html>

JavaScript is an object-based client-side scripting language that is popular and used to create
dynamic and interactive web pages. Javascript is an interpreted language usually used with
HTML, and programs written in JavaScript are called lightweight scripts.

Earlier, JavaScript was named LiveScript, but later, Netscape changed its name to JavaScript
because its origin was from Java which was very popular at that time. JavaScript released its
first look for Netscape 2.0 under the name "LiveScript" in 1995.

Where Is JavaScript Being Used?

 JavaScript can interact with HTML DOM elements and dynamically control the webpage.
 Client-side validation in the webpage is done using JavaScript.
 Components such as drop-down menus, pop-up windows, dialog boxes, etc., are created using
JavaScript.
 Javascript is used to load data asynchronously without refreshing the webpage.
 JavaScript is used extensively in the development of online games.
Advantages of JavaScript

 Speed: JavaScript is a client-side scripting language. It is fast because all its code functions
run immediately on the client machine instead of contacting the server and waiting for a
response.
 Simplicity: JavaScript is relatively easy to learn and code.
 Versatility: JavaScript works well with other languages and is utilized in various applications.
 Server Load: Being on the client side reduces the requirement on the website server.
What Does the Script Mean?
A script is a set of instructions given in the form of code. Instructions are designed for either
the web browser (client-side scripting) or the server (server-side scripting). Scripts provide
changes to the web page.

What Does Client-Side Scripting Mean?


The client is the structure or system on which the Web browser runs. JavaScript is the
primary client-side scripting language for the Web. Client-side scripts get interpreted by the
browser. The server is where the Web page and other content reside. The server sends pages
to the user/client on request. This single programming language facilitates this combined
handling of client-server.

report this ad❮ Previous Page  Print PageNext Page ❯


© 2009 — 2022 W3schools® of Technology.

 About Us

Brendan Eich created JavaScript in 1995 while working at Netscape Communications


Corporation. As the web gained popularity, a gradual demand for client-side scripting
languages developed. Most Internet users were connected to a 28.8 kbps modem at the time,
even when web pages were growing in size and complexity. Netscape began to think
seriously about developing client-side scripting language early, at a cutting-edge time of
technological innovation, to handle simple processing. Brendan Eich is the person who
worked for Netscape at that time and began developing a scripting language named "Mocha",
later named "LiveScript", for the release of Netscape Navigator 2 in 1995. He was fascinated
by Java, Scheme, and Self. Netscape, for some time, made the best browser of that time and
enjoyed market supremacy.

Purpose of JavaScript
When JavaScript first appeared in 1995, with effective use of handling some of the input
validation that had previously been left over to server-side languages like Perl. Before that
time, the server required a round-trip to determine whether a required field was left blank or
an invalid value entered. Netscape Navigator wanted to change that with the introduction of
JavaScript. The potential and ability to handle some necessary validation on the client was an
exciting fresh feature when telephone modems were common and well known. The
associated slow speeds turned every trip to the server into an exercise in patience.

More Details on JavaScript History


Later in 1995, as Microsoft rise-up to the competition with the threat the web created, the
project Internet Explorer started in an all-out attempt to wrestle control of the emerging
platform from Netscape.

Gradually Microsoft became a mortal threat, compelling Netscape with its Internet Explorer.
Slowly, a standardization process started to develop to prevent Microsoft from gaining the
power of the JavaScript language. Furthermore, they partnered with Sun to influence their
shared interest in breaking the Microsoft monopoly.

Brendan Eich has assumed that Sun on board decided to surf the tidal wave of building up
surrounding Java and position JavaScript as the companion language with Java, in a similar
manner, Visual Basic was to C++. Netscape's Mocha was later named JavaScript and aimed
to turn the web into a full-blown application platform.

Unfortunately for JavaScript, its early marketing position outlasted its usefulness and later
became a mark on market acceptance because it emerged as a viable technology.

More on JavaScript
Since then, JavaScript has become a significant feature of every main web browser on the
market. No longer bound to simple data validation, JavaScript now interacts and works with
nearly all aspects of the browser window and its contents. JavaScript is recognized as a
complete programming language that can handle complex calculations and interactions,
including closures, anonymous (lambda) functions, and meta-programming. JavaScript has
become such an essential element of the web that even alternative browsers, including those
browsers that run on mobile phones and those designed for users with disabilities, support
and maintain it. Even Microsoft, with its client-side scripting language called VBScript,
ended up with its JavaScript implementation in Internet Explorer from its initial version.

The come-up of JavaScript from a simple, accessible input validator to a powerful


programming language is marvelous. JavaScript is at once a straightforward but, at the same
time, very complex language since it takes minutes to learn but years to master.

report this ad❮ Previous Page  Print PageNext Page ❯

© 2009 — 2022 W3schools® of Technology.

 About Us
 The introduction of JavaScript into web pages immediately ran into the Web's
primary language, HTML. As the component of its original work on JavaScript,
Netscape tried to find out how to make JavaScript coexist in HTML pages without
causing any breaks on those pages, rendering in other browsers. Through trial and
error and controversy, several decisions were finally made and agreed upon to bring
universal scripting support to the Web. Most of the work done in these early days of
the Web has endured and become official in the HTML specification. In this chapter,
you will relate the JavaScript language with HTML.

 Use of <script> Element


 The primary technique of inserting JavaScript into an HTML page is through
the <script> element. Netscape created this <script> element and first implemented it in
the browser - Netscape Navigator version 2. Then it was later added to the formal
HTML specification.

 Six attributes are provided by the <script> element. These are:

Attribute Description

async Which indicates that the script ought to begin downloading immediately.

charset Set the character set of the code particularizes using the src attribute.

defer It indicates that the execution of the script can safely be deferred until after the document's content has be
and displayed.

language Which indicates that the code is using the scripting language.

src Which indicates that an external file that holds the code is to be executed.
type is used to replace language; indicates the content type (also called MIME type) of the used scripting languag

 Example:

 function test() {
 alert("Hello Test!");
 }
 JavaScript Placement Within HTML
 Traditionally, all <script> elements were positioned within the <head> element on an
HTML document's page, such as in the example given below:

 Example:

 <!DOCTYPE html>
 <html>

 <head>
 <title>Webpage Title</title>
 <script src="example1.js"></script>
 <script src="example2.js"></script>
 </head>

 <body>
 <!- - contents here -->
 </body>

 </html>
 The primary purpose of this structuring was to keep external file references, both CSS
and JavaScript files, in the exact location. Moreover, including all JavaScript files in
the <head> of a document designates that all of the JavaScript code must have to be
downloaded, then parsed and interpreted before the page begins rendering. Rendering
means the moment when the browser receives the opening <body> tag in an HTML
code. For pages that require a lot of JavaScript code, this can cause a noticeable delay
in page rendering, during which time the browser will be entirely blank.

 What is Deferred Attribute?


 HTML 4.01 defines an attribute named defer for the <script> element. The use
of defer indicates that a script won't change the page's structure as it executes.
Likewise, the script can be run safely after parsing the whole page. Setting the defer
attribute on an <script> element tells the browser that download should begin at once,
but execution should be deferred:

 Example:

 <!DOCTYPE html>
 <html>

 <head>
 <title>Webpage Title</title>
 <script defer src="example1.js"></script>
 <script defer src="example2.js"></script>
 </head>

 <body>
 <!-- contents here -->
 </body>

 </html>

 report this ad❮ Previous Page  Print PageNext Page ❯

 JavaScript Keywords must be in your information because you can not use them as a
variable name.

 What Are JavaScript Keywords?


 Keywords are reserved words in JavaScript that cannot use to indicate variable labels
or function names. There are a total of 63 keywords that JavaScript provides. All of
them are shown in the below-mentioned table:

 JavaScript Reserved Keywords List


 You can't use a keyword as an identifier in your JavaScript programs; it's reserved
words and used to perform internal operations.

abstract arguments boolean break

Byte case catch char

Const continue debugger default

Delete do double else

Eval false Final finally

Float for function Goto

If implements In Instanceof

Int interface Let Long

Native new Null Package

Private protected public Return

Short static switch Synchronized

This throw throws Transient

True try typeof Var

Void volatile while With


Yield

 ECMAScript5 New Keywords


class Enum expor extends
t

impor Super
t


 ❮ Previous Page  Print PageNext Page ❯

Object-oriented (OO) languages usually are recognized through their use of classes for
creating various objects which have similar properties and methods. It is to be noted that
ECMA-Script has no concept of classes, and hence objects are different than in class-based
languages.

ECMA-262 describes and classifies an object as an "unordered collection of dissimilar


properties, each of them having a primitive value, object, or function." Firmly speaking, this
means that an object is an array of all values in no specific order. Each property and method
is recognized by a name mapped to a value. For this reason, it thinks of ECMA-Script objects
as hash tables, i.e., nothing more than a combination of name-value pairs where the value
may be data or a function. In this chapter, you will learn about JavaScript Object-oriented
concepts.

Understanding Objects
The simplest way to create a custom object is to create a new instance of the object and add
properties and methods to it, as in the example mentioned below:

var person = new Object();


person.name = "Karlos";
person.age = 23;
person.job = "Network Engineer";
person.say_Name = function() {
alert(this.name);
};
This example creates an object called the person that has three properties which are: name,
age, and job, and one method (say_Name()). The say_Name() method displays the value
of this.name, which resolves to person.name.

The previous example can be rewritten using literal object notation as follows:

var person = {
name: "Karlos",
age: 23,
job: "Network Engineer",
say_Name: function() {
alert(this.name);
}
};
The person object in the above example is equivalent to the object in the previous example,
with all those same properties and methods added. These properties are all created with
specific characteristics that define their behavior in JavaScript.

Since JavaScript is an object-oriented programming language and so a programming


language can be called object-oriented when it provides programmers with at least four basic
capabilities to develop:

 Encapsulation: Encapsulation is the capability of storing related information, whether data


or methods, mutually in a single object.
 Aggregation: Aggregation is the ability to store one object inside another.
 Inheritance: A class can depend upon another class or number of classes and inherit their
variables and methods for some specific use.
 Polymorphism: Polymorphism is the potential of the concept of OOP for writing one function
or method which works in a variety of different ways.
Objects are composed of attributes, and when an attribute contains a function, it is considered
a method of the object, or the attribute is considered a property.

Object Properties in JavaScript


Object properties can be any of the three basic data types or any of the abstract data types.
Object properties are variables used within the object's methods but can also be globally
visible variables used throughout the page.

The syntax for including any property to an object is:

Obj_Name.obj_Property = property_Value;
Example:

var obj1 = project.title;

❮ Previous Page  Print PageNext Page ❯

Although ECMA-Script defines it as the core of JavaScript, the Browser Object Model
(BOM) is the central part of using JavaScript on the Web. This chapter will teach you about
the browser object model, window-related objects and frames, positions, and more.

About Window Object


At the heart of the BOM is the window object that signifies an instance of the browser. The
window object serves a dual purpose in browsers and acts as the JavaScript interface between
the browser window and the ECMA-Script Global object. This ultimately means that every
object, variable, and function defined in a web page uses the window as its Global object and
has the right of entry to the methods like parse-Int().

What is Global Scope?


Since the window object gets doubles as the ECMA-Script Global object, every other
variable and function declared globally turned into properties and methods of the window
object. Let us take the example given below:
var age = 26;

function say_Age() {
alert(this.age);
}

alert(window.age); //26
say_Age(); //26
window.say_Age(); //26
In the above example, a variable named 'age' and a function named 'say_Age()' is classified in
the global scope that automatically places them on the window object. So, the variable age is
also accessible as window .age, and the function say_Age() is also accessible
via window.sayAge().

Window Relationships and Frames


When a page contains frames, each frame has its window object, which is stored in the
frames collection. Within that frame collection, the window objects get indexed by number
(ranging from 0 and going in the direction of left to right and then row by row) and by the
frame's name. Each window object has its name property that contains the frame's name. Let
us the following code snippet:

<html>

<head>
<title>Frameset Example</title>
</head>

<frameset rows="150,*">
<frame src="frame1.html" name="top_Frame">
<frameset cols="60%,60%">
<frame src="another_frame.html" name="left_Frame">
<frame src="yetAnother_frame.html" name="right_Frame">
</frameset>
</frameset>
<noframes></noframes>
</html>
The above code snippet generates a frameset having one frame across the top and two frames
below. Also, the top frame can be referenced by window.frames[0] or window.frames ["top_Frame"].
Though, you would most likely use the top object instead of a window to refer to these
frames (creating its top .frames[0], for instance). The top object always points to the very top
(outermost) frame, which is the browser window itself.

Alter Window Size using JavaScript


Shaping the size of a window cross-browser is not straightforward in JavaScript. Internet
Explorer 9+, Mozilla Firefox, Safari Browser, Opera, and Google Chrome - these browsers
supply four properties to deal with window size: innerWidth, innerHeight, outerWidth, and
outerHeight.

var pageWidth = window.innerWidth,


pageHeight = window.innerHeight;
if (typeof pageWidth != "number") {
if (document.compatMode == "CSS1Compat") {
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}

<i class="far fa-eye" id="togglePassword" style="margin-left: -20px; cursor:


pointer;"></i>
                        <script>
                        const togglePassword =
document.querySelector('#togglePassword');
  const password = document.querySelector('#pwd');

  togglePassword.addEventListener('click', function (e) {


    // toggle the type attribute
    const type = password.getAttribute('type') === 'password' ? 'text' :
'password';
    password.setAttribute('type', type);
    // toggle the eye slash icon
    this.classList.toggle('fa-eye-slash');
});  
</script>

You might also like