[Go to site: main page, start]

0% found this document useful (0 votes)
2 views20 pages

JavaScript Lecture

The document provides comprehensive lecture notes on JavaScript, covering key topics such as operators, conditional statements, loops, functions, and objects & arrays. It includes detailed explanations, examples, and syntax for various JavaScript constructs. The notes serve as a foundational guide for understanding and using JavaScript effectively.

Uploaded by

itsayanali990
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

JavaScript Lecture

The document provides comprehensive lecture notes on JavaScript, covering key topics such as operators, conditional statements, loops, functions, and objects & arrays. It includes detailed explanations, examples, and syntax for various JavaScript constructs. The notes serve as a foundational guide for understanding and using JavaScript effectively.

Uploaded by

itsayanali990
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVASCRIPT

Comprehensive Lecture Notes


─────────────────────────────────────────
Topics Covered
• Operators
• Conditional Statements
• Loop Types (for / while / do-while)
• Functions
• Objects & Arrays
1. JavaScript Operators
Operators are special symbols or keywords used to perform operations on values (operands).
JavaScript provides a rich set of operators grouped into several categories.

1.1 Arithmetic Operators


Arithmetic operators perform mathematical calculations on numeric values.

Operator Name Example


+ Addition 5 + 3 // 8

- Subtraction 10 - 4 // 6

* Multiplication 4 * 3 // 12

/ Division 15 / 3 // 5

% Modulus (remainder) 10 % 3 // 1

** Exponentiation 2 ** 4 // 16

++ Increment let x=5; x++; // 6

-- Decrement let y=5; y--; // 4

// Arithmetic Examples
let a = 10, b = 3;
[Link](a + b); // 13
[Link](a - b); // 7
[Link](a * b); // 30
[Link](a / b); // 3.333...
[Link](a % b); // 1 (remainder)
[Link](a ** b); // 1000 (10 to the power of 3)

1.2 Assignment Operators


Assignment operators assign values to variables. Compound assignment operators combine an
arithmetic operation with assignment.
let x = 10; // simple assignment
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
x **= 3; // x = x ** 3 → 8

1.3 Comparison Operators


Comparison operators compare two values and return a boolean (true or false).

let a = 5, b = '5';

[Link](a == b); // true (loose equality – type coercion)


[Link](a === b); // false (strict equality – no coercion)
[Link](a != b); // false
[Link](a !== b); // true
[Link](a > 3); // true
[Link](a < 3); // false
[Link](a >= 5); // true
[Link](a <= 4); // false

💡 Note: Always prefer === (strict equality) over == (loose equality) to avoid unexpected
type coercion bugs.

1.4 Logical Operators


Logical operators are used to combine or invert boolean expressions.

// && (AND) – true only if BOTH are true


[Link](true && false); // false
[Link](5 > 3 && 8 > 6); // true

// || (OR) – true if AT LEAST ONE is true


[Link](true || false); // true
[Link](5 > 10 || 3 < 7);// true

// ! (NOT) – inverts the boolean


[Link](!true); // false
[Link](!(5 > 10)); // true

1.5 Ternary Operator


The ternary operator is a concise way to write a simple if-else expression on one line.

// Syntax: condition ? valueIfTrue : valueIfFalse

let age = 20;


let status = age >= 18 ? 'Adult' : 'Minor';
[Link](status); // 'Adult'

// Equivalent if-else:
// if (age >= 18) { status = 'Adult'; } else { status = 'Minor'; }

1.6 typeof Operator

[Link](typeof 42); // 'number'


[Link](typeof 'hello'); // 'string'
[Link](typeof true); // 'boolean'
[Link](typeof undefined); // 'undefined'
[Link](typeof null); // 'object' ← known JS quirk
[Link](typeof {}); // 'object'
[Link](typeof []); // 'object'
[Link](typeof function(){}); // 'function'
2. Conditional Statements
Conditional statements allow your program to make decisions and execute different code paths
based on whether a condition is true or false.

2.1 if Statement
The simplest conditional — executes a block only when the condition is truthy.

let temperature = 35;

if (temperature > 30) {


[Link]('It is hot outside!');
}
// Output: 'It is hot outside!'

2.2 if...else Statement


Provides an alternative block to execute when the condition is false.

let score = 65;

if (score >= 70) {


[Link]('You passed!');
} else {
[Link]('You need to study more.');
}
// Output: 'You need to study more.'

2.3 if...else if...else (Chaining)


Use multiple else if clauses to test several conditions in sequence.

let score = 82;

if (score >= 90) {


[Link]('Grade: A');
} else if (score >= 80) {
[Link]('Grade: B');
} else if (score >= 70) {
[Link]('Grade: C');
} else if (score >= 60) {
[Link]('Grade: D');
} else {
[Link]('Grade: F');
}
// Output: 'Grade: B'

2.4 switch Statement


The switch statement is ideal when comparing a single value against many possible cases. It is
cleaner than a long if-else if chain when you have many discrete options.

let day = 'Monday';

switch (day) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
[Link]('Weekday – time to work!');
break;
case 'Saturday':
case 'Sunday':
[Link]('Weekend – time to rest!');
break;
default:
[Link]('Unknown day');
}
// Output: 'Weekday – time to work!'

💡 Note: Always include break after each case to prevent 'fall-through'. Without break,
execution continues into the next case automatically.
2.5 Nullish Coalescing Operator (??)
Returns the right-hand value only when the left-hand value is null or undefined — useful for
setting default values.

let username = null;


let displayName = username ?? 'Guest';
[Link](displayName); // 'Guest'

let count = 0;
let total = count ?? 10;
[Link](total); // 0 (0 is NOT null/undefined)

3. Loop Types
Loops allow you to execute a block of code repeatedly. JavaScript provides three primary loop
constructs, each suited for different scenarios.

3.1 for Loop


The for loop is the most common loop — ideal when you know in advance how many times to
iterate. It has three parts in its header: initialization, condition, and update.

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

// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
[Link]('Count:', i);
}
// Output: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5

// Loop through an array


let fruits = ['Apple', 'Banana', 'Cherry'];
for (let i = 0; i < [Link]; i++) {
[Link](i + ': ' + fruits[i]);
}
// Reverse loop
for (let i = 5; i >= 1; i--) {
[Link](i);
}
// Output: 5 4 3 2 1

for...of Loop
A modern loop that iterates directly over iterable values (arrays, strings, Maps, Sets).

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

for (let color of colors) {


[Link](color);
}
// Output: red green blue

// Works on strings too


for (let char of 'hello') {
[Link](char); // h e l l o
}

for...in Loop
Iterates over the enumerable property keys of an object.

let person = { name: 'Alice', age: 25, city: 'NYC' };

for (let key in person) {


[Link](key + ': ' + person[key]);
}
// Output:
// name: Alice
// age: 25
// city: NYC
3.2 while Loop
The while loop executes its body as long as the condition remains true. Use it when the number
of iterations is not known beforehand. The condition is checked before each iteration.

// Syntax
// while (condition) { body }

let count = 1;

while (count <= 5) {


[Link]('Count is: ' + count);
count++; // ← IMPORTANT: always update to avoid infinite loop
}

// Practical example: keep asking until valid input


let number = 0;
while (number <= 0) {
number = parseInt(prompt('Enter a positive number:'));
}
[Link]('You entered:', number);

💡 Note: Always make sure the condition will eventually become false. Failing to update the
variable controlling the condition will cause an infinite loop.

3.3 do...while Loop


The do...while loop is similar to the while loop, but the condition is evaluated after the loop body
executes. This guarantees the body runs at least once, even if the condition is initially false.

// Syntax
// do { body } while (condition);

let attempt = 1;

do {
[Link]('Attempt #' + attempt);
attempt++;
} while (attempt <= 3);
// Output: Attempt #1 Attempt #2 Attempt #3

// Even if condition is false from the start, body runs once


let x = 10;
do {
[Link]('This runs once! x =', x);
x++;
} while (x < 5);
// Output: 'This runs once! x = 10'

3.4 Loop Control: break & continue

// break – exits the loop immediately


for (let i = 0; i < 10; i++) {
if (i === 5) break;
[Link](i); // prints 0 1 2 3 4
}

// continue – skips the current iteration


for (let i = 0; i <= 10; i++) {
if (i % 2 !== 0) continue; // skip odd numbers
[Link](i); // prints 0 2 4 6 8 10
}

3.5 Loop Comparison


Feature for while do...while
Condition check Before Before After
Min. executions 0 0 1
Best use case Known iterations Unknown iterations Run-at-least-once
Init. in header Yes No No
4. JavaScript Functions
A function is a reusable block of code designed to perform a specific task. Functions are first-
class citizens in JavaScript — they can be assigned to variables, passed as arguments, and
returned from other functions.

4.1 Function Declaration


The classic way to define a function. Declarations are hoisted — they can be called before they
appear in the code.

function greet(name) {
return 'Hello, ' + name + '!';
}

[Link](greet('Alice')); // 'Hello, Alice!'


[Link](greet('Bob')); // 'Hello, Bob!'

4.2 Function Expression


A function stored in a variable. Unlike declarations, expressions are NOT hoisted.

const add = function(a, b) {


return a + b;
};

[Link](add(3, 4)); // 7

4.3 Arrow Functions (ES6)


Arrow functions offer a concise syntax. They do not have their own 'this' binding, making them
ideal for callbacks.

// Full arrow function


const multiply = (a, b) => {
return a * b;
};
// Implicit return (one-liner)
const square = x => x * x;

// No parameters
const sayHello = () => 'Hello World!';

[Link](multiply(3, 5)); // 15
[Link](square(4)); // 16
[Link](sayHello()); // 'Hello World!'

4.4 Parameters & Arguments

Default Parameters

function greet(name = 'Stranger', greeting = 'Hello') {


return `${greeting}, ${name}!`;
}

[Link](greet()); // 'Hello, Stranger!'


[Link](greet('Alice')); // 'Hello, Alice!'
[Link](greet('Bob', 'Welcome')); // 'Welcome, Bob!'

Rest Parameters

// Collect multiple arguments into an array


function sum(...numbers) {
return [Link]((total, n) => total + n, 0);
}

[Link](sum(1, 2, 3)); // 6
[Link](sum(1, 2, 3, 4, 5)); // 15
4.5 Return Values
Functions return a value using the return keyword. A function without a return statement returns
undefined.

function divide(a, b) {
if (b === 0) {
return 'Error: Cannot divide by zero';
}
return a / b;
}

[Link](divide(10, 2)); // 5
[Link](divide(10, 0)); // 'Error: Cannot divide by zero'

4.6 Scope
Scope determines where a variable is accessible. JavaScript has global scope, function (local)
scope, and block scope.

let globalVar = 'I am global';

function myFunction() {
let localVar = 'I am local';
[Link](globalVar); // accessible
[Link](localVar); // accessible
}

myFunction();
[Link](globalVar); // accessible
// [Link](localVar); // ReferenceError: localVar is not defined

4.7 Higher-Order Functions


A higher-order function either accepts a function as an argument, returns a function, or both.
They are foundational to functional programming in JavaScript.

// Passing a function as an argument (callback)


function applyOperation(a, b, operation) {
return operation(a, b);
}

const add = (a, b) => a + b;


const subtract = (a, b) => a - b;

[Link](applyOperation(5, 3, add)); // 8
[Link](applyOperation(5, 3, subtract)); // 2

// Common built-in higher-order functions


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

let doubled = [Link](n => n * 2); // [2,4,6,8,10]


let evens = [Link](n => n % 2 === 0); // [2,4]
let total = [Link]((sum, n) => sum + n, 0); // 15

4.8 Closures
A closure is a function that retains access to its outer (enclosing) scope even after that scope
has finished executing. Closures are powerful for data encapsulation.

function makeCounter() {
let count = 0; // private variable
return function() {
count++;
return count;
};
}

const counter = makeCounter();


[Link](counter()); // 1
[Link](counter()); // 2
[Link](counter()); // 3
// count is not accessible from outside — it is private!
5. JavaScript Objects & Arrays

5.1 Objects
An object is a collection of key-value pairs (properties). Keys are strings (or Symbols) and
values can be any data type, including functions (called methods).

Creating Objects

// Object literal (most common)


const person = {
name: 'Alice',
age: 30,
city: 'New York',
greet: function() {
return 'Hi, I am ' + [Link];
}
};

// Accessing properties
[Link]([Link]); // 'Alice' (dot notation)
[Link](person['age']); // 30 (bracket notation)
[Link]([Link]()); // 'Hi, I am Alice'

Modifying Objects

const car = { brand: 'Toyota', model: 'Camry', year: 2020 };

// Add property
[Link] = 'Blue';

// Update property
[Link] = 2024;

// Delete property
delete [Link];
[Link](car); // { brand: 'Toyota', model: 'Camry', year: 2024 }

Destructuring Objects

const student = { name: 'Bob', grade: 'A', score: 95 };

// Extract properties into variables


const { name, grade, score } = student;
[Link](name, grade, score); // 'Bob' 'A' 95

// With renamed variables


const { name: studentName, score: finalScore } = student;
[Link](studentName); // 'Bob'
[Link](finalScore); // 95

Spread & [Link]()

const defaults = { theme: 'light', fontSize: 14, language: 'en' };


const userPrefs = { theme: 'dark', fontSize: 16 };

// Merge objects (later properties win)


const settings = { ...defaults, ...userPrefs };
[Link](settings);
// { theme: 'dark', fontSize: 16, language: 'en' }

Looping Through Objects

const laptop = { brand: 'Dell', ram: '16GB', storage: '512GB' };

// for...in
for (let key in laptop) {
[Link](`${key}: ${laptop[key]}`);
}

// [Link]() / [Link]() / [Link]()


[Link]([Link](laptop)); // ['brand', 'ram', 'storage']
[Link]([Link](laptop)); // ['Dell', '16GB', '512GB']
[Link]([Link](laptop)); // [['brand','Dell'], ...]

5.2 Arrays
An array is an ordered, indexed collection of values. Arrays in JavaScript are dynamic — they
can hold mixed types and grow/shrink at runtime.

Creating & Accessing Arrays

// Array literal
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

// Accessing by index (zero-based)


[Link](fruits[0]); // 'Apple'
[Link](fruits[2]); // 'Cherry'
[Link]([Link]); // 4

// Last element
[Link](fruits[[Link] - 1]); // 'Date'
[Link]([Link](-1)); // 'Date' (ES2022)

Modifying Arrays

let nums = [1, 2, 3];

[Link](4, 5); // add to end → [1,2,3,4,5]


[Link](); // remove last → [1,2,3,4]
[Link](0); // add to front → [0,1,2,3,4]
[Link](); // remove first → [1,2,3,4]

// splice(start, deleteCount, ...items)


[Link](1, 1); // remove 1 at index 1 → [1,3,4]
[Link](1, 0, 2); // insert 2 at index 1 → [1,2,3,4]
Essential Array Methods
Method Description Returns
map(fn) Transform each element New array
filter(fn) Keep elements that pass test New array
reduce(fn, Accumulate to single value Any value
init)
find(fn) First matching element Element or undefined
findIndex(fn) Index of first match Number or -1
some(fn) Any element passes? Boolean
every(fn) All elements pass? Boolean
includes(val) Does array contain value? Boolean
indexOf(val) Index of first occurrence Number or -1
slice(start, Copy portion of array New array
end)
flat(depth) Flatten nested arrays New array
sort(fn) Sort in place Same array (mutated)
forEach(fn) Iterate, no return value undefined

Array Methods in Practice

const students = [
{ name: 'Alice', score: 92 },
{ name: 'Bob', score: 58 },
{ name: 'Carol', score: 75 },
{ name: 'Dave', score: 88 },
];

// map – extract names


const names = [Link](s => [Link]);
// ['Alice', 'Bob', 'Carol', 'Dave']

// filter – passing students (score >= 70)


const passed = [Link](s => [Link] >= 70);
// [{Alice,92}, {Carol,75}, {Dave,88}]

// reduce – total score


const total = [Link]((sum, s) => sum + [Link], 0);
// 313

// find – first student with score > 90


const topStudent = [Link](s => [Link] > 90);
// { name: 'Alice', score: 92 }

// sort – by score descending


const ranked = [...students].sort((a, b) => [Link] - [Link]);
// [{Alice,92}, {Dave,88}, {Carol,75}, {Bob,58}]

Array Destructuring

const [first, second, ...rest] = [10, 20, 30, 40, 50];


[Link](first); // 10
[Link](second); // 20
[Link](rest); // [30, 40, 50]

// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];
[Link](a, b); // 2 1

5.3 Objects Inside Arrays (Common Pattern)

const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Phone', price: 699, inStock: true },
{ id: 3, name: 'Tablet', price: 499, inStock: false },
{ id: 4, name: 'Monitor', price: 350, inStock: true },
];

// Get names of in-stock products under $700


const affordable = products
.filter(p => [Link] && [Link] < 700)
.map(p => [Link]);
[Link](affordable); // ['Phone', 'Tablet' → no, 'Monitor']
// Result: ['Phone', 'Monitor']

Summary
Here is a quick reference to the key concepts covered in this lecture:

• Operators – JavaScript offers arithmetic, assignment, comparison, logical, ternary, and


typeof operators to manipulate data and control logic.
• Conditional Statements – if, else if, else, and switch let your program branch based on
conditions. The ternary and nullish coalescing (??) operators provide concise
alternatives.
• for Loop – Best for a known number of iterations. for...of iterates over values; for...in
iterates over object keys.
• while Loop – Best when the number of iterations is unknown; condition evaluated before
each run.
• do...while Loop – Guarantees the body runs at least once; condition evaluated after each
run.
• Functions – Reusable blocks of code. Supports declarations, expressions, arrow
functions, default/rest parameters, closures, and higher-order functions.
• Objects – Key-value pairs for structured data. Use dot or bracket notation to access
properties; destructuring and spread for elegant code.
• Arrays – Ordered collections with a rich set of methods: map, filter, reduce, find, sort,
and more. Combine with objects for powerful data modelling.

End of Lecture Notes

You might also like