Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
53 views

JavaScript Lecture Notes BCA-5

JavaScript is a scripting language used primarily for client-side web development. It allows developers to create dynamic and interactive web pages through features like DOM manipulation, event handling, and asynchronous operations. Common JavaScript constructs include variables, functions, arrays, objects, conditional statements, loops, and more. Developers can declare variables with var, let, or const, with let and const being preferred modern choices.

Uploaded by

amit.ray455
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

JavaScript Lecture Notes BCA-5

JavaScript is a scripting language used primarily for client-side web development. It allows developers to create dynamic and interactive web pages through features like DOM manipulation, event handling, and asynchronous operations. Common JavaScript constructs include variables, functions, arrays, objects, conditional statements, loops, and more. Developers can declare variables with var, let, or const, with let and const being preferred modern choices.

Uploaded by

amit.ray455
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

JavaScript Basics

1. Introduction:

- JavaScript is a high-level, interpreted scripting language.

- It is primarily used for client-side web development but can also be used on the server-side
(Node.js).

Why Use JavaScript?

JavaScript is a fundamental language for web development and offers numerous benefits that
enhance the functionality and interactivity of websites. Here's a concise explanation of why JavaScript
is widely used:

a) Client-Side Interactivity: JavaScript allows developers to create dynamic and interactive web
pages, enhancing user experience without requiring constant page reloads.

b) User Interface Enhancement: It enables the modification of page content and styles in
response to user actions, making web applications more responsive and user-friendly.

c) DOM Manipulation: JavaScript can manipulate the Document Object Model (DOM) to
change, add, or remove elements from a webpage dynamically, resulting in real-time updates.

d) Event Handling: JavaScript facilitates the handling of user interactions, like clicks and form
submissions, by attaching event listeners to elements on the page.

e) Browser Compatibility: JavaScript is supported by all modern web browsers, ensuring broad
compatibility and consistent behaviour across different platforms.

f) Asynchronous Operations: With asynchronous programming techniques like Promises and


async/await, JavaScript can perform tasks like data fetching without blocking the main thread,
enhancing performance.

g) Rich Ecosystem: JavaScript boasts a vast ecosystem of libraries (e.g., React, Angular, Vue.js)
and frameworks that simplify complex tasks, accelerate development, and encourage code
organization.

h) Server-Side Development: Through Node.js, JavaScript can be used for server-side scripting,
enabling a unified language for both client and server development.
i) Cross-Platform Development: JavaScript's versatility extends beyond web browsers, allowing
developers to create mobile applications using tools like React Native and frameworks like
Electron for desktop apps.

j) Community and Resources: JavaScript has a large, active community, resulting in abundant
online resources, tutorials, and open-source projects to aid learning and development.

k) Fast Development: Its concise syntax and dynamic typing enable faster development cycles,
allowing developers to iterate quickly.

l) Real-Time Updates: JavaScript's capabilities are foundational for building real-time features
like chat applications, live updates, and collaborative tools.

m) Interactive Forms: JavaScript enhances forms by providing validation, auto-complete, and


real-time feedback, improving user input and reducing errors.

n) Animations and Effects: It facilitates the creation of animations, transitions, and visual
effects, contributing to more engaging and visually appealing websites.

o) Data Manipulation: JavaScript can process and manipulate data on the client side, reducing
the need for constant server requests and enhancing performance.

In essence, JavaScript empowers developers to create dynamic, feature-rich, and interactive web
applications that cater to modern user expectations and technological advancements.

2. Variables and Data Types:

- Variables are used to store data values. They can be declared using `var`, `let`, or `const`.

- Common data types include numbers, strings, booleans, arrays, objects, and more.

- Example:

let name = "John";

let age = 30;

let isStudent = true;

Difference Between `var` and `const` in JavaScript:


JavaScript offers different ways to declare variables, such as `var`, `let`, and `const`. Here's a concise
explanation of the differences between `var` and `const`:

1. `var`:

- `var` was historically used to declare variables in JavaScript before the introduction of `let` and
`const`.

- Variables declared with `var` have function-level scope, meaning they are accessible throughout the
entire function they are declared in, even outside of loops and conditionals.

- Variables declared with `var` are hoisted, which means they are moved to the top of their scope
during the compilation phase.

- `var` allows variable redeclaration within the same scope, potentially leading to unintended
consequences.

2. `const`:

- `const` is used to declare variables that should not be reassigned after their initial assignment.

- Variables declared with `const` are block-scoped, meaning they are only accessible within the block
they are defined in (block refers to code enclosed in curly braces).

- `const` variables are not hoisted in the same way as `var` variables, so they must be declared before
they are used.

- Once a value is assigned to a `const` variable, that value cannot be changed or reassigned.

Key Points to Remember:

- Use `var` if you need variable hoisting or need to support older browsers, but be cautious due to its
less predictable scoping behavior.

- Use `const` for values that should remain constant throughout their scope. This helps prevent
unintentional reassignments and improves code readability.

- Favor `let` over `var` for block-scoped variables when you need reassignment, as `let` provides more
predictable scoping behavior.

Example:

// Using var

var x = 10;

if (true) {

var x = 20;

}
console.log(x); // Output: 20

// Using const

const y = 10;

if (true) {

const y = 20; // This is a separate variable with block scope

console.log(y); // Output: 10

In modern JavaScript development, `let` and `const` are preferred over `var` due to their more
predictable scoping behavior and the added benefits they provide for maintaining code quality and
reducing bugs.

3. Operators:

- JavaScript supports various operators like arithmetic, comparison, logical, assignment, and more.

- Example:

let sum = 10 + 5;

let isGreater = age > 25;

4. Control Flow:

- Use `if`, `else if`, and `else` statements for conditional execution.

- Use `for` and `while` loops for repetitive tasks.

- Example:

if (age > 18) {

console.log("You are an adult.");

} else {

console.log("You are a minor.");

5. Functions:

- Functions are blocks of code that can be reused.

- They can take parameters and return values.

- Example:
function greet(name) {

return "Hello, " + name + "!";

6. Arrays:

- Arrays are used to store multiple values in a single variable.

- Elements in an array are accessed using an index (starting from 0).

- Example:

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

let firstFruit = fruits[0];

7. Objects:

- Objects store key-value pairs and are used to represent complex data structures.

- Properties of an object are accessed using dot notation or square brackets.

- Example:

let person = {

firstName: "John",

lastName: "Doe",

age: 30

};

let firstName = person.firstName;

8. DOM Manipulation:

- The Document Object Model (DOM) represents the structure of a web page.

- JavaScript can be used to interact with and manipulate the DOM to change content and styles
dynamically.

- Example:

let element = document.getElementById("myElement");

element.textContent = "New content";

9. Events:
- JavaScript can respond to events triggered by the user, like clicks and keyboard input.

- Event listeners are used to attach code to specific events.

- Example:

let button = document.getElementById("myButton");

button.addEventListener("click", function() {

alert("Button clicked!");

});

Statements in JavaScript
1. Expression Statements:

- Expression statements are the most basic type of statement.

- They consist of an expression followed by a semicolon.

- The expression is evaluated, and its result may have side effects.

- Example:

let x = 5;

console.log(x * 2);

2. Variable Declarations (var, let, const):

- Statements for declaring variables using different keywords.

- `var` (historical): Function or global scope, hoisting.

- `let` and `const`: Block-scoped, no hoisting, better predictability.

- Example:

let name = "John";

const age = 30;

3. Control Flow Statements:

- Statements used to control the flow of execution based on conditions.

- `if`, `else if`, `else`: Conditionally execute code blocks.

- `switch`: Evaluate different cases and execute code accordingly.

- Example:

if (age > 18) {

console.log("You are an adult.");

} else {

console.log("You are a minor.");


}

4. Loops:

- Loops are used for repetitive execution of code blocks.

- `for`: Execute code a specific number of times.

- `while` and `do-while`: Execute code while a condition is true.

- Example:

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

console.log("Iteration: " + i);

5. Function Declarations and Expressions:

- Defining functions using the `function` keyword or function expressions.

- Functions are reusable blocks of code.

- Example:

function greet(name) {

return "Hello, " + name + "!";

6. Break and Continue:

- `break`: Exit a loop or switch statement.

- `continue`: Skip the current iteration of a loop.

- Example:

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

if (i === 5) {

break; // Exit the loop when i is 5

console.log(i);

7. Return:

- Used in functions to specify the value to be returned.

- It ends the execution of the function.


- Example:

function add(a, b) {

return a + b;

8. Throw and Try-Catch:

- `throw`: Generate an exception or error.

- `try`, `catch`, `finally`: Handle exceptions and errors.

- Example:

try {

if (input === null) {

throw new Error("Input cannot be null.");

} catch (error) {

console.error(error.message);

}
Programs in JavaScript
ADDITION OF TWO NO.
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>JavaScript</title>

<link

href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"

rel="stylesheet">

<script

src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min

.js"></script>

</head>

<body style="text-align: center;">

<div class="col-md-6 mt-5">

<lable>Enter First Number</lable></br>

<input type="text" id="first"/></br>

<lable>Enter Second Number</lable></br>

<input type="text" id="second"/></br>

<lable>Result</lable></br>

<input type="text" id="result"/></br></br>

<input type="button" value="Submit" onclick="result()">

</div>

</body>

<script type="text/javascript">

function result(){

var a=Number(document.getElementById("first").value);

var b=Number(document.getElementById("second").value);

var c=a+b;
document.getElementById("result").value=Number(c);

</script>

</html>

MULTIPLICATION OF TWO NO.


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>JavaScript</title>

<link

href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"

rel="stylesheet">

<script

src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min

.js"></script>

</head>

<body style="text-align: center;">

<div class="col-md-6 mt-5">

<lable>Enter First Number</lable></br>

<input type="text" id="first"/></br>

<lable>Enter Second Number</lable></br>

<input type="text" id="second"/></br>

<lable>Result</lable></br>

<input type="text" id="result"/></br></br>

<input type="button" value="Submit" onclick="result()">

</div>

</body>

<script type="text/javascript">

function result(){

var a=Number(document.getElementById("first").value);

var b=Number(document.getElementById("second").value);

var c=a*b;
document.getElementById("result").value=Number(c);

</script>

</html>

SIMPLE INTEREST
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Simple Interest</title>

<style type="text/css">

#container{

width: 50%;

padding: 12px 20px;

margin: 8px 0;

display: inline-block;

border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

div {

border-radius: 5px;

background-color: #f2f2f2;

padding: 20px;

input[type=Submit] {

width: 100%;

background-color: #4CAF50;

color: white;

padding: 14px 20px;

margin: 8px 0;

border: none;
border-radius: 4px;

cursor: pointer;

input[type=text], select {

width: 100%;

padding: 12px 20px;

margin: 8px 0;

display: inline-block;

border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

input[type=Submit]:hover {

background-color: #45a049;

input[type=Reset]:hover {

background-color: #45a049;

</style>

</head>

<body style="text-align: center;">

<h1 style="background-color: cornflowerblue;">Simple Interest Calculator</h1>

<div id="container">

</br>

<label>Enter Principal Amount</label>

<input type="text" id="principal" value="0"></body></br>

<label>Enter Rate of Interest</label>

<input type="text" id="interest" value="0"></br>

<label>Enter Time Duration(In Year)</label>

<input type="text" id="time" value="0"></br>

<label>Simple Interest Amount</label>

<input type="text" id="simpleint" value="0" disabled></br>

<input type="button" value="Submit" onclick="result()">

<input type="button" value="Reset" onclick="reset()">


</div>

<script lang="en" style="text/javascript">

confirm("Enter OK to Continue");

function result()

var p=Number(document.getElementById("principal").value);

var r=Number(document.getElementById("interest").value);

var t=Number(document.getElementById("time").value);

var simpleint=p*r*t/100;

document.getElementById("simpleint").value=Number(simpleint);

function reset()

document.getElementById("principal").value="0";

document.getElementById("interest").value="0";

document.getElementById("time").value="0";

document.getElementById("simpleint").value="0";

</script>

</body>

</html>

You might also like