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

Web Scripting Updated

The document outlines the history and evolution of JavaScript, detailing its creation in 1995, standardization in 1997, and the rise of modern frameworks and tools. It provides a step-by-step guide to setting up a development environment for JavaScript on Windows, including creating HTML files and running JavaScript in browsers. Additionally, it covers variable declaration methods (var, let, const), data types, and basic operations in JavaScript.

Uploaded by

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

Web Scripting Updated

The document outlines the history and evolution of JavaScript, detailing its creation in 1995, standardization in 1997, and the rise of modern frameworks and tools. It provides a step-by-step guide to setting up a development environment for JavaScript on Windows, including creating HTML files and running JavaScript in browsers. Additionally, it covers variable declaration methods (var, let, const), data types, and basic operations in JavaScript.

Uploaded by

Aaditya Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

WEB SCRIPTING

- RONAK BHALALA
History and Evolution of javascript
History and Evolution of JavaScript

● 1995: Created by Brendan Eich at Netscape as LiveScript, later renamed JavaScript.


● 1997: ECMAScript standardization begins to ensure consistency across browsers.
● 2005-2010: Growth with AJAX and libraries like jQuery driving Web 2.0 interactivity.
● 2015 (ES6): Major update adding classes, modules, arrow functions, and more.
● 2010s-Present: Rise of frameworks like React, Angular, and Vue.js, and continuous
updates to ECMAScript (ES7-ES11).
● Today: JavaScript powers both client-side and server-side (Node.js) applications, with
modern tools like TypeScript enhancing development.
Setting up Development environment
Step-by-Step Guide to Run JavaScript with HTML on Windows
1. Install a Code Editor
To write your code, you’ll need a text editor. A free, popular choice is Visual Studio Code (VS Code).

● Download Visual Studio Code. even you can use normal notepad also.

● Follow the installation instructions.

2. Create a Project Folder


1. Create a new folder where you'll store your HTML and JavaScript files. For example, create a folder named
MyJavaScriptProject on your Desktop or any preferred location.

3. Create an HTML File


1. Open VS Code.

2. In the VS Code editor, go to File > Open Folder and select the folder you just created (MyJavaScriptProject).
3. Inside this folder, create a new file and name it index.html.

4. Add HTML Structure


In your index.html file, add the following basic HTML structure to include your JavaScript:
Setting up Development environment
<!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>
<h1>Hello World in JavaScript</h1>

<!-- JavaScript code placed inside script tag -->


<script>
// Your JavaScript code here
console.log("Hello, World!");
</script>
</body>
</html>
Setting up Development environment
5. Run Your Code in a Browser

1. Save the index.html file.


2. Open the folder where index.html is located.
3. Double-click on index.html. This will open the file in your default web browser.
4. To see the JavaScript output (like console.log("Hello, World!");), open the Developer Tools in your
browser (press F12 or right-click and select Inspect).
5. Go to the Console tab, and you should see Hello, World! printed there.

Alternative: Running JavaScript Directly in Browser Console


If you want to quickly try out JavaScript without creating an HTML file, you can use the browser's Developer Tools
Console:

1. Open any webpage in your browser (you can use a blank page).
2. Open the Developer Tools (press F12 or right-click and select Inspect).
3. Go to the Console tab.
4. Type console.log("Hello, World!"); and press Enter. You will see Hello, World! printed in the console.

Conclusion
You can now run JavaScript in a browser using the <script> tag in an HTML file. No need for frameworks—just pure
JavaScript!
Variables in JavaScript
In JavaScript, variables are used to store and manipulate data. You can create a variable using one of three keywords: var,
let, or const. Each has different scoping rules and behaviors.

1. var (Oldest Way to Declare a Variable)

● Scope: var has function scope (if declared inside a function) or global scope (if declared outside any function).
● Hoisting: Variables declared with var are hoisted to the top of their scope, meaning they are accessible before they
are declared, but their value will be undefined until the line of declaration is executed.

var name = "Alice";

console.log(name); // Output: Alice

var name = "Bob"; // Re-declaring and re-assigning

console.log(name); // Output: Bob


Setting up Development environment
2. let (Modern Way to Declare Variables)

● Scope: let has block scope. This means it is limited to the block in which it is defined (e.g., inside loops or
conditionals).
● Hoisting: let is also hoisted but remains in a temporal dead zone until it is initialized. It cannot be accessed before
its declaration.

let name = "Alice";


console.log(name); // Output: Alice

name = "Bob"; // Re-assigning (but not redeclaring)


console.log(name); // Output: Bob

// let name = "Charlie"; // Error: Cannot redeclare block-scoped variable 'name'


Setting up Development environment
3. const (For Constant Variables)

● Scope: const has block scope, just like let.


● Immutability: Variables declared with const must be initialized at the time of declaration and cannot be
re-assigned. However, if the variable holds an object or array, the content (like properties or elements) can still be
modified.

const name = "Alice";


console.log(name); // Output: Alice

// name = "Bob"; // Error: Assignment to constant variable.

// Arrays and objects can still be modified:


const person = { name: "Alice" };
person.name = "Bob"; // This is allowed
console.log(person); // Output: { name: "Bob" }
Setting up Development environment
4. Types of Data Stored in Variables

JavaScript variables can store different types of data:

String: Text data enclosed in quotes.


let name = "John";

Number: Numeric values.


let age = 25;

Boolean: True or false values.


let isActive = true;

Object: Key-value pairs (can store complex data).


let person = { name: "Alice", age: 30 };

Array: A collection of values.


let fruits = ["apple", "banana", "orange"];

Null & Undefined: Special types to represent "no value" or "missing value".
let emptyValue = null;
let uninitializedValue;
Setting up Development environment
// String: Text data enclosed in quotes.
let name = "John";
console.log(name); // Output: John

// Number: Numeric values.


let age = 25;
console.log(age); // Output: 25

// Boolean: True or false values.


let isActive = true;
console.log(isActive); // Output: true

// Object: Key-value pairs (can store complex data).


let person = { name: "Alice", age: 30 };
console.log(person); // Output: { name: "Alice", age: 30 }

// Array: A collection of values.


let fruits = ["apple", "banana", "orange"];
console.log(fruits); // Output: [ 'apple', 'banana', 'orange' ]

// Null & Undefined: Special types to represent "no value" or "missing value".
let emptyValue = null;
console.log(emptyValue); // Output: null

let uninitializedValue;
console.log(uninitializedValue); // Output: undefined
Setting up Development environment
Use let for variables that can change.
Use const for variables that should remain constant.
Avoid using var unless necessary (older codebases or specific scenarios).

var: Can be used anywhere in the function or globally. You can reassign its value. It gets moved to the top of the code but will be
undefined until it’s actually assigned.
let: Can be used only within the block (like inside loops or conditions). You can reassign its value. It gets moved to the top but can’t be
used before the declaration.
const: Can be used only within the block. You can’t reassign its value once it's set. It must be assigned a value when declared.
Extra
For writing into document:
<script> document.write("Hello World"); </script> /

For writing alert:


<script> alert("Hello World"); </script>
Let's code something new….
<html>
<head> bt.value="Pahila data dal…"
<style> }
.outer{ else{
margin:auto; document.getElementById("a").style.border="3px solid green"
document.getElementById("b").style.border="3px solid green"
height:300px; bt.value="Yeh theek hai ab."
width:400px; bt.style.left="120px";
border:2px solid black; }
position:relative }
} flag=1
p{ function f(){
margin-left:80px; if(flag==1){
} bt.style.left="210px"
.in{ flag=2
margin-left:80px; }
else if(flag==2){
padding:10px bt.style.left="80px"
} flag=1
#bt{ }
margin-top:20px; }
position:absolute; </script>
left:150px; </head>
} <body>
#bt:hover{ <div class="outer">
background:green; <h1 style="text-align:center">Legend form</h1>
font-size:13px; <p>Enter Id</p>
cursor:pointer; <input class="in" type="text" placeholder="Enter id" id="a"/>
<p>Enter Confirm Pass</p>
color:white; <input class="in" type="password" placeholder="Enter password"
} id="b"/>
</style> <br>
<script> <input type="submit" onmouseenter="fa()" onclick="alert('waaaa')"
function fa(){ id="bt" />
if(a.value=="" || b.value==""){ </div>
f() </body>
document.getElementById("a").style.border="3px solid red" </html>
document.getElementById("b").style.border="3px solid red"
Let's code something new….
<!DOCTYPE html>
<html lang="en"> ctx.quadraticCurveTo(petalLength / 2, -petalWidth, 0, -petalLength);
<head> ctx.quadraticCurveTo(-petalLength / 2, -petalWidth, 0, 0);
<meta charset="UTF-8"> ctx.fillStyle = "#FF6347"; // Petal color (tomato red)
<meta name="viewport" content="width=device-width, ctx.fill();
ctx.restore();
initial-scale=1.0"> }
<title>Animated Flower</title> // Function to draw the flower
<style> function drawFlower() {
body { const centerX = canvas.width / 2;
display: flex; const centerY = canvas.height / 2;
justify-content: center; ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
align-items: center; before redrawing
height: 100vh; // Draw flower petals in a circular pattern
margin: 0; for (let i = 0; i < petalCount; i++) {
background-color: #f0f8ff; let currentAngle = (i * Math.PI * 2) / petalCount + angle; // Rotate
petals
} drawPetal(centerX, centerY, currentAngle);
</style> }
</head> // Draw center of the flower
<body> ctx.beginPath();
<canvas id="flowerCanvas" width="400" height="400"></canvas> ctx.arc(centerX, centerY, 20, 0, Math.PI * 2);
<script> ctx.fillStyle = "#FFD700"; // Flower center color (golden yellow)
const canvas = document.getElementById("flowerCanvas"); ctx.fill();
const ctx = canvas.getContext("2d");
let angle = 0; // Variable for rotating flower petals // Increment the angle for the animation effect
const petalCount = 6; // Number of petals angle += 0.02;
const petalLength = 60; // Length of each petal }
// Animation loop
const petalWidth = 20; // Width of each petal function animate() {
// Function to draw a petal at a specific angle drawFlower();
function drawPetal(x, y, angle) { requestAnimationFrame(animate); // Repeat the animation
ctx.save(); }
ctx.translate(x, y); animate(); // Start the animation
ctx.rotate(angle); </script>
</body>
ctx.beginPath(); </html>
ctx.moveTo(0, 0);
Practical
Task - 1
Create a js for print hello world on console window.
Create a js for print hello world on Html page.
Create a js for alert hello world on Html page.
Create multiple scripts for defining and printing various
variable using let, const, var.
Task - 2
Perform basic calc.
Create Array fruit and Declaration element also Acces
declared array
Create Object fruit and Declaration element also Acces
declared object
Take 2 string variable like “KrISHna” Perform string
operation like count length, concat both string also convert
string into lower and upper case
Task - 3
Data Types and operators
In JavaScript, data types are categorized into two types: Primitive and Non-Primitive (Reference) data types.

1. Primitive Data Types

These are simple data types that are immutable and hold a single value. They are directly assigned to variables.

a) Number

Represents both integer and floating-point numbers.

let age = 25; // Integer


let price = 19.99; // Float

Operations:

● Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulo (%), Exponentiation (**)
● let sum = 10 + 5; // 15
● let product = 10 * 5; // 50
● let remainder = 10 % 3; // 1
Data Types and operators
● b) String
● Represents a sequence of characters enclosed in single, double, or backtick quotes.

let name = "Alice";

let greeting = 'Hello, World!';

let templateString = `Hello, ${name}!`;

Operations:

● Concatenation (+)
● String length (.length)
● String methods (e.g., .toUpperCase(), .toLowerCase())

let fullName = "John" + " " + "Doe"; // "John Doe"

let length = fullName.length; // 8

let upper = name.toUpperCase(); // "ALICE"


Data Types and operators
c) Boolean

Represents a logical entity that can be either true or false.

let isActive = true;

let hasPermission = false;


Operations:

● Logical AND (&&), OR (||), NOT (!)

let isAdult = true;

let canVote = isAdult && hasPermission; // false

d) Undefined

Indicates that a variable has been declared but not assigned a value.

let x;

console.log(x); // undefined

Operations:

● Undefined can be assigned to variables, but cannot be operated on like a number or string.
Data Types and operators
f) Symbol (ES6)

● A unique and immutable primitive value used as the key for object properties.

let sym = Symbol('description');

Operations:

● Cannot be used with arithmetic operations or string concatenation. Primarily used for creating unique keys in objects.

g) BigInt (ES11)

Used to represent integers that are too large for the Number type

let bigNumber = 1234567890123456789012345678901234567890n;

Operations:

● Supports arithmetic operations but cannot be mixed with regular Number type.
Data Types and operators
e) Null

Represents the intentional absence of any object value.

let person = null;


Data Types and operators
2. Non-Primitive (or Reference) Data Types:
These are mutable and are passed by reference.

Object: A collection of key-value pairs.

let person = {

name: "John",

age: 30

};

Array: A special type of object used to store ordered collections of values.

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

let colors = ['red', 'blue', 'green'];

Function: A block of code designed to perform a particular task.

function greet() {

console.log("Hello!");

}
Data Types and operators
Operations on Data Types in JavaScript:

1. Arithmetic Operations (applies to Number):


○ Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%), Exponentiation (**).

let sum = 10 + 5; // 15

let diff = 10 - 5; // 5

let product = 10 * 5; // 50

let quotient = 10 / 5; // 2

let remainder = 10 % 3; // 1

let power = 2 ** 3; // 8
Data Types and operators
String Operations:

● Concatenation (+), length, substring(), toUpperCase(), toLowerCase(), trim().

let fullName = "John" + " " + "Doe"; // "John Doe"

let greeting = "hello".toUpperCase(); // "HELLO"

let length = "hello".length; // 5

let trimmed = " hello ".trim(); // "hello"


Comparison Operations:

● ==, ===, !=, !==, >, <, >=, <=.

let result = 10 == 10; // true (loose equality)

let strictResult = 10 === '10'; // false (strict equality)


Data Types and operators
Logical Operations (applies to Boolean):

● && (AND), || (OR), ! (NOT).

let a = true;
let b = false;
let andResult = a && b; // false
let orResult = a || b; // true
let notResult = !a; // false

Type Conversion:

● String(), Number(), Boolean().

let numStr = String(123); // "123"


let strToNum = Number("123"); // 123
let boolValue = Boolean(""); // false
Data Types and operators
Array Operations:

● push(), pop(), shift(), unshift(), map(), filter(), forEach().

let arr = [1, 2, 3];

arr.push(4); // [1, 2, 3, 4]

arr.pop(); // [1, 2, 3]

arr.shift(); // [2, 3]

arr.unshift(0); // [0, 2, 3]

let doubled = arr.map(x => x * 2); // [0, 4, 6]

Object Operations:

● Adding/Accessing properties: obj.property, obj['property'].

let obj = { name: 'Alice', age: 25 };

console.log(obj.name); // "Alice"

obj.address = 'USA'; // Add a new property


Control structure
In JavaScript, control statements are used to control the flow of execution in a program based on certain conditions or loops. The main
types of control statements in JavaScript are:

1. Conditional Statements
These are used to perform different actions based on different conditions.

● if Statement: Executes a block of code if a specified condition is true.

if (condition) {

// Code to be executed if the condition is true

● else Statement: Executes a block of code if the condition in the if statement is false.

if (condition) {

// Code to be executed if the condition is true

} else {

// Code to be executed if the condition is false

}
Control structure
● else if Statement: Specifies a new condition if the original if condition is false.

if (condition1) {

// Code to be executed if condition1 is true

} else if (condition2) {

// Code to be executed if condition2 is true

} else {

// Code to be executed if neither condition1 nor condition2 is true

}
Control structure
Example:
User define example
let number = -5; // Prompt the user to enter a number
let number = parseInt(prompt("Enter a number:"));
// Check if the number is positive, negative, or zero
if (number > 0) {
if (number > 0) {
console.log("You entered the number: " + number);
console.log("The number is positive.");
console.log("The number is positive.");
alert("You entered the number: " + number + "\nThe
} else { number is positive.");
} else if (number < 0) {
console.log("The number is negative."); console.log("You entered the number: " + number);
console.log("The number is negative.");
} alert("You entered the number: " + number + "\nThe
number is negative.");
} else {
console.log("You entered the number: " + number);
console.log("The number is zero.");
alert("You entered the number: " + number + "\nThe
number is zero.");
}
Control structure
● switch Statement: Evaluates an expression and matches the result to one of several case blocks.

switch (expression) {

case value1:

// Code to be executed if expression == value1

break;

case value2:

// Code to be executed if expression == value2

break;

default:

// Code to be executed if expression doesn't match any case

}
Control structure
Example:
User define example
let number = 4; // Prompt the user to enter a number
let number = parseInt(prompt("Enter a number:"));
switch (number % 2) {
// Display the entered number
case 0: console.log("Even"); break;
console.log("You entered the number: " + number);
case 1: console.log("Odd"); break;
// Check if the number is odd or even
default: console.log("Invalid"); switch (number % 2) {
case 0:
} alert("The number " + number + " is Even.");
break;
case 1:
alert("The number " + number + " is Odd.");
break;
default:
alert("Invalid input.");
}
Control structure
2. Looping Statements

These are used to repeat a block of code multiple times.

● for Loop: Repeats a block of code a specified number of times.

for (initialization; condition; increment/decrement) {

// Code to be executed in each iteration

EX: for (let i = 0; i < 10; i++) {

console.log(i); // Code to be executed in each iteration

}
Control structure
User define example
Example: // Get the height from the user
let height = parseInt(prompt("Enter the height of the
pyramid:"));
let height = 5; // You can change this value to
increase or decrease the size of the pyramid // Check if the height is a valid number
if (isNaN(height) || height <= 0) {
console.log("Please enter a valid positive number.");
for (let i = 1; i <= height; i++) { } else {
let row = ''; // Generate the pyramid
for (let i = 1; i <= height; i++) {
let row = '';
// Add leading spaces
for (let j = 1; j <= height - i; j++) { // Add leading spaces
row += ' '; for (let j = 1; j <= height - i; j++) {
row += ' ';
}
}

// Add stars // Add stars


for (let k = 1; k <= (2 * i - 1); k++) {
for (let k = 1; k <= (2 * i - 1); k++) {
row += '*';
row += '*'; }
}
// Print the current row
console.log(row);
// Print the current row }
console.log(row); }
}
Control structure
● while Loop: Executes a block of code as long as the specified condition is true.

while (condition) {

// Code to be executed as long as the condition is true

Ex: let i = 0;

while (i < 10) {

console.log(i); // Code to be executed while the condition is true

i++;

}
Control structure
User define example
Example: let number = parseInt(prompt("Enter a number to
let number = 5; // Static number for which factorial is calculate its factorial:"));
calculated let factorial = 1;
let factorial = 1;
if (number < 0) {
if (number < 0) { console.log("Factorial is not defined for negative
console.log("Factorial is not defined for negative numbers.");
numbers."); } else {
} else { let i = 1;
let i = 1; while (i <= number) {
while (i <= number) { factorial *= i;
factorial *= i; i++;
i++; }
} console.log(`The factorial of ${number} is
console.log(`The factorial of ${number} is ${factorial}`);
${factorial}`); }
}
Control structure
● do...while Loop: Executes a block of code once, and then repeats the execution as long as the specified condition is true.

while (condition) {

// Code to be executed as long as the condition is true

Ex: let i = 0;

do {

console.log(i); // Code to be executed at least once

i++;

} while (i < 10);


Control structure
User define example
Example: let number = parseInt(prompt("Enter a number to
let number = 5; // Static number for which factorial is calculate its factorial:"));
calculated let factorial = 1;
let factorial = 1;
if (number < 0) {
if (number < 0) { console.log("Factorial is not defined for negative
console.log("Factorial is not defined for negative numbers.");
numbers."); } else {
} else { let i = 1;
let i = 1; while (i <= number) {
while (i <= number) { factorial *= i;
factorial *= i; i++;
i++; }
} console.log(`The factorial of ${number} is
console.log(`The factorial of ${number} is ${factorial}`);
${factorial}`); }
}
Control structure
3. Control Flow Statements

These statements control the flow of a loop or function.

● break Statement: Exits a loop or a switch statement prematurely.

for (let i = 0; i < 10; i++) {

if (i === 5) {

break; // Exits the loop when i is 5

console.log(i);

}
Control structure
● continue Statement: Skips the current iteration of a loop and continues with the next iteration.

for (let i = 0; i < 10; i++) {

if (i === 5) {

continue; // Skips the iteration when i is 5

console.log(i);

}
Control structure
● return Statement: Exits from the current function and optionally returns a value.

function add(a, b) {

return a + b; // Exits the function and returns the result

}
Control structure
In JavaScript, there is no typeof operator for directly
checking the type of a variable. However, JavaScript let isTrue = true;
provides the typeof operator, which can be used to let obj = { name: "John", age: 30 };
check the type of a variable at runtime.
let arr = [1, 2, 3];
1. typeof Operator:
let func = function() {};
The typeof operator in JavaScript is used to check
console.log(typeof num); // "number"
the data type of a variable or an expression.
console.log(typeof str); // "string"
Syntax:
console.log(typeof isTrue); // "boolean"
typeof variable
console.log(typeof obj); // "object"
let num = 10;
console.log(typeof arr); // "object"
let str = "Hello, World!"; (arrays are also objects in JavaScript)

console.log(typeof func); // "function"

console.log(typeof undefinedVar); //
"undefined"

You might also like