Unit 3 Javascript
Unit 3 Javascript
JAVASCRIPT
JAVASCRIPT: INTRODUCTION
JavaScript (JS) is a high-level, interpreted programming language used primarily to make web pages
interactive. It is a client-side scripting language but can also be used on the server-side with platforms like
Node.js.
Key Features of JavaScript:
1. Lightweight & Interpreted – No need for compilation; runs directly in the browser.
2. Object-Oriented – Supports objects and prototypal inheritance.
3. Event-Driven – Handles user actions like clicks, keypresses, and form submissions.
4. Cross-Platform – Runs on any browser or device with JavaScript support.
5. Dynamic Typing – Variables can hold different types of values.
6. Asynchronous Programming – Uses callbacks, promises, and async/await for non-blocking execution.
7. Manipulates HTML & CSS – Modifies webpage content dynamically using the DOM.
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that
time, so it was decided that positioning a new language as a “younger brother” of Java would help.But as it
evolved, JavaScript became a fully independent language with its own specification called ECMAScript, and
now it has no relation to Java at all.
HELLO WORLD PROGRAM OF JAVASCRIPT
document.write() method is used to print output directly onto the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Hello World</title>
</head>
<body>
<script>
// Writing "Hello, World!" on the webpage
document.write("Hello, World!");
</script>
</body>
</html>
document.write() vs console.log()
DATA TYPES
JavaScript supports various datatypes, which can be broadly categorized into primitive and non-primitive
types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
4. Undefined: A variable that has been declared but not assigned a value.
let notAssigned;
console.log(notAssigned);
5. Null: Represents an intentional absence of any value.
let empty = null;
6. Symbol: Represents unique and immutable values, often used as object keys.
let sym = Symbol('unique');
7.BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;
Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex entities.
1. Object: Represents key-value pairs.
let obj = {
name: "Amit",
age: 25
};
2. Array: Represents an ordered list of values.
let a = ["red", "green", "blue"];
3. Function: Represents reusable blocks of code.
function fun() {
console.log("Hello");
}
STATEMENTS IN JAVASCRIPT
In JavaScript, statements are instructions that are executed by the browser or Node.js. A statement can be a
simple or complex operation that performs an action, such as assigning a value to a variable, calling a function,
or controlling program flow with conditional statements.
Declaration Statements
Declaration statements are variables, functions, or classes that are introduced into a program. These statements
begin with a keyword followed by its identifier or name.
Example
var x = 5;
var y = 6;
var X = 4;
var z = x + y;
Expression Statements
Expression statements, such as function calls or assignments, evaluate an expression and generate a value in
JavaScript. They can be assigned to a variable or used as part of a larger expression and are then discarded.
var x = 5;
x = 6;
console.log(x);
Conditional Statements
Conditional statements, such as if statements or switch statements, control program flow based on a condition:
Example
// If statement
var x = 10;
if (x > 5) {
console.log('x is greater than 5');
}
Loop Statements
Loop statements, such as while loops or for loops, repeat a block of code while a condition is true:
/ While loop
var x = 4;
while (x < 5) {
document.write(x);
x++;
}
// For loop
for (let i = 0; i < 5; i++) {
document.write(i);
}
Jump Statements
Jump statements, such as break or return statements, transfer control to another part of the program.
COMMENTS
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
FUNCTIONS
A function in JavaScript is a block of reusable code that performs a specific task. It helps in modular
programming, making the code more organized and manageable.
1. Function Declaration (Named Function)
A function can be declared using the function keyword, followed by the function name, parameters (optional),
and a body enclosed in {}.
Syntax:
function functionName(parameters) {
// Function body
return value; // Optional
}
Example
function greet(name) {
return "Hello, " + name + "!";
}
document.write(greet("John"));
Output
Hello, John!
document.write(greetUser());
document.write("<br>");
document.write(greetUser("Alice"));
Output
Welcome, Guest!
Welcome, Alice!
VARIABLE SCOPE
In JavaScript, the concept of scope refers to the visibility and accessibility of variables in different parts of
your code. There are two primary types of scope: global scope and local scope.
Global Scope
A variable declared outside of any function or block has global scope, meaning it can be accessed from
anywhere in the code. This includes inside functions, loops, and conditional statements.
Example:
var globalVar = "I am a global variable";
function displayGlobalVar() {
document.write(globalVar); // Accessing global variable
}
displayGlobalVar(); // Output: I am a global variable
In this example, globalVar is accessible inside the displayGlobalVar function because it is declared in the
global scope.
Local Scope
A variable declared within a function is considered to have local scope. It can only be accessed from within
that function. Local variables are not visible outside their defining function.
Example:
function displayLocalVar() {
var localVar = "I am a local variable";
document.write(localVar); // Accessing local variable
}
function checkScope() {
var scope = "I am local";
document.write(scope); // Output: I am local
}
checkScope();
document.write(scope); // Output: I am global
Here, the scope variable inside checkScope shadows the global scope variable.
HOISTING
Variables declared with var are hoisted to the top of their function or global context. If you try to access a
variable before its declaration, it will return undefined.
Example:
javascript
document.write(myVar); // Output: undefined
var myVar = "I am hoisted";
document.write(myVar); // Output: I am hoisted
In this example, myVar is hoisted but not initialized until after the first document.write() call.
Function Hoisting
Function declarations are also hoisted. You can call a function before it is defined in your code.Example:
javascript
greet(); // Output: Hello!
function greet() {
document.write("Hello!");
}
In this case, the greet() function can be called before its declaration due to hoisting.
STRICT MODE IN JAVASCRIPT
Strict mode is a way to opt into a restricted variant of JavaScript, which helps catch common coding errors
and "unsafe" actions such as defining global variables unintentionally. It can be enabled by adding "use
strict"; at the beginning of a script or function.
Benefits of Strict Mode
1. Prevents Accidental Globals: Variables must be declared with var, let, or const.
2. Eliminates this coercion: In strict mode, if you use this in a function without an explicit context, it
remains undefined.
3. Disallows Duplicate Parameter Names: Functions cannot have duplicate parameter names.
Example of Strict Mode:
javascript
"use strict";
function myFunction() {
undeclaredVar = "This will cause an error"; // ReferenceError: undeclaredVar is not defined
}
myFunction();
In this example, attempting to assign a value to undeclaredVar without declaring it first results in an error due
to strict mode.
JAVASCRIPT OBJECTS
An object in JavaScript is a data structure used to store related data collections. It stores data as key-value
pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the
properties can be added, modified, or deleted at runtime.
There are two primary ways to create an object in JavaScript: Object Literal and Object Constructor.
1. Creation Using Object Literal
The object literal syntax allows you to define and initialize an object with curly braces {}, setting properties
as key-value pairs.
let obj = {
name: "Sheetal",
age: 23,
job: "Developer"
};
console.log(obj);
Output
{ name: 'Sheetal', age: 23, job: 'Developer' }
2. Creation Using new Object() Constructor
let obj = new Object();
obj.name= "Sourav",
obj.age= 23,
obj.job= "Developer"
console.log(obj);
Output
{ name: 'Sourav', age: 23, job: 'Developer' }
Basic Operations on JavaScript Objects
1. Accessing Object Properties
You can access an object’s properties using either dot notation or bracket notation
let obj = { name: "Sourav", age: 23 };
Output
Sourav
23
2. Modifying Object Properties
Properties in an object can be modified by reassigning their values.
let obj = { name: "Sourav", age: 22 };
console.log(obj);
obj.age = 23;
console.log(obj);
Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
3. Adding Properties to an Object
You can dynamically add new properties to an object using dot or bracket notation.
let obj = { model: "Tesla" };
obj.color = "Red";
console.log(obj);
Output
{ model: 'Tesla', color: 'Red' }
4. Removing Properties from an Object
The delete operator removes properties from an object.
let obj = { model: "Tesla", color: "Red" };
delete obj.color;
console.log(obj);
Output
{ model: 'Tesla' }
5. Checking if a Property Exists
You can check if an object has a property using the in operator or hasOwnProperty() method.
let obj = { model: "Tesla" };
console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));
Output
false
true
<script>
alert("Hello! This is an alert box.");
</script>
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.
<script>
var result = confirm("Are you sure you want to proceed?");
if (result) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
</script>
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.
<script>
JavaScript operators are symbols or keywords used to perform operations on values and variables. They are
the building blocks of JavaScript expressions and can manipulate data in various ways.
1. JavaScript Arithmetic Operators
Arithmetic Operators perform mathematical calculations like addition, subtraction, multiplication, etc.
<script>
const x = 4 + 7;
document.write("x"+" "+x+"<br>");
const y = 6 * 7;
document.write("y" + " "+y);
</script>
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can also perform operations like addition
or multiplication before assigning the value.
let n =8;
n+=9;
document.write(n+"<br>");
let r=8
r*=2;
document.write(r);
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or false). They are useful for making
decisions in conditional statements.
document.write(7==9);
document.write(9!=9);
u=parseInt(prompt("enter"));
v=parseInt(prompt("enter"));
document.write(v>u);
4. JavaScript Logical Operators
Comparison operators are mainly used to perform the logical operations that determine the equality or
difference between the values.
const c=true;
const d=false;
document.write(c && d);
document.write(c || d);
document.write(!c);
5.JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
const res = 4 & 2; // Bitwise AND
document.write(res+"<br>");
const re = 4 | 2;
document.write(re);
LOOPS IN JAVASCRIPT
Loops in JavaScript are used to repeatedly execute a block of code as long as a specified condition is true.
BENEFITS OF USING LOOPS
• Code Reusability: Loops reduce code repetition by executing the same block of code multiple times.
• Automation: They automate repetitive tasks, like iterating over arrays or objects.
• Efficiency: Loops save time and effort when performing operations on large datasets.
• Dynamic Control: Loops adapt to changing conditions during runtime, making programs more flexible.
TYPES OF LOOPS IN JAVASCRIPT
1.for loop
2.while loop
3.do-while loop
4.for in loop
5.for of loop
1. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition) {
// Code to be executed
}
Example
let i=1;
while(i<=10)
{
document.write(i+"<br>");
i++;
}
2. for Loop
The for loop repeats a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
Example
for(i=0;i<11;i++)
{
document.write(i+"<br>");
}
3. do...while Loop
The do...while loop executes the block of code at least once before checking the condition.
Syntax:
do {
// Code to be executed
} while (condition);
Example
let r=5;
do
{
document.write(r+ "<br>");
r--;
}
while(r<4)
4. for...in Loop
The for...in loop is used to iterate over the properties of an object.
Syntax:
for (key in object) {
// Code to be executed
}
Example
let ob={name:"rahul",age:56};
for(let key in ob)
{
document.write(key+" " + ob[key] + "<br>");
}
5. for...of Loop
The for...of loop is used to iterate over iterable objects like arrays, strings, or other collections.
Syntax
for (element of iterable) {
// Code to be executed
}
Example
let colors = ["Red", "Green", "Blue"];
for (let color of colors) {
document.write(color + "<br>");
}
Difference Between break and continue in JavaScript:
1. break:
o Terminates the loop entirely and exits it.
o No further iterations are executed.
2. continue:
o Skips the current iteration and moves to the next one.
o The loop continues running.
Using break
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exit the loop when i is 3
}
document.write("Number: " + i + "<br>");
}
// Output: 1, 2
Using continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i is 3
}
document.write("Number: " + i + "<br>");
}
// Output: 1, 2, 4, 5
WITH KEYWORD
The with statement in JavaScript is used to simplify the code when working with an object that has multiple
properties. It allows you to access an object's properties directly without repeatedly specifying the object name.
with (object) {
// Statements
}
Example Without with Statement
var person = { name: "John", age: 25, city: "New York" };
with (person) {
document.write("Name: " + name + "<br>");
document.write("Age: " + age + "<br>");
document.write("City: " + city + "<br>");
}
Explanation in Points
1. The with statement allows you to access an object’s properties directly inside the block.
2. It helps to reduce code repetition and improves readability when dealing with objects with many
properties.
3. It is mostly used when working with deeply nested objects.
4. However, the with statement is not recommended because it makes code harder to understand and can
lead to unexpected errors.
5. JavaScript strict mode ("use strict") does not allow the use of the with statement.
1. Number Object
Syntax:
let num = new Number(10);
console.log(num.valueOf()); // 10
2. String Object
Represents a sequence of characters.
Syntax:
let str = new String("Hello");
console.log(str.toUpperCase()); // "HELLO"
3. Array Object
Used to store multiple values in a single variable.
Syntax:
let arr = new Array(1, 2, 3);
console.log(arr.length); // 3
4. Date Object
Works with dates and times.
Syntax:
let date = new Date();
console.log(date.toDateString()); // "Mon Feb 02 2025"
5. Math Object
Provides mathematical operations.
console.log(Math.sqrt(25)); // 5
REGEXP
Regular Expressions (RegExp) in JavaScript are used for pattern matching and string manipulation (e.g.,
searching, replacing, validating inputs).
Creating a RegExp
Using Literal Syntax:
var pattern = /hello/;
Using Constructor:
var pattern = new RegExp("hello");
RegExp Methods
1. test() – Checks if a pattern exists (returns true/false)
2. exec() – Returns first match as an array, else null
3. match() – Returns all matches in an array
4. replace() – Replaces matched pattern with a new string
5. search() – Returns index of first match, else -1
6. split() – Splits a string based on the pattern
BOM IN JAVASCRIPT
The Browser Object Model (BOM) allows JavaScript to interact with the browser. It provides objects that
control browser operations, such as windows, navigation, history, and screen properties.
BOM Properties and Methods
a) window Object (Global Object)
• Represents the browser window.
• All global variables and functions belong to window.
Example
console.log(window.innerWidth); // Width of the browser window
console.log(window.innerHeight); // Height of the browser window
b) navigator Object
• Provides information about the browser.
console.log(navigator.userAgent); // Browser details
console.log(navigator.language); // Language setting
c) screen Object
• Gives information about the user's screen.
console.log(screen.width); // Screen width
console.log(screen.height); // Screen height
d) location Object
• Handles the URL of the current page.
console.log(location.href); // Current URL
location.reload(); // Reloads the page
e) history Object
• Manages browser history.
history.back(); // Go back one page
history.forward(); // Go forward one page
The window object is the global object in JavaScript that represents the browser window. It provides properties
and methods to interact with the browser, such as opening new windows, displaying alerts, and getting screen
size.
1. Properties of window Object
The window object has several properties. Here are some important ones:
(i) window.innerWidth and window.innerHeight
• These properties return the width and height of the browser window (excluding toolbars and
scrollbars).
document.write("Width: " + window.innerWidth + "<br>");
document.write("Height: " + window.innerHeight + "<br>");
(ii) window.outerWidth and window.outerHeight
• These return the width and height of the browser window, including toolbars and scrollbars.
Example:
document.write("Outer Width: " + window.outerWidth + "<br>");
document.write("Outer Height: " + window.outerHeight + "<br>");
(iii) window.location
• The location property returns the URL of the current page.
document.write("Current URL: " + window.location.href + "<br>");
(iv) window.navigator
• This property gives information about the browser and operating system.
Example:
document.write("Browser Name: " + window.navigator.appName + "<br>");
document.write("Browser Version: " + window.navigator.appVersion + "<br>");
(v) window.screen
• It provides information about the user's screen.
Example:
document.write("Screen Width: " + window.screen.width + "<br>");
document.write("Screen Height: " + window.screen.height + "<br>");
JavaScript window Object
The window object is the global object in JavaScript that represents the browser window. It provides properties
and methods to interact with the browser, such as opening new windows, displaying alerts, and getting screen
size.
(iii) window.location
• The location property returns the URL of the current page.
Example:
javascript
CopyEdit
document.write("Current URL: " + window.location.href + "<br>");
(iv) window.navigator
• This property gives information about the browser and operating system.
Example:
javascript
CopyEdit
document.write("Browser Name: " + window.navigator.appName + "<br>");
document.write("Browser Version: " + window.navigator.appVersion + "<br>");
(v) window.screen
• It provides information about the user's screen.
Example:
javascript
CopyEdit
document.write("Screen Width: " + window.screen.width + "<br>");
document.write("Screen Height: " + window.screen.height + "<br>");
(vi) window.document
• It represents the document object, which allows us to manipulate the HTML content.
Example:
javascript
CopyEdit
document.write("Document Title: " + window.document.title + "<br>");
DOM in JavaScript
The Document Object Model (DOM) represents an HTML document as a structured tree, allowing JavaScript
to manipulate elements dynamically.
DOM Properties and Methods
a) document Object
• Represents the entire HTML document.
console.log(document.title); // Displays page title
document.title = "New Title"; // Changes title
b) Selecting Elements
• getElementById() – Selects an element by ID.
• getElementsByClassName() – Selects elements by class.
• getElementsByTagName() – Selects elements by tag.
• querySelector() – Selects the first matching element.
• querySelectorAll() – Selects all matching elements.
let element = document.getElementById("demo");
console.log(element.innerHTML);
c) Modifying Elements
• Changing Content
document.getElementById("demo").innerHTML = "Hello, DOM!";
Changing Styles:
document.getElementById("demo").style.color = "red";
d) Creating and Removing Elements
let newDiv = document.createElement("div");
newDiv.innerHTML = "New Element";
document.body.appendChild(newDiv); // Adds element to body
Events make web pages interactive and dynamic. They are used for:
Handling User Actions: Detecting clicks, key presses, form submissions, etc.
Validating Forms: Checking user input before submission.
Dynamic UI Changes: Showing/hiding elements, updating text, animations, etc.
Game Development: Handling keyboard and mouse inputs.
Asynchronous Tasks: Handling AJAX requests, API responses, and timers.
Tracking User Activity: Logging user behavior (e.g., Google Analytics).
1. onAbort (Deprecated)
This event was used when an image or media failed to load but is no longer widely supported. Use onError
instead.
<img src="invalid.jpg" onerror="alert('Image failed to load!')">
2. onBlur
Triggered when an element loses focus.
<input type="text" onblur="alert('Input lost focus!')" placeholder="Click and then click outside">
3. onChange
Fires when the value of an input element changes and loses focus.
<select onchange="alert('Selection changed!')">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
4. onClick
Occurs when an element is clicked.
5. onDblClick
Triggered when an element is double-clicked.
<button ondblclick="alert('Button double-clicked!')">Double Click Me</button>
6. onError
Fires when an error occurs, such as a failed image load.
7. onFocus
Occurs when an element gains focus.
<input type="text" onfocus="this.style.backgroundColor='yellow'">
8. onKeyDown
Triggered when a key is pressed down.
<input type="text" onkeydown="alert('Key pressed down!')">
10. onKeyUp
Fires when a key is released.
<input type="text" onkeyup="alert('Key released!')">
11. onLoad
Occurs when a page or an image is fully loaded.
<body onload="alert('Page Loaded!')">
12. onMouseDown
Triggered when the mouse button is pressed down.
<button onmousedown="alert('Mouse button pressed!')">Press Me</button>
13. onMouseMove
Fires when the mouse moves over an element.
<div onmousemove="alert('Mouse moving!')" style="width:200px; height:100px; border:1px solid black;">
Move Mouse Here
</div>
14. onMouseOut
Occurs when the mouse moves away from an element.
<button onmouseout="alert('Mouse left the button!')">Hover and Leave</button>
15. onMouseOver
Fires when the mouse enters an element.
<button onmouseover="alert('Mouse entered the button!')">Hover Over Me</button>
16. onMouseUp
Occurs when the mouse button is released.
<button onmouseup="alert('Mouse button released!')">Click and Release</button>
17. onReset
Triggered when a form reset button is clicked.
<form onreset="alert('Form reset!')">
<input type="text">
<button type="reset">Reset</button>
</form>
18. onResize
Occurs when the browser window is resized.
<body onresize="alert('Window resized!')">
19. onSelect
Triggered when text inside an input is selected.
<input type="text" onselect="alert('Text selected!')" value="Select this text">
20. onSubmit
Fires when a form is submitted.
<form onsubmit="alert('Form submitted!'); return false;">
<input type="text">
<button type="submit">Submit</button>
</form>
21. onUnload
Occurs when the page is about to be closed or reloaded.
22.onbeforeunload
The onbeforeunload event asks the user for confirmation before leaving the page.
The browser shows its own default message (custom messages are ignored in modern browsers).
<script>
window.onbeforeunload = function() {
return "Are you sure you want to leave?";
};
</script>
Write a javascript program that adds an event listener when a button is clicked.
<button id="myBtn">Click Me</button>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Button clicked!");
});
</script>
BOM VS DOM
JAVASCRIPT CODE EXAMPLES
a. Using JavaScript, design a web page to accept a number from the user and print its Factorial.
<!-- USING JAVASCRIPT TO FIND THE FACTORIAL OF ANY NUMBER-->
<html>
<head>
<title>
JAVASCRIPT</title>
</head>
<body BGCOLOR="PINK">
<script language="javascript">
var x=parseInt(prompt("Enter any number" ," " ))
var fact=1
for(i=1;i<=x;i++)
fact=fact*i
document.write("<h1>Factorial of "+x+" is:" +fact+ "<h1>")
</script>
</body>
</html>
b. Using JavaScript, a web page that prints Fibonacci series/any given series.
<!-- PRINTING FIBONACCI SERIES-->
<html>
<head>
<title>
PRINTING FIBONACCI SERIES
</title>
<script language="javascript">
var a=0,b=1,c,n,i;
n=parseInt(prompt("Enter limit for fibonacci series"));
document.write("<h2> Fibonacci series</h2>")
document.write(a+" " +b+" ")
for(i=2;i<n;i++)
{
c=a+b;
document.write(c+" ");
a=b;
b=c;
}
</script>
</head>
<body>
</body>
</html>
c. Write a JavaScript program to display all the prime numbers between 1 and 100.
<!DOCTYPE html>
<html>
<head>
<title>prime number</title>
<script>
for(var i=2;i<=100;i++)
{
var flag=0;
for(var j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
document.write(i+"<br>");
}
}
</script>
</head>
</html>
OUTPUT
d. Write a JavaScript program to accept a number from the user and display the sum of its digits.
<!--Write a JavaScript program to accept a number from the
user and display the sum of its digits-->
<!DOCTYPE html>
<html>
<head>
<title>sum of digits</title>
<script>
var n=parseInt(prompt("Enter the number"," "));
var p=0,y;
while(n>0)
{
y=n%10;
n=parseInt(n/10);
p=p+y;
}
document.write("Sum of digits is: "+p);
</script>
</head>
</html>