[Go to site: main page, start]

0% found this document useful (0 votes)
7 views16 pages

JavaScript Basics for Web Development

Unit 5 of the Web Application Development course provides a comprehensive introduction to JavaScript, covering essential topics such as syntax, variables, operators, control statements, and loops. It emphasizes exam preparation strategies, including the use of definitions, syntax, examples, and flowcharts to enhance answers. The notes also highlight key features of JavaScript, its differences from Java, and practical applications in web development.

Uploaded by

priyanshuji31205
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)
7 views16 pages

JavaScript Basics for Web Development

Unit 5 of the Web Application Development course provides a comprehensive introduction to JavaScript, covering essential topics such as syntax, variables, operators, control statements, and loops. It emphasizes exam preparation strategies, including the use of definitions, syntax, examples, and flowcharts to enhance answers. The notes also highlight key features of JavaScript, its differences from Java, and practical applications in web development.

Uploaded by

priyanshuji31205
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

WAD Unit 5: Introduction to JavaScript

Web Application Development (WAD)


Unit 5 Notes: Introduction to JavaScript
Extremely detailed, exam-ready notes aligned to RTU BCA Unit 5 syllabus

Unit 5 syllabus coverage: Writing first JavaScript, External JavaScript, Variables (rules,
declaration, assignment, scope), Operators, Control statements, Loops, Functions (definition,
return value, user-defined functions).
How to use: Study topic-wise. For exams, write crisp definitions, then add syntax + example +
short explanation. Use the tables and flowcharts for high marks.

Exam pattern hack: A 10–15 marker answer becomes strong when you add (1) definition, (2) syntax, (3)
flow/diagram, (4) example code, (5) key points table.

RTU BCA: Web Application Development (Theory) Page 1


WAD Unit 5: Introduction to JavaScript

1. Introduction to JavaScript
JavaScript (JS) is a high-level scripting language used to create interactive and dynamic
behavior in web pages. It executes mainly in the browser, and in modern development it can also
run on servers.

1.1 JavaScript, ECMAScript, and the Web (concept clarity)


ECMAScript is the standard specification for JavaScript. Browsers implement the ECMAScript
standard via JavaScript engines.

Term Meaning Exam-friendly note

JavaScript Programming language used in Used for validation, interactivity, dynamic UI,
browsers and servers scripting

ECMAScript Standard/specification of the language New features come as ES versions (ES6,


ES2020 etc.)

JS Engine Program that runs JavaScript Examples: V8 (Chrome), SpiderMonkey


(Firefox)

1.2 Key features of JavaScript


• Interpreted/JIT executed: runs without separate compilation step in typical web usage.
• Event-driven: reacts to events like click, keypress, load.
• Dynamically typed: variable type depends on stored value.
• Object-based: supports objects and functions as first-class values.
• Platform independent: works across browsers (with standard JS).

1.3 Where JavaScript is used


• Client-side (Browser): UI interaction, form validation, DOM manipulation.
• Server-side: [Link] for APIs and server logic (extra point).
• Mobile/Desktop: frameworks can use JS for apps (extra awareness).

1.4 JavaScript vs Java (common confusion, scoring table)


Point JavaScript Java

Type Scripting language Compiled programming language

Main use Web page behavior (browser) General-purpose applications

Execution JS engine in browser/server JVM (Java Virtual Machine)

Typing Dynamic typing Static typing

2. JavaScript Basics: Syntax and Core Rules


Before writing programs, understand the basic syntax rules, because exam questions often ask
simple definitions and small code snippets.

2.1 Statements, blocks, and semicolons

RTU BCA: Web Application Development (Theory) Page 2


WAD Unit 5: Introduction to JavaScript

• Statement: a single instruction (example: let x = 10;).


• Block: group of statements inside { } used in if, loops, functions.
• Semicolon (;): marks end of statement. JS can insert semicolons automatically, but writing
them is safer for beginners and exams.
let x = 10; // statement
if (x > 5) { // block begins
x = x + 1;
} // block ends

2.2 Case sensitivity and whitespace


• JavaScript is case-sensitive (Total and total are different).
• Whitespace (spaces/newlines) generally does not matter, but improves readability.
• Use meaningful names and consistent formatting (camelCase recommended).

2.3 Comments (very common in theory)


// Single-line comment

/*
Multi-line comment
used for explanations
*/

Why comments matter:


• Improve readability.
• Help explain logic in exam answers and project code.

2.4 Input and output in JavaScript (exam practical)


In browser-based JS, you can take basic input using prompt and show output using
alert/console/document.

Function Purpose Example Notes

alert() Show message popup alert('Hi') Simple output; blocks page until OK

prompt() Take input as string prompt('Enter name') Returns string or null

confirm() Yes/No dialog confirm('Are you sure?') Returns true/false

[Link]() Print in console [Link](x) Best for debugging

[Link]() Write into page [Link]('Hello') Not recommended for modern apps

let name = prompt("Enter your name:");


if (name !== null) {
alert("Hello " + name);
}

3. Writing First JavaScript


JavaScript can be written inside an HTML file using the <script> tag. The browser executes
code as it parses the page (unless you use defer/async).

RTU BCA: Web Application Development (Theory) Page 3


WAD Unit 5: Introduction to JavaScript

3.1 Internal JavaScript (inside HTML)


Internal JS is placed between <script> ... </script> within the HTML page.
<!DOCTYPE html>
<html>
<head>
<title>First JS</title>
</head>
<body>
<h1>Demo</h1>

<script>
[Link]("Hello from JavaScript!");
alert("Welcome to JavaScript!");
</script>
</body>
</html>

3.2 Where to place the script tag (head vs body)


Placement When it runs Exam points

Inside <head> Runs before body loads May fail for DOM elements not yet created; use defer
(unless deferred) or DOM loaded event.

End of <body> Runs after HTML is parsed Simple and safe approach for beginners.

3.3 Script attributes: defer and async


defer downloads in background and executes after HTML parsing. async downloads and
executes as soon as ready (order may change).

Attribute Download Execution Use when

defer Parallel with HTML parsing After HTML parsing DOM-dependent scripts; stable order.

async Parallel with HTML parsing As soon as Independent scripts like analytics.
downloaded

4. External JavaScript
External JS means writing code in a separate .js file and linking it to HTML using the script tag
with src attribute.

4.1 Advantages of external JS (write any 4 for marks)


• Separation of concerns: clean structure and maintainable code.
• Reusability: same file can be used in multiple pages.
• Easy debugging: clear file organization.
• Browser caching: improves loading speed after first load.

4.2 Linking an external .js file


<!-- [Link] -->
<script src="[Link]"></script>

RTU BCA: Web Application Development (Theory) Page 4


WAD Unit 5: Introduction to JavaScript

// [Link]
[Link]("External JS loaded!");

Multiple external scripts: place them in correct order if one depends on another.

5. Variables
A variable stores data that can be used in expressions and statements. JavaScript variables can
hold any type of value.

5.1 Rules for variable names (RTU favorite)


• Must start with a letter, underscore (_), or dollar ($).
• Can contain letters, digits, underscore, and dollar sign.
• No spaces allowed (use camelCase).
• Case-sensitive.
• Reserved keywords not allowed.

5.2 Declaring variables: var, let, const


Modern JS uses let and const. Older JS used var. Scope is the key difference.

Keyword Scope Re-declare Re-assign Exam note

var Function scope Yes Yes Hoisted; can create unexpected behavior

let Block scope No Yes Best for changing values

const Block scope No No Constant binding; value cannot be


reassigned

5.3 Declaring + assigning values


let x; // declared (undefined)
x = 10; // assigned
let y = 20; // declared + assigned
const pi = 3.14; // constant

5.4 Data types (deep understanding, exam-safe)


JavaScript is dynamically typed. Use typeof operator to check type.
typeof 10 // "number"
typeof "Hi" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (known JS quirk)

RTU BCA: Web Application Development (Theory) Page 5


WAD Unit 5: Introduction to JavaScript

Type Example Key points

Number 10, 3.5 One numeric type; includes NaN and Infinity

String 'A', "Hello" Sequence of characters; + concatenates strings

Boolean true/false Logical decisions and conditions

Undefined let a; Declared but not assigned

Null let a = null; Intentional empty value

Object { }, [ ], function() Collections; arrays and functions are objects

5.5 Type conversion (extra but scoring)


Sometimes values convert automatically (implicit) or you convert them intentionally (explicit).

Conversion Example Result

String to Number Number('12') 12

String to Number parseInt('12.9') 12

Number to String String(50) '50'

Implicit conversion (loose 5 == '5' true


==)

Explicit strict check 5 === '5' false

5.6 Scope of variables


Scope means where a variable can be accessed.
• Global scope: declared outside functions; accessible anywhere (avoid excessive global
variables).
• Function scope: var inside function is accessible throughout function.
• Block scope: let/const inside { } accessible only inside that block.
let a = 1; // global

function demo() {
var b = 2; // function scope
if (true) {
let c = 3; // block scope
const d = 4; // block scope
[Link](a, b, c, d);
}
// [Link](c); // error
}

5.7 Hoisting (must-know)


• Hoisting means declarations are processed before code runs.
• var is hoisted and initialized to undefined.
• let/const are hoisted but not initialized; using them before declaration causes an error.

RTU BCA: Web Application Development (Theory) Page 6


WAD Unit 5: Introduction to JavaScript

6. Using Operators
An operator performs operations on operands (values/variables).

6.1 Categories of operators (write in exam)


Category Operators Used for

Arithmetic +, -, *, /, %, **, ++, -- Math calculations

Assignment =, +=, -=, *=, /=, %= Assign/update values

Comparison ==, ===, !=, !==, >, <, >=, <= Compare values (true/false)

Logical &&, ||, ! Combine conditions

Conditional ?: Short if-else

Special typeof Get type of value

6.2 Arithmetic operators


Operator Meaning Example Result/Notes

+ Addition 5+2 7

- Subtraction 5-2 3

* Multiplication 5*2 10

/ Division 5/2 2.5

% Remainder 5%2 1

** Power 2 ** 3 8

++ Increment x++ post-increment

-- Decrement --x pre-decrement

Pre vs Post increment (exam trap)


let x = 5;
[Link](++x); // 6
let y = 5;
[Link](y++); // 5 (y becomes 6 after this line)

6.3 Assignment operators

RTU BCA: Web Application Development (Theory) Page 7


WAD Unit 5: Introduction to JavaScript

Operator Meaning Example Same as

= Assign x = 10 x becomes 10

+= Add and assign x += 5 x=x+5

-= Subtract and assign x -= 2 x=x-2

*= Multiply and assign x *= 3 x=x*3

/= Divide and assign x /= 2 x=x/2

%= Mod and assign x %= 2 x=x%2

6.4 Comparison operators (loose vs strict)


Comparison returns boolean. Prefer strict equality for safer logic.

Operator Meaning Example Output

== Equal (loose) 5 == '5' true

=== Equal (strict) 5 === '5' false

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

!== Not equal (strict) 5 !== '5' true

>, <, >=, <= Relational x >= 10 true/false


Exam line: == may convert types, but === compares both value and type.

6.5 Logical operators (short-circuit concept)


Operator Meaning Example Result idea

&& AND (a>0) && (b>0) true if both true

|| OR (a==0) || (b==0) true if any true

! NOT !flag reverses boolean


Short-circuit: In AND, if first condition is false, second may not be evaluated. In OR, if first is
true, second may not be evaluated.

6.6 Conditional (ternary) operator


let age = 17;
let msg = (age >= 18) ? "Adult" : "Minor";
[Link](msg);

6.7 Operator precedence (safe summary)


Use parentheses to avoid confusion in exams.
2 + 3 * 4 -> 14
(2 + 3) * 4 -> 20

RTU BCA: Web Application Development (Theory) Page 8


WAD Unit 5: Introduction to JavaScript

7. Control Statements
Control statements decide which block executes and in what order.

7.1 if statement
if (condition) {
// statements
}

Flow:
Start → condition?
true → execute block → next
false → skip block → next

7.2 if-else statement


if (condition) {
// true block
} else {
// false block
}

7.3 else-if ladder


Used for multiple ranges like grading system.
if (marks >= 90) grade = "A+";
else if (marks >= 75) grade = "A";
else if (marks >= 60) grade = "B";
else grade = "C";

7.4 Nested if (extra common)


if (x > 0) {
if (x % 2 === 0) [Link]("Positive even");
else [Link]("Positive odd");
} else {
[Link]("Non-positive");
}

7.5 switch statement


switch (choice) {
case 1:
// statements
break;
case 2:
// statements
break;
default:
// statements
}

Exam points:
• break stops fall-through.
• default handles unmatched case.

RTU BCA: Web Application Development (Theory) Page 9


WAD Unit 5: Introduction to JavaScript

• switch is cleaner than long else-if for fixed values (menu).

7.6 break and continue


Keyword Meaning Effect in loop

break Exit loop immediately Stops looping and jumps after loop

continue Skip current iteration Jumps to next iteration

RTU BCA: Web Application Development (Theory) Page 10


WAD Unit 5: Introduction to JavaScript

8. JavaScript Loops
A loop repeats a block of statements either for a fixed count or until a condition becomes false.

8.1 for loop (count-controlled)


for (initialization; condition; update) {
// body
}

Meaning of parts:
• initialization: runs once at the start.
• condition: checked before each iteration; if false, loop stops.
• update: runs after each iteration (often i++).
// Print 1 to 5
for (let i = 1; i <= 5; i++) {
[Link](i);
}

8.2 while loop (condition-controlled)


while (condition) {
// body
}

Use when you do not know exact iterations beforehand (depends on condition).

8.3 do-while loop (runs at least once)


do {
// body
} while (condition);

Point while do-while

Condition check Before loop body After loop body

Minimum runs 0 possible 1 always

8.4 Nested loops


Used in patterns (stars), multiplication tables, matrix operations.
// 2D iteration idea
for (let i = 1; i <= 2; i++) {
for (let j = 1; j <= 3; j++) {
[Link](i, j);
}
}

8.5 for...in and for...of (extra awareness)


for...in iterates keys. for...of iterates values (arrays/strings).
let arr = [10, 20, 30];

for (let idx in arr) [Link](idx); // 0,1,2

RTU BCA: Web Application Development (Theory) Page 11


WAD Unit 5: Introduction to JavaScript

for (let val of arr) [Link](val); // 10,20,30

8.6 Common loop algorithms (practice)


• Sum of first n natural numbers.
• Factorial of n.
• Reverse a number / sum of digits.
• Prime checking using loop.
• Fibonacci series generation.

Example: prime check logic (simple)


function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= n - 1; i++) {
if (n % i === 0) return false;
}
return true;
}

RTU BCA: Web Application Development (Theory) Page 12


WAD Unit 5: Introduction to JavaScript

9. JavaScript Functions
A function is a reusable block of code designed to perform a specific task.

9.1 Function definition (syntax)


function functionName(parameters) {
// statements
}

9.2 Calling a function


function greet() {
[Link]("Hello!");
}
greet();

9.3 Returning value from function


return sends a value back to caller and stops execution.
function add(a, b) {
return a + b;
}
let sum = add(2, 3); // 5

• If no return statement, function returns undefined.

9.4 User-defined functions (types)


Type Meaning Example

No parameter No input greet(), showDate()

With parameter Takes input square(n), add(a,b)

With return Returns value factorial(n) returns number

No return Performs action only printTable(n)

9.5 Parameters vs arguments


• Parameters: variables in definition: function add(a, b) → a and b.
• Arguments: values passed in call: add(2, 3) → 2 and 3.

9.6 Function expression (extra common)


const multiply = function(a, b) {
return a * b;
};
[Link](multiply(2, 4));

9.7 Arrow function (extra but modern)


Arrow functions give shorter syntax (useful knowledge).
const square = (n) => n * n;
[Link](square(5));

RTU BCA: Web Application Development (Theory) Page 13


WAD Unit 5: Introduction to JavaScript

9.8 Recursion (extra, but helps in long answers)


Recursion means a function calls itself. Example: factorial.
function fact(n) {
if (n === 0) return 1;
return n * fact(n - 1);
}

9.9 Variable scope inside functions (connects Unit 5 topics)


let globalX = 10;

function demoScope() {
let localY = 20;
[Link](globalX); // ok
[Link](localY); // ok
}
// [Link](localY); // error

9.10 Example programs (user-defined functions)


Factorial (iterative, easy for exams):
function factorial(n) {
let f = 1;
for (let i = 1; i <= n; i++) {
f *= i;
}
return f;
}

Fibonacci (first n terms):


function fibonacci(n) {
let a = 0, b = 1;
for (let i = 1; i <= n; i++) {
[Link](a);
let c = a + b;
a = b;
b = c;
}
}

RTU BCA: Web Application Development (Theory) Page 14


WAD Unit 5: Introduction to JavaScript

10. Exam Boosters (RTU Answer Writing)


This section is designed to help you write strong 10–15 mark answers quickly.

10.1 One-liners (write fast in exam)


• JavaScript is a scripting language used to create interactive web pages.
• Internal JavaScript is written inside <script> tag; external JavaScript is stored in a .js file
linked using src.
• Variables store values; JavaScript is dynamically typed.
• var has function scope; let and const have block scope.
• Operators perform operations; comparison operators return boolean.
• Control statements decide execution path; loops repeat statements.
• Functions are reusable blocks; return sends value back and stops execution.

10.2 Ready-made 10–12 mark answer outlines


A) Variables in JavaScript (write this structure)
• Definition of variable.
• Rules for variable names.
• Declaration keywords: var/let/const with scope table.
• Data types + typeof example.
• Scope explanation: global, function, block with small code.
• 2–3 advantages of let/const over var.
B) Operators + Control statements
• Define operator and operand.
• Classify operators (arithmetic, assignment, comparison, logical, conditional).
• Explain strict vs loose equality (=== vs ==) with example.
• Explain if-else and switch with syntax.
• Add a small program snippet (max of two) or a flow diagram.
C) Loops
• Define loop and need.
• Explain for, while, do-while with syntax and difference table.
• Explain break and continue.
• Write one small example (factorial or sum of digits).
D) Functions
• Define function and advantages.
• Syntax of function declaration and function call.
• Return statement meaning.
• Parameterized vs non-parameterized; with/without return.
• Write one user-defined function (factorial/prime) and explain logic.

10.3 Two flowcharts (text-based, exam friendly)


Flowchart 1: Factorial using loop

RTU BCA: Web Application Development (Theory) Page 15


WAD Unit 5: Introduction to JavaScript

Start

Read n

Set fact = 1, i = 1

Is i ≤ n ?
Yes → fact = fact * i → i = i + 1 → back to condition
No → Print fact

End

Flowchart 2: Prime check


Start

Read n

If n ≤ 1 → Not Prime → End

Set i = 2

Is i ≤ n-1 ?
Yes → If n % i == 0 → Not Prime → End
Else i = i + 1 → back
No → Prime

End

10.4 15-mark practice questions (high probability)


• Explain JavaScript. Write first JavaScript program and explain internal vs external scripts.
• Explain variables in JavaScript. Include naming rules, var/let/const, scope and examples.
• Explain operators in JavaScript with categories and examples. Explain == vs ===.
• Explain control statements (if, if-else ladder, switch) with syntax and examples.
• Explain loops (for, while, do-while), differences and use cases with sample programs.
• Explain JavaScript functions: definition, syntax, call, return value, user-defined functions
with example.

RTU BCA: Web Application Development (Theory) Page 16

You might also like