0% found this document useful (0 votes)
8 views15 pages

Unit 4 UGCSA104

Unit 4 professor pratik c notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Unit 4 UGCSA104

Unit 4 professor pratik c notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

VIVEKANANDA GLOBAL UNIVERSITY

LECTURE NOTES

Unit IV
Working with Java Script (6L)

CONTENT:
1. Introduction to JavaScript
2. Data types
3. Variables
4. Operators
5. Expressions
6. Statements
7. Functions
8. Objects
9. Arrays
10. Date
11. Math
12. Error Handling
13. Flow control
14. Loops
15. Document Object Model (DOM).

Introduction to JavaScript:

JavaScript is a high-level, interpreted programming language that is widely used


for building dynamic and interactive websites. It is often embedded directly into
Notes By:- Pratik Pandey 1
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
HTML and runs in web browsers, providing client-side scripting capabilities.
JavaScript allows developers to manipulate the Document Object Model (DOM),
handle events, and create responsive and engaging user interfaces.

Here are some key points about JavaScript:

Client-Side Scripting: JavaScript is primarily used for client-side scripting,


meaning it runs on the user's browser, enabling dynamic and interactive web pages.

Multi-paradigm Language: JavaScript supports multiple programming


paradigms, including procedural, object-oriented, and functional programming.

Event-Driven: JavaScript is event-driven, allowing developers to respond to user


actions, such as clicks, form submissions, and keyboard events.

Versatile Usage: Apart from web development, JavaScript is now used in various
environments, including server-side development (Node.js), mobile app
development, and game development.

Data Types in JavaScript:

JavaScript has several data types that are classified into two categories: primitive
and object.

Primitive Data Types:

Number: Represents numeric values. Example: let num = 42;

String: Represents textual data. Example: let text = "Hello, World!";

Boolean: Represents true or false values. Example: let isTrue = true;

Undefined: Represents the absence of a value. Example: let undefinedVar;

Notes By:- Pratik Pandey 2


Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
Null: Represents the absence of any object value. Example: let nullVar = null;

Symbol (ES6+): Represents a unique identifier. Example: let sym =


Symbol('foo');

Object Data Type:

Object: Represents a collection of key-value pairs. Example:

let person = {
name: 'John',
age: 25,
isStudent: true
};
Variables in JavaScript:

Variables are used to store and manipulate data in JavaScript. To declare a variable,
you can use the let, const, or var keyword.

let and const:

let is used for variables whose values can be reassigned.


const is used for variables with constant values that cannot be reassigned.

let message = "Hello, World!";


const pi = 3.14;

var (older, less preferred):

var is used for declaring variables, but it has some differences in behavior
compared to let and const.
Notes By:- Pratik Pandey 3
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES

var counter = 0;

JavaScript is a dynamically typed language, meaning you don't have to explicitly


specify the data type of a variable; it is inferred at runtime. For example, you can
reassign a variable with a different type:

let myVar = 42; // Number


myVar = "Hello"; // String
myVar = true; // Boolean

This flexibility is a characteristic of dynamically typed languages like JavaScript.


Understanding data types and working with variables is foundational to writing
effective JavaScript code.

Variables in JavaScript:

Variables in JavaScript are used to store and manage data. They are declared using
the let, const, or var keyword, and their values can be updated or reassigned.

let age = 25; // Declaring a variable 'age' and assigning the value 25
const pi = 3.14; // Declaring a constant 'pi' with the value 3.14
var name = "John"; // Older way of declaring a variable

Operators in JavaScript:

Operators perform operations on variables and values. JavaScript has various types
of operators, including:

Arithmetic Operators:
Notes By:- Pratik Pandey 4
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES

let a = 10;
let b = 5;

let sum = a + b; // Addition


let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
let remainder = a % b; // Modulus

Comparison Operators:

let x = 10;
let y = 5;

console.log(x > y); // Greater than


console.log(x < y); // Less than
console.log(x === y); // Equal to
console.log(x !== y); // Not equal to

Logical Operators:

let p = true;
let q = false;

console.log(p && q); // Logical AND


console.log(p || q); // Logical OR
console.log(!p); // Logical NOT

Assignment Operators:

let num = 10;


Notes By:- Pratik Pandey 5
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
num += 5; // Equivalent to: num = num + 5

Unary Operators:

let count = 5;
count++; // Increment by 1 (count = count + 1)
count--; // Decrement by 1 (count = count - 1)

Expressions in JavaScript:

An expression is a combination of values, variables, and operators that can be


evaluated to a single value.

let result = (10 + 5) * 2; // An expression with arithmetic operations

Expressions can be more complex and involve function calls, conditional


statements, and other JavaScript constructs. They are a fundamental part of writing
dynamic and functional code in JavaScript.

Statements in JavaScript:

A statement in JavaScript is a complete instruction that performs an action.


Common types of statements include:

Declaration Statements:

Used to declare variables or functions.

let x; // Variable declaration


function myFunction() {} // Function declaration

Expression Statements:
Notes By:- Pratik Pandey 6
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
Statements that include expressions.

let result = 5 + 3; // Assignment statement with an expression

Control Flow Statements:

Used for control flow in the program, such as if, else, switch, for, while, etc.

if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

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


// Code to execute in a loop
}

Functions in JavaScript:

Functions are reusable blocks of code that can be defined and called with a set of
parameters. They encapsulate a specific task or behavior.

// Function declaration
function greet(name) {
console.log(`Hello, ${name}!`);
}

// Function call
greet("John"); // Output: Hello, John!

Notes By:- Pratik Pandey 7


Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
Functions can have parameters and return values, allowing for modular and
organized code.

// Function with parameters and return value


function addNumbers(a, b) {
return a + b;
}

let sum = addNumbers(3, 5); // sum will be 8

Objects in JavaScript:

Objects in JavaScript are complex data types that store data in key-value pairs.
They can represent real-world entities and have properties and methods.

// Object literal
let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello!");
}
};

console.log(person.name); // Accessing a property


person.greet(); // Calling a method

Objects provide a way to organize and structure data, and they can be used to
model various entities in a program.

Arrays in JavaScript:

Notes By:- Pratik Pandey 8


Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
Arrays are ordered lists of values and are used to store collections of data.

// Array literal
let fruits = ["apple", "banana", "orange"];

console.log(fruits[0]); // Accessing an element


fruits.push("grape"); // Adding an element to the end

Arrays are versatile and can hold various data types. They provide methods for
manipulating and iterating through their elements.

These foundational concepts—statements, functions, objects, and arrays—are


crucial for understanding and building JavaScript applications. They enable
developers to create structured, modular, and efficient code.

Date Object in JavaScript:

The Date object in JavaScript is used to work with dates and times. It provides
methods for creating, formatting, and manipulating dates.

// Creating a new Date object


let currentDate = new Date();

// Getting specific components of a date


let year = currentDate.getFullYear();
let month = currentDate.getMonth(); // Note: Months are zero-based (0 - 11)
let day = currentDate.getDate();

The Date object also supports various methods for working with time, such as
getHours(), getMinutes(), getSeconds(), etc.

let hours = currentDate.getHours();


Notes By:- Pratik Pandey 9
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();

Math Object in JavaScript:

The Math object provides mathematical functions and constants in JavaScript.

let num = 4.567;

// Rounding a number
let roundedNum = Math.round(num); // Rounds to the nearest integer

// Getting the square root


let sqrtNum = Math.sqrt(num);

// Generating a random number between 0 (inclusive) and 1 (exclusive)


let randomNum = Math.random();

The Math object includes functions for common mathematical operations like
round(), floor(), ceil(), max(), and min().

Error Handling in JavaScript:

Error handling in JavaScript is done using try, catch, finally, and throw statements.

try {
// Code that may throw an error
let result = x / y;
if (isNaN(result)) {
throw new Error("Result is not a number!");
}
// Continue with normal execution if no error occurs
} catch (error) {
Notes By:- Pratik Pandey 10
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
// Code to handle the error
console.error("An error occurred:", error.message);
} finally {
// Code that always executes, whether an error occurred or not
}

The try block contains the code that might throw an error. If an error occurs, it is
caught and handled in the catch block. The finally block is optional and executes
regardless of whether an error occurred or not.

Flow Control in JavaScript:

Flow control in JavaScript involves making decisions (conditionals) and repeating


actions (loops).

Conditional Statements (if, else, switch):

let temperature = 25;

if (temperature > 30) {


console.log("It's a hot day!");
} else if (temperature > 20) {
console.log("It's a nice day.");
} else {
console.log("It's a cold day!");
}

Loops (for, while, do-while):

// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
Notes By:- Pratik Pandey 11
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
}

// While loop
let counter = 0;
while (counter < 5) {
console.log(counter);
counter++;
}

// Do-while loop
let index = 0;
do {
console.log(index);
index++;
} while (index < 5);

These control flow structures help manage the execution flow of a program based
on conditions and repetitions. They are essential for writing flexible and dynamic
JavaScript code.

Loops in JavaScript:

Loops are used to execute a block of code repeatedly. JavaScript provides several
types of loops, including for, while, and do-while.

1. For Loop:

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


console.log(i);
}
This loop initializes a variable (i), sets a condition (i < 5), and increments i after
each iteration.

Notes By:- Pratik Pandey 12


Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
2. While Loop:

let counter = 0;

while (counter < 5) {


console.log(counter);
counter++;
}
The while loop continues to execute as long as the specified condition (counter <
5) is true.

3. Do-While Loop:

let index = 0;

do {
console.log(index);
index++;
} while (index < 5);

The do-while loop is similar to the while loop, but it guarantees that the block of
code is executed at least once, as the condition is checked after the block.

Document Object Model (DOM):

The DOM is a programming interface provided by web browsers that allows


JavaScript to interact with HTML and XML documents. It represents the document
as a tree structure, where each node corresponds to an element, attribute, or piece
of text in the document.

Example of DOM Manipulation:

Notes By:- Pratik Pandey 13


Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Example</title>
</head>
<body>

<h1 id="myHeading">Hello, World!</h1>


<button onclick="changeText()">Change Text</button>

<script>
// JavaScript code to manipulate the DOM
function changeText() {
// Accessing an element by its ID
let heading = document.getElementById("myHeading");

// Modifying the text content of the element


heading.textContent = "New Text!";
}
</script>

</body>
</html>
In this example:

The HTML document contains an <h1> element with the ID "myHeading" and a
<button> element.
The JavaScript code defines a function changeText() that manipulates the content
of the <h1> element when the button is clicked.

DOM Manipulation Steps:


Notes By:- Pratik Pandey 14
Assistant Professor
VIVEKANANDA GLOBAL UNIVERSITY
LECTURE NOTES
Select Elements:

Use methods like getElementById, getElementsByClassName,


getElementsByTagName, or newer methods like querySelector and
querySelectorAll to select elements.

Manipulate Content or Style:

Use properties like textContent, innerHTML, style, etc., to change the content or
style of the selected elements.

Respond to Events:

Use event listeners to respond to user interactions (e.g., clicks, key presses) and
trigger JavaScript functions.
DOM manipulation allows dynamic updates to web pages, making them interactive
and responsive to user actions. It's a key aspect of creating modern web
applications.

************* Thank You *************

Notes By:- Pratik Pandey 15


Assistant Professor

You might also like