Introduction
JavaScript is a light-weight object-oriented programming language which is used by several websites for scripting the webpage. It was introduced in the year 1995 for adding programs to webpage in the netscape navigator browser. The traditional website uses js to provide several forms of interactivity and simplicity.
Features of JavaScript:
1. JavaScript runs on the client-side, meaning it’s executed by the user’s web browser rather than the web server. This allows for dynamic updates without requiring a page reload.
2. JavaScript can manipulate the content of a webpage in real-time. It can add, remove, or modify HTML elements, styles, and attributes based on user actions or other events.
3. JavaScript enables developers to respond to user actions (such as clicks, mouse movements, and keyboard inputs) through event handling. Event listeners can be attached to HTML elements to trigger specific functions when events occur.
4. JavaScript supports asynchronous programming through callbacks, promises, and async/await syntax.
5. JavaScript is supported by all major web browsers, making it a cross-platform language for web development. This enables consistent functionality and user experience across different devices and browsers.
6. JavaScript interacts with the Document Object Model (DOM), which represents the structure of HTML documents as a tree of objects. It can access, traverse, and modify DOM elements, attributes, and content dynamically.
7. JavaScript enables asynchronous communication with web servers using AJAX. This allows for fetching data from servers and updating parts of a webpage without reloading the entire page.
8. JavaScript supports modular programming through functions, objects, and modules. This encourages code organization, reusability, and maintainability in large-scale applications.
History of JavaScript
JavaScript, created by Brendan Eich in 1995 while working at Netscape Communications Corporation, was initially developed in just 10 days. Its purpose was to enable interactive web pages, filling a gap between HTML, used for static content, and server-side languages like Java, which was more complex for client-side scripting. Originally named Mocha, it was quickly renamed to LiveScript and finally to JavaScript to capitalize on the popularity of Java, although the two languages are quite different. JavaScript was standardized as ECMAScript in 1997 by the European Computer Manufacturers Association (ECMA). Over the years, JavaScript has evolved significantly, especially with the release of ECMAScript 5 in 2009 and ECMAScript 6 (also known as ES6 or ECMAScript 2015) in 2015, which introduced major improvements and features.
Javascript in different browser
JavaScript is a core technology of the World Wide Web and is supported by all major web browsers, but each browser has its own JavaScript engine that executes the code. Here’s how JavaScript works across different browsers:
Internet Explorer:
– Follow Tools > Internet option from menu.
– Select security tab from dialog box.
– Click the custom level button.
– Scroll down till you find scripting option.
– Select enable radio button under active scripting.
– Finally click OK and come out.
Firefox:
– Open a new tab > type about: config in the address bar.
– Then you will find warning dialog. Select I’ll be careful, I promise!
– Then you will find the list of configure option in browser.
– In the search bar, type javascript. Enable.
– There you will find the option to enable or disable javascript by right-clicking on the value of that option > select toggle.
Chrome:
– Click the chrome menu at the top right hand corner of your browser.
– Select setting.
– Click show advanced settings at the end of the page.
– Under the privacy section, click the content settings button.
– In the javascript section, select “don’t allow any site to rum javascript”.
Opera:
– Follow Tools > preferences from the menu.
– Select advanced option from the dialog box.
– Select content from the listed items.
– Select enable javascript checkbox.
– Finally click OK and come out.
Javascript in html documents
JavaScript can be included in HTML documents in several ways: embedded directly within the HTML, inline within HTML elements, or via external files. Here’s a breakdown of each method:
Embedding JavaScript in HTML:
This method involves placing JavaScript code inside a `<script>` tag within the HTML document. It can be placed in the `<head>`, `<body>`, or both.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Embedded JavaScript</title>
<script>
function showMessage()
{
alert(‘Hello, world!’);
}
</script>
</head>
<body>
<button onclick=”showMessage()”>Click Me</button>
</body>
</html>
Inline JavaScript:
Inline JavaScript is used directly within HTML tags using event attributes such as `onclick`, `onmouseover`, etc. This method is useful for small snippets of code but is generally discouraged for larger scripts due to maintainability and readability concerns.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript</title>
</head>
<body>
<button onclick=”alert(‘Hello, world!’)”>Click Me</button>
</body>
</html>
External JavaScript File
This method involves placing JavaScript code in a separate `.js` file and linking to it from the HTML document using the `<script>` tag with the `src` attribute. This approach is preferred for larger scripts as it separates content from behavior and promotes better organization and reusability of code.
Example:
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript</title>
<script src=”script.js”></script>
</head>
<body>
<button onclick=”showMessage()”>Click Me</button>
</body>
</html>
Hello.js
function showMessage() {
alert(‘Hello, world!’);
}
Variables and Data types
javaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don’t need to specify type of the variable because it is dynamically used by JavaScript engine. For example:
var a=40;//holding number
var b=”Rahul”;//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:
String:
Represents sequence of characters eg. “hello”
Number:
represents numeric values e.g. 100
Boolean:
represents boolean value either false or true
Undefined:
represents undefined value
Null
represents null i.e. no value at all
JavaScript non-primitive data types
The non-primitive data types are as follows:
Object:
represents instance through which we can access members .
Array:
represents group of similar value.
RegExp:
represents regular expression.
Javascript variable
Like many other programming languages, JavaScript has variables, Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type “text/javascript”>
var money!
var name:
//–>
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type=”text/javascript”>
< !–
var money, name;
//–>
</script>
For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script type “text/javascript”>
<!–
var name = “Ali”;
var money;
money 2000.50;
//–>
<<</script>
Javascript variable scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
- Global Variables: A global variable has global scope which means it can be defined anywhere in your JavaScript code.
- Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Take a look into the following example.
<html>
<body onload checkscope ();>
<script type “text/javascript”>
<!–
var myVar “global”;// Declare a global variable
function checkscope() {
var myVar “local”; // Declare a local variable
document.write(myVar):
//–>
</script>
</body>
</html>
JavaScript Variable Names
– You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
– JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but 123 test is a valid one.
– JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
Html DOM
DOM introduction
The document object model is a platform and language-neutral interface that was allow programs and programs and scripts to dynamically access and update the content, structure and style of documents.
DOM METHOD
Here are some instances in which the HTML markup needs to be dynamically manipulated without actually changing the HTML source code. To achieve this, users can make use of a variety of HTML DOM methods present in JavaScript at their disposal. Now coming to the HTML DOM methods, there are six different methods in which users can access or manipulate HTML elements using JavaScript:
– HTML DOM getElementById() Method.
– HTML DOM getElementsByClassName() Method.
– HTML DOM getElementsByName() Method.
– HTML DOM getElementsByTagName() Method.
– HTML DOM querySelector() Method.
– HTML DOM querySelectorAll() Method
These methods are illustrated with some sample code snippets below:
– HTML DOM getElementById():
This method is used when developers have defined certain HTML elements with IDs that uniquely identify the same elements in the whole document. It returns an Element object which matches the specified ID in the method. If the ID does not exist in the document, it simply returns null.
Syntax:
document.getElementById(id);
Parameter: It has a single parameter as mentioned above and described below:
– id: The ID of the element to locate in the HTML document. It should be a case-sensitive string.
– Return value: It returns the object corresponding to the passed ID in the method, or null if no match is found.
– Example: The following example clearly demonstrates the use of the getElementById() method.
<!DOCTYPE html>
<html>
<body>
<h2> web designing </h2>
<!– Paragraph element with an id of “web” –>
<p id=”web”> class 9 </p>
<script>
const paragraph =
document.getElementById(“web”);
console.log(
“The selected element is” + paragraph
);
</script>
</body>
</html>
– HTML DOM getElementsByClassName:
This method is used when there mufpple HTML. eletsents with the same class name. It returns a collection of a objects which match the specified class in the method.
Syntax:
document.getElementsByClassName (ClassName)
Parameter: It has a single parameter as mentioned above and described below: className:
– The class name of the element(s) to locate in the HTML.
– document. It should be a case-sensitive string Return value: It returns a collection of objects corresponding to the passed class name in the method.
Example
<!DOCTYPE html>
<html>
<body>
<h2> GFG </h2>
<!–> Dive elements with class names of “web” –>
<div class “web”> class </div>
<div class “web”> 9 </div>
<div class “web”> web designing </div>
<script>
const divs document. getElementsByClassName(
“geeks-for-geeks” Console.log(dives);
console.log(divs[0]);
</script>
</body>
</html>
– HTML DOM getElementsBy Name():
In Javascript, getElementsByName() returnis a NodeList of objects which match a particular name attribute in the HTML document.
Syntax:
document.getElementsByName (nameAttribute);
Parameter: It has a single parameter as mentioned above and described below:
– nameAttribute: The name attribute of the elementis) to locate in the HTML document. It should be a case-sensitive string.
– Return value: It returns a NodeList of objects corresponding to the passed name attribute in the method.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Web designing</h2>
<!– Input elements with name attributes of “web”>
<input type=”text” placeholder = “Text input” name= “web”/>
< input type = “number” placeholder= “Number input” name = “web”>
<script>
const inputs document.getElementsByName (“web”);
console.log(inputs);
// Select second element with
// name attribute “web”
console.log(inputs [1]);
</script>
</body>
</html>
– HTML DOM getElementsByTagName():
The getElementsByTagName() returns a HTML Collection of objects which match a tag name in the HTML document.
Syntax:
document.getElementsByTagName (tagName):
Parameter: It has a single parameter as mentioned above and described below:
– tagName: The tag name of the element(s) to locate in the HTML document. It should be a case-sensitive string.
– Return value: It returns an HTMLCollection of objects corresponding to the passed tag name in the method.
example:
<!DOCTYPE html>
<html>
<body>
<! — Various HTML elements with different tag names –>
<div> web <div>
<p> for </p>
<p> class </p>
<p>nine</p>
const p = document.getElementsByTagName(“p”);
console.log(p);
// select third element with tag name “p”
console.log(p[2]);
</script>
</body>
</html>
– HTML DOM querySelector():
This method returns the first match of an element that is found within the HTML document with the specific selector. If there is no match, null is returned.
Syntax:
document.querySelector(selector)
Parameter: It has a single parameter as mentioned above and described below:
– selector: A string containing one or more selectors to match elements located in the HTML document.
– Return value: It returns the first occurrence of the object corresponding to the passed selector in the method.
Example:
<!DOCTYPE html>
<html>
<body>
<div class=”gfg”> web technology </div>
<p> class 9 </p>
<p id=”para”> For </p>
<p>web</p>
<script>
// using “.” For prefix class selector
const div =
document. querySelector(“.gfg”);
// Using tag name for tag selector
const firstparagraph =
Document.querySelector(“p”);
// Using “#” prefix for ID selector
const secondParagraph =
document.querySelector(“#para”);
Console.log(
div, firsParagraph, secondParagraph
);
</script>
</body>
</html>
– HTML DOM querySelector Alt:
This method retut the specific set of elements that are found within the HTML document with the specific selector, Syntax:
document.querySelectorAll (selector);
Parameter: It has a single parameter as mentioned above and described below:
selector: A string containing one or more selectors to match elements located in the HTML document.
Return value: It returns a NodeList of the objects corresponding to the passed selector in the method.
Example:
<!DOCTYPE html>
<html>
<body>
<! Various HTML elements with different tag names –>
<div class = “gfg”> let’s learn </div>
<div class=”gfg”> class </div>
< div class=”gfg”> nine </div>
<div class= “gfg”> web </div>
<p> let’s learn web technology </p>
<script>
// Using “.” for prefix class selector
const divs =
document.querySelectorAll (“.gfg”);
console.log(divs);
</script>
</body>
</html>
DOM Document
The HTML DOM Document Object
The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object. Below are some examples of how you can use the document object to access and manipulate HTML.
Finding HTML elements:
Method | Description |
document.getElementById(id) | Find an element by element id |
document.getElementsByTagName(name) | Find elements by tag name |
document.getElementsByClassName(name) | Find elements by class name |
Changing HTML Elements:
Property | Description |
element.innerHTML=new html content | Change the inner HTML of an element |
element attribute = new value | Change the attribute value of an HTML element |
element style property = new style | Change the style of an HTML element |
Method | Description |
element.setAttribute(attribute, value) | Change the attribute value of an HTML element |
Adding and Deleting Elements:
Method | description |
document.createElement(element) | Create an HTML element |
document.removeChild(element) | Remove an HTML element |
document.appendChild(element) | Add an HTML element |
document.replaceChild(new, old) | Replace an HTML element |
document.write(text) | Write into the HTML output stream |
Adding Event Handler:
Method | Description |
document.getElementById(id).onclick = function(){code} | Adding event handler code to an onclick |
Finding HTML Objects:
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5. Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Property | Description | DOM |
document.anchors | Returns all <a> elements that have a name attribute | 1 |
document.applets | Deprecated | 1 |
document.baseURI | Returns the absolute base URI of the document | 3 |
document.body | Returns the <body> element | 1 |
document.cookie | Returns the document’s cookie | 1 |
document.doctype | Returns the document’s doctype | 3 |
document.documentElement | Returns the <html> element | 3 |
document.documentMode | Returns the mode used by the browser | 3 |
document.documentURI | Returns the URL of the document | 3 |
document.domain | Returns the domain name of the document server | 1 |
document.domConfig | Obsolete. | 3 |
document.embeds | Returns all <embed> elements | 3 |
document.forms | Returns all <form> elements | 1 |
document.head | Returns the <head> element | 3 |
document.images | Returns all <img> elements | 3 |
document.links | Return all <area> and <a> elements that have a href attribute. | 1 |
document.implementation | Returns the DOM implementation | 3 |
document.inputEncoding | Returns the document’s encoding (character set) | 3 |
document.lastModified | Returns the date and time the document was updated. | 3 |
document.readyState | Returns the (loading) status of the document | 1 |
document.referrer | Returns the URI of the referrer (the linking document) | 3 |
document.scripts | Returns all <script> elements | 1 |
document.strictErrorChecking | Returns if error checking is enforced | 3 |
Document.title | Returns the <title> element | 1 |
document. URL | Returns the complete URL of the document. | 1 |
Dom Elements
JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc, But, before you can perform any action you need to find or select the target HTML element.
Selecting Elements by ID
You can select an element based on its unique ID with the getElementById() method. This is the easiest way to find an HTML element in the DOM tree.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset utf = “8”>
<title> Javascript Select an Element by its ID Attribute
</title>
</head>
<body>
<p id “mark”> This is a paragraph of text. </p>
<p> This is another paragraph of text. </p>
<script>
//selecting element with id mark
var match document.getElementById (“mark”
// Hihghlighting elements background
match.style.background “yellow”:
</script>
</body>
</html>
Selecting Elements by Class Name
Similarly, you can use the getElementsByClassName() method to select all the elements having specific class names. This method returns an array-like object of all ML child elements which have all of the given class names.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title> JavaScript Select Elements by Class Name
</title>
</head>
<p class=”test”> This is a paragraph of text. </p>
<body>
<div class=”block test”> This is another paragraph of text. </div>
<p> This is one more paragraph of text. </p>
<hr>
// Selecting elements with class test
<script>
var matches = document.getElementsByClassName (“test”);
// Displaying the selected elements count
document.write (“number of selected element: “+ matches.length”)
// Applying bold style to first element in selection matches (0). style, forntweight = “bold”,
//Applying itatiic style to last element in selection Patches (matches.length- 11.style.fontStyle “italic
//Highlighting each element’s Background through loop for (var elem in matches){
matches (elem).style.background “yellow”;
}
</script>
</body>
</html>
Selecting Elements by Tag Name
You can also select HTML elements by tag name using the getElementsByTagName() method. This method also returns an array-like object of all child elements with the given tag name.
<!DOCTYPE html>
<html lang “en”>
<head>
<meta charset=”utf-8″>
<title> JavaScript Select Elements by Tag Name
</title>
</head>
<body>
<p> This is a paragraph of text. </p>
<div class= “test”> This is another paragraph of text. </div>
<p> This is one more paragraph of text. </p>
<hr>
<script>
// Selecting all paragraph elements
var matches document.getElementsByTagName (“p”);
// Printing the number of selected paragraphs
document.write (“number of selected elements:” + matches.length);
// Highlighting each paragraph’s background through
Loop
for (var elem in matches) {
matches [elem].style.background “yellow”;
}
</script>
</body>
</html>
Selecting Elements with CSS Selectors
You can use the querySelectorAll() method to select elements that matches the specified CSS selector. CSS selectors provide a very powerful and efficient way of selecting HTML elements in a document.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title> Javascript Select Elements with CSS Selectors </title>
</head>
<body>
<ul>
<li> Bread </li>
<li class = “tick”> Coffee </li>
<li> Pineapple Cake </li>
</ul>
<script>
// Selecting all li elements
var matches document. querySelectorAll (“ul li”);
// Printing the number of selected 11 elements document.write (“Number of selected elements:- matches. Length + “<hr>”)
// Printing the content of selected li elements for (var elem of matches) {
document.write (elem.innerHTML + “<br>”);
}
//Appling line through style to first li element with class tick
matches= document.querySelectorAll (“ul li.tickm;
matches [0].style.textDecoration “line-through”;
</script>
</body>
DOM Node List
Node interface is the primary datatype for the entire Document Object Model. The node is used to represent a single XML element in the entire document tree. A node can be any type that is an attribute node, a text node or any other node.
We have listed the node types as below:
– ELEMENT_NODE
– ATTRIBUTE_NODE
– ENTITY_NODE
– ENTITY_REFERENCE_NODE
– DOCUMENT_FRAGMENT_NODE
– TEXT_NODE
– CDATA_SECTION_NODE
– COMMENT_NODE
– PROCESSING_INSTRUCTION_NODE
– DOCUMENT_NODE
– DOCUMENT_TYPE_NODE
– NOTATION_NODE
Control Flow
Control flow in JavaScript is how your computer runs code from top to bottom. It starts from the first line and ends at the last line, unless it hits any statement that changes the control flow of the program such as loops, conditionals, or functions.
– if … else
– switch case
– do while loop
– while loop
– for loop
Conditional Statement
1. If … else
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
Syntax
if (expression) {
Statement (s) to be executed if expression is true
}
Example:
<script type <! “text/javascript”>
<! – –
var age 20;
if (age> 18) {
document.write(“<b> Qualifies for driving </b>”);
}
// –>
- Switch
The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
Syntax
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
case condition n: statement (s)
break;
default: statement(s)
Example:
<script type=”text/javascript”>
<! —
var grade ‘A’;
document.write(“Entering switch block <br/>”);
switch (grade ) |
case ‘A’: document.write (“Good job <br/>”);
break:
case ‘B’: document.write (“Pretty good <br/>”);
break;
case ‘C’: document.write (Passed <br/>”);
break;
case ‘D’: document.write (Not so good<br/>”);
break;
case ‘E’: document.write (Failed <br/>”);
break;
default: document.write (“Unknown grade<br/>”)
}
document.write (“Exiting switch block”);
//–>
</script>
Loop Statement
- Do while Loop
The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.
Syntax:
do{
Statement(s) to be executed;
} while (expression);
Example:
<script type=”text/javascript”>
<! —
var count – D
document.write (“Starting loop” +”<br/>”);
do{
document.write(“current count:” + count + “<br/>”);
count++;
} while (count < 0);
document.write (“loop stopped!”);
</script>
- While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.
Syntax
while (expression) {
Statement (s) to be executed if expression is true
}
Example:
<Script type=”text/javascript”>
<!–
var count = 0;
document.write(“Starting loop” + “<br/>”);
while (count < 10)
{
document.write(“Current Cout: count “<br/>”);
count++;
}
document.write(“Loop stopped!”);
//–>
</Script>
- For Loop
The for loop is the most compact form of looping and includes the following three important parts:
– The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
– The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
– The iteration statement where you can increase or decrease your counter.
Syntax:
for (initialization; test condition; iteration statement)
{
Statement (s) to be executed if test condition is true
}
Example:
<script type=”text/javascript”>
<!–
var count,
document.write (“Starting Loop” + “<br/>”);
for (count=0; count< 10; count++){
document.write (“Current Count:” + Count);
document.write (“<br/>”);
}
document.write (“Loop stopped!”); //–>
</script>
Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.
Advantage of JavaScript function:
There are mainly two advantages of JavaScript functions.
– Code reusability: We can call a function several times so it save coding.
– Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.
Syntax:
function functionName([argl, arg2, …argN)){ //code to be executed
For example:
/ declaring a function named greet()
functiongreet () {
console.log(“Hello there”);
Calling a Function
In the above program, we have declared a function named greet(). To use that function, we need to call it. Here’s how you can call the above greet() function.
// function call
greet();
Example:
// program to print a text
// declaring a function
functiongreet() {
console.log(“Hello there!”);
}
// calling the function
greet();
Function Parameters:
A function can also be declared with parameters. A parameter is a value that is passed when declaring a function.
Example:
// program to print the text
// declaring a function
functiongreet (name) {
console.log (“Hello” + name + “:)”);
// variable name can be different let name prompt (“Enter a name: “);
// calling function
greet (name);
Function Return:
The return statement can be used to return the value to a function call. The return statement denotes that the function has ended. Any code after return is not executed. If nothing is returned, the function returns an undefined value.
Example:
// program to add two numbers
// declaring a function
functionadd(a, b) {
return a + b;
}
// take input from the user
let number1 let number2 parseFloat (prompt(“Enter first number: “)); parseFloat (prompt(“Enter second number: “));
// calling function
let result add (number1, number2);
// display the result
console.log(“The sum is ” + result);
Benefits of Using a Function:
– Function makes the code reusable. You can declare it once and use it multiple times.
– Function makes the program easier as each small task is divided into a function.
– Function increases readability.
Function Expressions
For example,
// program to find the square of a number // function is declared inside the variable
let x function (num) { return num num);
console.log(x(4));
// can be used as variable value for other variables
let yx (3)
console.log(y);
Prompt, Confirm, Alert
JavaScript alert()
The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to give a warning message to the users. It displays an alert dialog box that consists of some specified message (which is optional) and an OK button. When the dialog box pops up, we have to click “OK” to proceed.
Syntax:
alert (message)
Example:
<html>
<head>
<script type=”text/javascript”>
function fun() {
alert (“This is an alert dialog box”);
}
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = “butto” value = “fun();” /> “Click me” onclick=
</form>
</body>
</html>
javaScript prompt() dialog box:
The prompt() method in JavaScript is used to display a prompt bos that prompts the user for the input. It is generally used to take the input from the user before entering the page. It can be written without using the window prefix. When the prompt box pops up. we have to click “OK” or “Cancel” to proceed.
Syntax:
prompt (message, default)
Example:
<html>
<head>
<script type=”text/javascript”>
function fun() {
prompt (“This is a prompt box”, “Hello world”);
}
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type=”button” Value= “Click me” onclick = “fun();” />
</form>
</body>
</html>
Confirmation Dialog Box:
A confirmation dialog box is mostly used to take user’s consent on any option. It displays a dialog box with two buttons: OK and Cancel. 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. You can use a confirmation dialog box as follows.
<html>
<head>
<scripttype=”text/javascript”>
<!–
function getConfirmation() {
var retVal = confirm(“Do you want to continue ?”);
if(retVal =true) {
document.write (“User wants to continue!”);
returntrue;
}else{
document.write (“User does not want to continue!”);
returnfalse;
}
}
//–>
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<inputtype=”button”value=”Click Me”onclick=”getConfirmation();”/>
</form>
</body>
</html>
Objects
JavaScript Objects:
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard, monitor etc. JavaScript is an object-based language. Everything is an object in JavaScript.
Creating Objects in JavaScript:
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
JavaScript Object by object literal
syntax:
object={propertyl: valuel, property2:value2…..property N:valueN}
Example:
<Script>
emp{id: 102, name: “Shyam Kumar”, salary: 40000) document.write(emp.id + “” + emp.name + “” + emp.salary);
</Script>
By creating instance of Object
syntax:
var object.name new Object ().
Example:
<script>
var emp new Object (
emp.id 101,
emp.name Ravi Malik
emp.salary 50000;
document.write(emp.id + “ ” + emp.name + “ ” + emp.salary);
</script>
By using an Object constructor:
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword. The this keyword refers to the current object. The example of creating object by object constructor is given below.
<script>
Function emp (id, name, salary) {
this.id=id;
this.name name;
this.salary = salary;
}
e new emp (103, “Vimal Jaiswal”, 30000);
document.write (e.id + ” ” + e.name + ” ” + e.salary);
</script>
JavaScript Object Methods:
S.NO | Methods | Description |
1 | Object.assign() | This method is used to copy enumerable and own properties from a source object to a target object |
2 | Object.create() | This method is used to create a new object with the specified prototype object and properties. |
3 | Object.define Property() | This method is used to describe some behavioural attributes of the properties. |
4 | Object, detine Properties() | This method is used to create or configure multiple object properties. |
5 | Object.entries() | This method returns an array with arrays of the key, value pairs. |
6 | Object.freeze() | This method prevents existing properties from being removed. |
7 | Object.getOwnPropertyDescriptor()
|
This method returns a property descriptor for the specified property of the specified object. |
8 | Object.getOwnPropertyDescriptors() | This method returns all own property descriptor of given object. |
9 | Object.getOwnPropertyNames() | This method returns an array of all properties found. |
10 | Object.getOwnPropertySymbols() | This method returns an array of all own symbol key properties. |
11 | Object.getprototypeOf() | This method returns the prototype of the specified object. |
12 | Object.is() | This method determines whether two values are the same value. |
13 | Object.isExtensible() | This method determines if any object is extensible. |
14 | Object.isFrozen() | This method determines if an object is frozen. |
15 | Object.isSealed() | This method determines if an object is sealed. |
16 | Object.keys() | This method returns an array of a given objects own property names. |
17 | Object.preventExtensions() | This method is used to prevent any extensions of an object. |
18 | Object.seal() | This method prevents new properties from being added and marks all existing properties as non-configurable. |
19 | Object.setPrototypeOf() | This method sets the prototype of a specified object to another object. |
20 | Object.values() | This method returns an array of values. |