[Go to site: main page, start]

0% found this document useful (0 votes)
4 views19 pages

Java Script

The document provides an overview of JavaScript concepts including variable declaration with 'const', various operators, data types, control statements like if-else and switch, loops, functions, and popup boxes. It includes multiple HTML examples demonstrating the usage of these concepts in practice. The document serves as a comprehensive guide for understanding fundamental JavaScript programming techniques.

Uploaded by

Shubhendra Dutta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Java Script

The document provides an overview of JavaScript concepts including variable declaration with 'const', various operators, data types, control statements like if-else and switch, loops, functions, and popup boxes. It includes multiple HTML examples demonstrating the usage of these concepts in practice. The document serves as a comprehensive guide for understanding fundamental JavaScript programming techniques.

Uploaded by

Shubhendra Dutta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Const

 Variables defined with const cannot be Redeclared.


 Variables defined with const cannot be Reassigned.
 Variables defined with const have Block Scope.
Program 1:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript const</h2>
<p id="demo"></p>
<script>
try {
const PI = 3.141592653589793;
PI = 3.14;
}
catch (err)
{
[Link]("demo").innerHTML = err;
}
</script>
</body>
</html>
Javascript Operators
JavaScript includes operators same as other languages. An operator performs some operation on
single or multiple operands (data value) and produces a result. For example, in 1 + 2, the + sign is
an operator and 1 is left side operand and 2 is right side operand. The + operator performs the
addition of two numeric values and returns a result.
Syntax:
<Left operand> operator <right operand>

<Left operand> operator


javaScript includes following categories of operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Ternary Operator
7. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations between numeric operands.
Operato
r Description
+ Adds two numeric operands.
- Subtract right operand from left operand
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two
operands.
++ Increment operator. Increase operand value by
one.
-- Decrement operator. Decrease value by one.
//program1:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Arithmatic Operators</h1>
<p>x = 5, y = 10, z;</p>
<p id="p1">x+y=</p>
<p id="p2">y-x=</p>
<p id="p3">x*y=</p>
<p id="p4">y/x=</p>
<p id="p5">x%2=</p>
<script>
var x = 5, y = 10;
var z = x + y
[Link]("p1").innerHTML += z; //returns 15
z = y - x;
[Link]("p2").innerHTML += z; //returns 5
z = x * y;
[Link]("p3").innerHTML += z; //returns 50
z = y / x;
[Link]("p4").innerHTML += z; //returns 2
z = x % 2;
[Link]("p5").innerHTML += z; //returns 1
</script>
</body>
</html>
//program2:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript ++ and -- Operators</h1>
<p>x = 5;</p>
<p id="p1">x++=</p>
<p id="p2">x=</p>
<p id="p3">++x=</p>
<p id="p4">x--=</p>
<p id="p5">x=</p>
<p id="p6">--x=</p>
<script>
var x = 5;
[Link]("p1").innerHTML += x++; //post increment
[Link]("p2").innerHTML += x; // value changes here
[Link]("p3").innerHTML += ++x; //pre increment & value changes
here
[Link]("p4").innerHTML += x--; //post decrement
[Link]("p5").innerHTML += x; //value changes here
[Link]("p6").innerHTML += --x; //pre decrement and value changes
here
</script>
</body>
</html>
//program3:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison Operators</h1>
<p>
var a = 5, b = 10, c = "5", x = a;
</p>
<p id="p1">a == c returns </p>
<p id="p2">a === c returns </p>
<p id="p3">a == x returns </p>
<p id="p4">a != b returns </p>
<p id="p5">a > b returns </p>
<p id="p6">a < b returns </p>
<p id="p7">a >= b returns </p>
<p id="p8">a <= b returns </p>
<script>
var a = 5, b = 10, c = "5", x = a;
[Link]("p1").innerHTML += a == c;
[Link]("p2").innerHTML += a === c;
[Link]("p3").innerHTML += a == x;
[Link]("p4").innerHTML += a != b;
[Link]("p5").innerHTML += a > b;
[Link]("p6").innerHTML += a < b;
[Link]("p7").innerHTML += a >= b;
[Link]("p8").innerHTML += a <= b;
</script>
</body>
/*
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type*/
</html>
//program4:
!DOCTYPE html>
<html>
<body>
<h1>JavaScript Logical Operators</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var a = 5, b = 10;
[Link]("p1").innerHTML = (a != b) && (a < b);
[Link]("p2").innerHTML = (a > b) || (a == b);
[Link]("p3").innerHTML = (a < b) || (a == b);
[Link]("p4").innerHTML = !(a < b);
[Link]("p5").innerHTML = !(a > b);
</script>
</body>
</html>
//program5:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Ternary Operators</h1>
<p id="p1"></p>
<p id="p2"></p>
<script>
var a = 10, b = 5;
var c = a > b? a : b;
var d = a > b? b : a;
[Link]("p1").innerHTML = c;
[Link]("p2").innerHTML = d;
</script>
</body>
</html>
//program6:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Assignment Operators</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<p id="p6"></p>
<script>
var x = 5, y = 10;
x = y;
[Link]("p1").innerHTML = x;
x += 1;
[Link]("p2").innerHTML = x;
x -= 1;
[Link]("p3").innerHTML = x;
x *= 5;
[Link]("p4").innerHTML = x;
x /= 5;
[Link]("p5").innerHTML = x;
x %= 2;
[Link]("p6").innerHTML = x;
</script>
</body>
</html>
Javascript Data type
JavaScript is a loosely typed language. It means it does not require a data type to be declared. You can
assign any literal values to a variable, e.g., string, integer, float, boolean, etc.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Variables </h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var myvariable = 1; // numeric value
[Link]("p1").textContent = myvariable;
myvariable = 'one'; // string value
[Link]("p2").textContent = myvariable;
myvariable = 1.1; // decimal value
[Link]("p3").textContent = myvariable;
myvariable = true; // Boolean value
[Link]("p4").textContent = myvariable;
myvariable = null; // null value
[Link]("p5").textContent = myvariable;
</script>
</body>
</html>
If-statement
Program:
<html>
<body>
<script>
//[Link] statement
var a=20;
if(a>10)
{
[Link]("value of a is greater than 10");
}
[Link]("<br/>");
//[Link]...else Statement
var a=20;
if(a%2==0)
{
[Link]("a is even number");
}
else
{
[Link]("a is odd number");
}
[Link]("<br/>");
//[Link]...else if statement
var a=20;
if(a==10)
{
[Link]("a is equal to 10");
}
else if(a==15)
{
[Link]("a is equal to 15");
}
else if(a==20)
{
[Link]("a is equal to 20");
}
else
{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>

Switch-statement
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade)
{
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
</body>
</html>
Loop
Program:
<!DOCTYPE html>
<html>
<body>
<script>
//[Link] loop
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
[Link]("<br/>");
//2. While loop
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
[Link]("<br/>");
//[Link]-while loop
var i=21;
do
{
[Link](i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
1. break Statement
 Purpose: Exits the loop or switch statement immediately.
 When to Use: When you want to stop the execution of a loop early.
Example:
for (let i = 1; i <= 5; i++) {
if (i == 3) {
break; // Stops the loop when i is 3
}
[Link](i);
}

2. continue Statement
 Purpose: Skips the current iteration and moves to the next one.
 When to Use: When you want to skip specific cases without stopping the whole
loop.
Example:
for (let i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips printing when i is 3
}
[Link](i);
}

Functions in JavaScript
1. Defining and Invoking Functions
🔹 Function Definition
A function is a block of code that performs a specific task.
Syntax:
function functionName() {
// code to execute
}
🔹 Function Invocation (Calling)
You run a function by using its name followed by parentheses.
function greet() {
[Link]("Hello, World!");
}

greet(); // Function call

2. Parameters and Return Values


🔹 Parameters:
 Variables passed into the function.
function greet(name) { // 'name' is a parameter
[Link]("Hello, " + name);
}

greet("Alice"); // 'Alice' is an argument


🔹 Return Values:
 Functions can return a value using the return statement.
function add(a, b) {
return a + b; // returns the sum
}

let sum = add(5, 3);


[Link](sum); // Output: 8

3. Function Expressions and Arrow Functions


Function Expression:
 A function stored inside a variable.
let greet = function(name) {
[Link]("Hello, " + name);
};

greet("Bob");
🔹 Arrow Function:
 A shorter way to write functions.
 Introduced in ES6.
Syntax:
let greet = (name) => {
[Link]("Hello, " + name);
};
✔️If the function has one statement, you can write it like this:
let greet = name => [Link]("Hello, " + name);
✔️If the function returns a value:
let add = (a, b) => a + b;

[Link](add(2, 3)); // Output: 5

Program 1: Defining and Invoking Functions


<!DOCTYPE html>
<html>
<head>
<title>Function Definition and Call</title>
</head>
<body>
<h2>Click the button to greet!</h2>
<button >

<script>
// Function Definition
function greet() {
alert("Hello, welcome to JavaScript functions!");
}
</script>
</body>
</html>
✔️Explanation:
When you click the button, the greet function is invoked and displays an alert.

Program 2: Parameters and Return Values


<!DOCTYPE html>
<html>
<head>
<title>Function with Parameters and Return</title>
</head>
<body>
<h2>Check the Sum in the Console</h2>
<button Sum</button>

<script>
// Function with parameters and return value
function addNumbers(a, b) {
return a + b; // Returns the sum
}

function showSum() {
let result = addNumbers(10, 20);
[Link]("The sum is: " + result);
}
</script>
</body>
</html>
✔️Explanation:
When the button is clicked, the showSum function is called, which uses another function
addNumbers that accepts parameters and returns a value.

Program 3: Function Expression and Arrow Function


<!DOCTYPE html>
<html>
<head>
<title>Function Expressions and Arrow Functions</title>
</head>
<body>
<h2>Check the Console for Outputs</h2>
<button Functions</button>

<script>
// Function Expression
let greet = function(name) {
[Link]("Hello, " + name + " (from function expression)");
};

// Arrow Function
let multiply = (a, b) => {
return a * b;
};

function runFunctions() {
greet("Alice"); // Call function expression
let product = multiply(4, 5); // Call arrow function
[Link]("The product is: " + product);
}
</script>
</body>
</html>

Popup Boxes in JavaScript


🔹 1. Alert Box
 Displays a message to the user.
 Only OK button is available.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Alert Box Example</title>
</head>
<body>
<h2>Alert Box Example</h2>
<button Alert</button>

<script>
function showAlert() {
alert("This is an alert box!");
}
</script>
</body>
</html>
✔️Result: Clicking the button shows a message.

🔹 2. Confirm Box
 Displays a message with OK and Cancel buttons.
 Returns true if OK is clicked, false if Cancel is clicked.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Confirm Box Example</title>
</head>
<body>
<h2>Confirm Box Example</h2>
<button Confirm</button>
<script>
function showConfirm() {
let result = confirm("Do you want to continue?");
if (result) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
}
</script>
</body>
</html>
✔️Result: Clicking the button asks the user for confirmation.

🔹 3. Prompt Box
 Displays a message with a text input box.
 Accepts user input and returns it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Prompt Box Example</title>
</head>
<body>
<h2>Prompt Box Example</h2>
<button Prompt</button>

<script>
function showPrompt() {
let name = prompt("Please enter your name:", "Guest");
if (name != null && name != "") {
alert("Hello, " + name + "!");
} else {
alert("You didn't enter a name.");
}
}
</script>
</body>
</html>

Objects and Properties in JavaScript

1. Object Creation
🔹 Using Object Literals
 Simplest way to create an object.
 Define properties inside curly braces {}.
let person = {
name: "John",
age: 30,
city: "New York"
};
🔹 Using Constructors
 Create objects using the built-in Object() constructor.
let person = new Object();
[Link] = "John";
[Link] = 30;
[Link] = "New York";

2. Accessing and Modifying Properties


 Use dot notation or bracket notation to access or change properties.
// Access
[Link]([Link]); // Output: John
[Link](person["age"]); // Output: 30

// Modify
[Link] = 31;
person["city"] = "Chicago";

3. Custom Constructors (Function Constructors)


 Create object templates (like classes) to generate multiple similar objects.
function Person(name, age, city) {
[Link] = name;
[Link] = age;
[Link] = city;
}

// Creating new objects


let person1 = new Person("Alice", 25, "Los Angeles");
let person2 = new Person("Bob", 28, "Miami");

[Link]([Link]); // Alice
[Link]([Link]); // Miami

Complete Example Program


<!DOCTYPE html>
<html>
<head>
<title>Objects and Constructors Example</title>
</head>
<body>
<h2>Objects and Properties Demo</h2>
<button Objects</button>

<script>
// Using Object Literal
let personLiteral = {
name: "John",
age: 30,
city: "New York"
};

// Using Object Constructor


let personConstructor = new Object();
[Link] = "Jane";
[Link] = 28;
[Link] = "Boston";

// Custom Constructor Function


function Person(name, age, city) {
[Link] = name;
[Link] = age;
[Link] = city;
}

let person1 = new Person("Alice", 25, "Los Angeles");


let person2 = new Person("Bob", 32, "Miami");

function showObjects() {
// Accessing properties
alert("Literal Object:\nName: " + [Link] + ", Age: " + [Link]
+ ", City: " + [Link]);
alert("Constructor Object:\nName: " + [Link] + ", Age: " +
[Link] + ", City: " + [Link]);
alert("Custom Constructor Object 1:\nName: " + [Link] + ", Age: " +
[Link] + ", City: " + [Link]);
alert("Custom Constructor Object 2:\nName: " + [Link] + ", Age: " +
[Link] + ", City: " + [Link]);
}
</script>
</body>
</html>

Arrays in JavaScript

1. Array Creation
🔹 Using Array Literal (Recommended)
let fruits = ["Apple", "Banana", "Mango"];
🔹 Using Array Constructor
let fruits = new Array("Apple", "Banana", "Mango");

2. Array Manipulation
Accessing elements:
[Link](fruits[0]); // Apple
[Link](fruits[2]); // Mango
Changing elements:
fruits[1] = "Orange";
[Link](fruits); // ["Apple", "Orange", "Mango"]

3. Common Array Methods


Method Description Example
push() Adds element(s) at the end [Link]("Grapes");
pop() Removes element from the end [Link]();
shift() Removes element from the start [Link]();
unshift() Adds element(s) at the start [Link]("Strawberry");
splice() Adds/removes elements at specified [Link](1, 1, "Kiwi");
index
slice() Copies a portion of an array let newFruits = [Link](1,3);

4. Complete Example Program


<!DOCTYPE html>
<html>
<head>
<title>Array Methods Example</title>
</head>
<body>
<h2>Array Methods Demo</h2>
<button Array Demo</button>

<script>
function arrayDemo() {
let fruits = ["Apple", "Banana", "Mango"];
alert("Initial array: " + fruits);

// push() - add at end


[Link]("Grapes");
alert("After push('Grapes'): " + fruits);

// pop() - remove from end


let popped = [Link]();
alert("After pop(), removed: " + popped + ", array: " + fruits);

// shift() - remove from start


let shifted = [Link]();
alert("After shift(), removed: " + shifted + ", array: " + fruits);

// unshift() - add at start


[Link]("Strawberry");
alert("After unshift('Strawberry'): " + fruits);

// splice() - remove 1 element at index 1 and insert 'Kiwi'


[Link](1, 1, "Kiwi");
alert("After splice(1,1,'Kiwi'): " + fruits);

// slice() - get elements from index 1 to 3 (3 not included)


let newFruits = [Link](1, 3);
alert("Slice(1,3) returns: " + newFruits);
}
</script>
</body>
</html>

Built-in Objects in JavaScript

1. Window Object
Description:
 Represents the browser window.
 Controls browser features like alerts, opening new windows, screen size, etc.
Syntax & Use:
[Link]("Hello!"); // Show alert box
[Link]([Link]); // Get window width
[Link]("[Link] "_blank"); // Open new tab/window
Example:
<button Window Info</button>
<script>
function showWindowInfo() {
alert("Window width: " + [Link] + "px");
}
</script>

2. String Object
Description:
 Used to manipulate text strings.
 Has properties like length and methods like toUpperCase(), slice(), replace(), etc.
Syntax & Use:
let str = "Hello World";
[Link]([Link]); // Length of string
[Link]([Link]()); // "HELLO WORLD"
[Link]([Link](0,5)); // "Hello"
Example:
<script>
let message = "JavaScript";
alert("Uppercase: " + [Link]());
</script>

3. Number Object
Description:
 Provides numeric properties and methods such as toFixed(), parseInt(), isNaN().
Syntax & Use:
let num = 12.3456;
[Link]([Link](2)); // "12.35"
[Link]([Link]("abc")); // false
Example:
<script>
let pi = 3.14159;
alert("Pi rounded: " + [Link](3));
</script>

4. Boolean Object
Description:
 Represents boolean values (true or false).
 Mostly used in logical operations and type conversions.
Syntax & Use:
let isActive = Boolean(1); // true
let isFalse = Boolean(0); // false
Example:
<script>
alert("Boolean of 0 is: " + Boolean(0)); // false
alert("Boolean of 'hello' is: " + Boolean("hello")); // true
</script>

5. Date Object
Description:
 Handles dates and times.
 Methods include getDate(), getFullYear(), getHours(), setDate(), etc.
Syntax & Use:
let today = new Date();
[Link]([Link]()); // Current year
[Link]([Link]()); // Local date & time string
Example:
<script>
let now = new Date();
alert("Today is: " + [Link]());
</script>

6. Math Object
Description:
 Provides mathematical constants and functions like [Link], [Link](),
[Link](), [Link]().
Syntax & Use:
[Link]([Link]); // 3.141592653589793
[Link]([Link](4.7)); // 5
[Link]([Link]()); // Random number between 0 and 1
Example:
<script>
alert("Random number: " + [Link]([Link]() * 100));
</script>
7. RegExp Object
Description:
 Used for pattern matching and text search.
 Supports methods like test(), exec().
Syntax & Use:
let pattern = /hello/i; // case-insensitive match for 'hello'
[Link]([Link]("Hello World")); // true
Example:
<script>
let regex = /cat/;
let str = "The cat is here.";
alert("Contains 'cat'? " + [Link](str));
</script>

8. Form Object
Description:
 Represents HTML forms.
 Allows access and manipulation of form elements via DOM.
Syntax & Use:
// Access form named 'myForm' and input named 'username'
let username = [Link]["myForm"]["username"].value;
Example:
<form name="myForm">
Name: <input type="text" name="username" />
<button type="button" ></form>
<script>
function showName() {
let name = [Link]["myForm"]["username"].value;
alert("Name entered: " + name);
}
</script>

9. User Defined Objects


Description:
 Custom objects created using constructor functions or ES6 classes.
Syntax & Use (Constructor Function):
function Person(name, age) {
[Link] = name;
[Link] = age;
}

let p1 = new Person("John", 30);


Example:
<script>
function Car(make, model) {
[Link] = make;
[Link] = model;
}

let myCar = new Car("Toyota", "Corolla");


alert("My car is " + [Link] + " " + [Link]);
</script>

Summary Table
Object Purpose Example Method/Property
Window Browser window control alert(), innerWidth
String String manipulation length, toUpperCase()
Number Numeric properties/methods toFixed(), isNaN()
Boolean Boolean values and conversions Boolean()
Date Date and time getFullYear(), toDateString()
Math Math constants and functions PI, random(), round()
RegExp Pattern matching with regex test(), exec()
Form Access/manipulate HTML forms [Link]
User Custom objects Constructor functions or classes
Defined

You might also like