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

Java Script End Sem 2nd Part

JavaScript is a high-level, interpreted programming language essential for web development, enabling interactivity on web pages and server-side development. It offers advantages like versatility, client-side execution, rich user interfaces, and a large ecosystem of libraries and frameworks. The document also covers various JavaScript concepts including operators, data types, events, recursive functions, and user-defined functions.

Uploaded by

Mohammad Zafar
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)
4 views

Java Script End Sem 2nd Part

JavaScript is a high-level, interpreted programming language essential for web development, enabling interactivity on web pages and server-side development. It offers advantages like versatility, client-side execution, rich user interfaces, and a large ecosystem of libraries and frameworks. The document also covers various JavaScript concepts including operators, data types, events, recursive functions, and user-defined functions.

Uploaded by

Mohammad Zafar
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/ 9

JavaScript (JS) is a high-level, interpreted programming language that is primarily known for adding

interactivity to web pages. It is an essential part of web development and is widely used alongside
HTML and CSS to create dynamic content on the client side (browser) and for server-side
development with environments like Node.js.

Advantages of JavaScript

• Versatile and Cross-Platform: JavaScript can run on various platforms and devices, including
desktops, servers, and mobile devices, making it ideal for developing cross-platform
applications.

• Client-Side Execution: JavaScript is executed in the browser, reducing server load and
improving user experience by allowing immediate feedback.

• Rich User Interfaces: JavaScript enables developers to create interactive elements like
sliders, pop-ups, and dynamic forms that enhance the user experience.

• Large Ecosystem: It boasts a vast library and framework ecosystem (like React, Angular,
Vue.js) that speeds up development.

• Asynchronous Capabilities: JavaScript supports asynchronous programming through


callbacks, promises, and async/await, facilitating operations like data fetching without
blocking the main thread.

Difference Between Client-Side and Server-Side Scripting


Feature Client-Side Scripting Server-Side Scripting

Definition Code that executes in the user's web browser Code that runs on the web server

Language
JavaScript PHP, Python, Ruby, Node.js, ASP.NET
Examples

Execution Control The user’s browser controls execution The web server controls execution

User Interaction Provides immediate feedback (e.g., form validation) Fetches data, validates, and processes requests

Reduces server load, executes faster due to local


Performance Can be slower due to server communication delays
processing

More secure as it runs on the server, inaccessible to


Security Exposed to users, can be manipulated
users

Database interactions, authentication, sensitive data


Use Cases User interfaces, animations, data validation
processing
Q.Operators in JavaScript.

1. Arithmetic Operators
Operator Description Example

+ Addition 5 + 3 results in 8

- Subtraction 5 - 3 results in 2

* Multiplication 5 * 3 results in 15

/ Division 5 / 2 results in 2.5

% Modulus 5 % 2 results in 1

** Exponentiation 2 ** 3 results in 8

2. Assignment Operators

Operator Description Example

= Assigns right operand to left let x = 5;

+= Adds and assigns x += 3;

-= Subtracts and assigns x -= 3;

*= Multiplies and assigns x *= 3;

/= Divides and assigns x /= 3;

3. Comparison Operators

Operator Description Example

== Equal to 5 == '5' (true)

=== Strictly equal 5 === '5' (false)

!= Not equal 5 != '5' (false)

!== Strictly not equal 5 !== '5' (true)

> Greater than 5 > 3 (true)

< Less than 3 < 5 (true)

>= Greater than or equal 5 >= 5 (true)

<= Less than or equal 3 <= 5 (true)


4. Logical Operators

Operator Description Example

&& Logical AND true && false (false)

` `

! Logical NOT !true (false)

5. Bitwise Operators
Operator Description Example

& Bitwise AND 5 & 3 (1)

` ` Bitwise OR

^ Bitwise XOR 5 ^ 3 (6)

~ Bitwise NOT ~5 (-6)

<< Left shift 5 << 1 (10)

>> Right shift 5 >> 1 (2)

Data Types in JavaScript:

1. Primitive Data Types

Data Type Description Example

String Represents text. let str = "Hello";

Number Represents both integers and floats. let num = 42;

Boolean Represents a logical value (true/false) let isActive = true;

Undefined Declared but not assigned a value. let x;

Null Represents an intentional absence of value. let empty = null;

Symbol Represents a unique and immutable value. let sym = Symbol('desc');

BigInt Represents whole numbers larger than Number.MAX_SAFE_INTEGER. let bigInt = 9007199254740991n;

2. Non-Primitive Data Types

Data Type Description Example

Object A collection of properties, which can include primitives and other objects. let obj = { key: "value" };

Array A special type of object used to store multiple values in a single variable. let arr = [1, 2, 3];

Function A callable object that can be invoked. function add(a, b) { return a + b; }


Q.What is an Event in JavaScript?

An event in JavaScript is an action or occurrence that happens in the browser which the code can
respond to. Events are triggered by user interactions (like mouse clicks, keyboard input), browser
actions (page load), or JavaScript code itself.

Events enable interactive web pages by allowing scripts to execute code when these interactions or
actions occur.

Categories of Common JavaScript Events and Their Explanation

Event
Event Name(s) Description
Category

Triggered by mouse actions, e.g., clicking,


Mouse double-clicking, moving the pointer
click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove
Events over/out an element, pressing or
releasing mouse buttons.

Triggered by keyboard actions, e.g.,


Keyboard pressing or releasing keys. keypress is
keydown, keyup, keypress
Events deprecated in modern browsers but still
encountered.

Triggered during form interactions, e.g.,


Form
submit, change, input, focus, blur submitting a form, changing input value,
Events
input focus gained or lost.

Triggered related to the browser window


Window lifecycle or state changes, e.g., when the
load, unload, resize, scroll, error
Events page loads/unloads, window is resized or
scrolled.

Triggered when the user interacts with


Clipboard
copy, cut, paste the clipboard, e.g., copying, cutting, or
Events
pasting content.

Triggered during drag-and-drop


Drag and
dragstart, drag, dragenter, dragover, dragleave, drop, dragend operations, tracking the movement of
Drop Events
draggable elements.

Triggered when an element gains or loses


Focus
focus, blur, focusin, focusout focus, or when the focus is about to
Events
move in or out of an element.

Triggered by user touch on mobile


Touch
touchstart, touchmove, touchend, touchcancel devices, e.g., finger taps, swipes, or
Events
touch interruptions.

Triggered during media playback, e.g.,


Media
play, pause, ended, volumechange, timeupdate video or audio play, pause, end, volume
Events
changes, or time updates.
Q.What is a Recursive Function?

A recursive function is a function that calls itself in order to solve a problem. This approach is
commonly used to break down complex problems into simpler sub-problems. Recursive functions
have two main components:

1. Base Case: A condition that allows the function to stop calling itself, preventing infinite
recursion.

2. Recursive Case: The part of the function where it calls itself with modified arguments,
bringing it closer to the base case.

Example: JavaScript Program to Generate Fibonacci Series Using Recursive Function

The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually
started with 0 and 1. The sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Here is a JavaScript implementation to generate the Fibonacci series using a recursive function:

EXAMPLE:

// Recursive function to calculate Fibonacci number

function fibonacci(n) {

// Base case: If n is 0 or 1, return n

if (n === 0) {

return 0; }

if (n === 1) {

return 1; }

// Recursive case: Return the sum of the two preceding Fibonacci numbers

return fibonacci(n - 1) + fibonacci(n - 2); }

// Function to print Fibonacci series up to a certain number of terms

function printFibonacciSeries(terms) {

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

console.log(fibonacci(i)); } }

// Call the function to print the Fibonacci series

printFibonacciSeries(10); // Change the number to get more terms


Q.DIFFE BETWEEEN LOCAL AND GLOBAL VARIABLE IN JS.

Aspect Local Variable Global Variable

Definition A variable declared inside a function or block. A variable declared outside any function or block.

Accessible only within the function or block where


Scope Accessible throughout the entire script or program.
declared.

Exists only during function execution or block


Lifetime Exists as long as the script runs.
execution.

Declaration Typically declared with var, let, or const inside Declared with var, let, or const outside any function or
Keywords functions/blocks. block (or implicitly by not declaring in strict mode).

Not accessible outside the function/block it is


Accessibility Accessible from any function or block in the script.
defined in.

Memory allocated when function is called and Memory allocated when script loads and persists until the
Memory Usage
released after function execution completes. script ends.

Variable Local variables can shadow (override) global Global variables accessible unless shadowed by local
Shadowing variables within their scope. variables.

javascript function foo() { let x = 10; console.log(x); } javascript let y = 20; function bar() { console.log(y); } // y is
Example
// x is local to foo global

Q.What is a User-Defined Function (UDF) in JavaScript?

A User-Defined Function (UDF) in JavaScript is a function that you create to perform specific tasks.
Unlike built-in functions (like Math.random() or alert()), UDFs allow you to encapsulate reusable
code, making your programs modular and easier to manage.

Components of a UDF:

1. Function Declaration: This is where you define the function using the function keyword.

2. Function Name: A meaningful name to identify the function.

3. Parameters (optional): Inputs that the function can accept.

4. Function Body: The block of code that performs actions or calculations.

5. Return Statement (optional): Returns a value to the caller of the function.


Example of a User-Defined Function:
// Function to calculate the area of a rectangle

function calculateArea(length, width) {

// Calculate the area

let area = length * width;

// Return the result

return area;

// Using the function

let length = 5;

let width = 4;

let area = calculateArea(length, width); // Call the function

console.log(`The area of the rectangle is: ${area}`); // Output: The area of the rectangle is: 20

1. Odd or Even:

function isOddEven(num) {

if (num % 2 === 0) {

return "Even";

} else {

return "Odd";

console.log(isOddEven(7)); // Odd

console.log(isOddEven(10)); // Even
2. Multiplication Table

function multiplicationTable(num) {

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

console.log(`${num} x ${i} = ${num * i}`);

multiplicationTable(5);

3. Factorial:

function factorial(n) {

if (n === 0 || n === 1) return 1;

return n * factorial(n - 1);

console.log(factorial(5)); // 120

4Check Prime Number:

function isPrime(num) {

if (num <= 1) return false;

if (num === 2) return true;

if (num % 2 === 0) return false;

for (let i = 3; i <= Math.sqrt(num); i += 2) {

if (num % i === 0) return false;

return true;

console.log(isPrime(7)); // true

console.log(isPrime(10)); // false
5. Series of Prime Numbers (up to n)

function primeSeries(n) {

for (let i = 2; i <= n; i++) {

if (isPrime(i)) {

console.log(i);

primeSeries(20);

6. Reverse a Number

function reverseNumber(num) {

let reversed = 0;

while (num > 0) {

reversed = reversed * 10 + (num % 10);

num = Math.floor(num / 10);

return reversed;

console.log(reverseNumber(12345)); // 54321

8. Palindrome Check (for string or number)

function isPalindrome(input) {

let str = input.toString();

let reversed = str.split('').reverse().join('');

return str === reversed;

console.log(isPalindrome("madam")); // true

console.log(isPalindrome(12321)); // true

console.log(isPalindrome("hello")); // false

You might also like