JavaScript
Study Notes
Third Year Information Technology
Savitribai Phule Pune University (SPPU)
TEIT – InSem Exam Preparation
Table of Contents
1. Introduction to Scripting Languages
2. Introduction to JavaScript
3. JS Variables and Constants
4. JS Variable Scopes
5. JS Data Types
6. JS Functions
7. JS Arrays
8. JS Objects
9. JS Events
10. Quick Revision – Exam Cheat Sheet
1. Introduction to Scripting Languages
A scripting language is a programming language that is interpreted at runtime rather than
compiled to machine code before execution. It is typically used to automate tasks, control other
software, and add interactivity to applications.
1.1 Key Characteristics
■ Interpreted at runtime (no separate compilation step required)
■ Runs inside a host environment (web browser, operating system, server)
■ Dynamically typed – variable types are determined at runtime
■ High-level, easy-to-read syntax designed for rapid development
■ Used to automate repetitive tasks and control other programs
■ Generally slower than compiled languages but faster to develop
1.2 Types of Scripting Languages
Type Examples Used For
Client-side JavaScript, VBScript Browser interactivity, DOM manipulation
PHP, Python, Ruby,
Server-side Backend logic, database operations
[Link]
Shell/OS Bash, PowerShell, Perl OS automation, file management
Database PL/SQL, T-SQL Stored procedures, DB operations
Embedded Lua, TCL Games, IoT, embedded systems
1.3 Compiled vs Scripting Languages
Aspect Compiled Language Scripting Language
Execution Compiled to machine code first Interpreted line by line at runtime
Speed Faster execution Relatively slower
Examples C, C++, Java JavaScript, Python, PHP
Error Detection At compile time At runtime
Portability Platform-specific binary Host environment portable
★ Exam Tip: Scripting languages are interpreted, not compiled. JavaScript is the most popular
client-side scripting language that runs in the browser without any plugin.
2. Introduction to JavaScript
JavaScript (JS) is a lightweight, interpreted, object-based scripting language with first-class
functions. It was created by Brendan Eich at Netscape in 1995 and standardized as
ECMAScript (ES) by ECMA International.
2.1 History & Versions
Year Version / Event Key Addition
1995 JavaScript 1.0 Created by Brendan Eich at Netscape
1997 ECMAScript 1 (ES1) First standardized version by ECMA
1999 ES3 Regular expressions, try/catch
2009 ES5 Strict mode, JSON, Array methods
2015 ES6 / ES2015 let/const, arrow functions, classes, Promises, modules
2016+ ES2016–ES2024 Async/await, optional chaining, nullish coalescing
2.2 Key Features
■ Interpreted: Executed directly by browser's JavaScript engine (V8, SpiderMonkey)
■ Dynamically Typed: Variable types are resolved at runtime, not declared
■ Event-Driven: Responds to user actions like clicks, keypresses, form submissions
■ Prototype-based OOP: Objects inherit from prototypes, not classical classes
■ First-Class Functions: Functions can be assigned to variables, passed as arguments,
returned
■ Single-threaded: Uses event loop for non-blocking asynchronous operations
■ Cross-platform: Runs on any device with a browser – no installation needed
2.3 How JS Works in Browser
When a webpage loads: (1) Browser downloads HTML → (2) Parses HTML, builds DOM → (3)
Encounters <script> tag → (4) JS engine parses and executes JS → (5) JS can now manipulate
the DOM, respond to events, make network requests.
<!-- Embedding JavaScript in HTML --> <!DOCTYPE html> <html> <head> <script
src="[Link]"></script> <!-- External JS (recommended) --> </head> <body>
<script> [Link]("Inline JS"); // Inline JS </script> <button
onclick="alert('Hi!')">Click</button> <!-- Inline attribute --> </body>
</html>
★ Exam Tip: JS code executes in the browser without any server required. [Link]() is used for
debugging output in browser DevTools (F12).
3. JS Variables and Constants
A variable is a named container for storing data. JavaScript provides three keywords for
declaring variables: var, let, and const.
3.1 Comparison Table
Feature var let const
Scope Function Block Block
Hoisted? Yes (as undefined) No (TDZ error) No (TDZ error)
Re-declarable? Yes No No
Re-assignable? Yes Yes No
Introduced in ES1 (1997) ES6 (2015) ES6 (2015)
Constants &
Use Case Legacy code only Mutable variables
references
3.2 Detailed Examples
// ===== var ===== var x = 10; var x = 20; // Re-declaration: OK (no error)
x = 30; // Re-assignment: OK [Link](x); // 30 // ===== let ===== let y
= 10; // let y = 20; // Re-declaration: ERROR! y = 50; // Re-assignment: OK
[Link](y); // 50 // ===== const ===== const PI = 3.14159; // PI = 3; //
Re-assignment: ERROR! (TypeError) // const with objects - reference is
constant, but contents can change const obj = { name: "Alice" }; [Link] =
"Bob"; // OK! (object itself not re-assigned) // obj = {}; // ERROR!
(re-assigning reference)
3.3 Variable Naming Rules
■ Must begin with a letter, underscore (_), or dollar sign ($)
■ Can contain letters, digits, underscores, dollar signs
■ Cannot start with a digit (e.g., 1name is invalid)
■ Case-sensitive: myVar and myvar are different
■ Cannot use reserved keywords (let, const, function, if, etc.)
■ Conventions: camelCase for variables (myName), PascalCase for classes (MyClass),
UPPER_CASE for constants (MAX_SIZE)
3.4 Hoisting
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their
scope during compilation phase (before code execution).
// What you write: [Link](a); // undefined (not error!) var a = 5; //
What JS engine sees (after hoisting): var a; // Declaration hoisted
[Link](a); // undefined a = 5; // Assignment stays // let/const –
Temporal Dead Zone (TDZ): [Link](b); // ReferenceError: Cannot access
'b' before initialization let b = 10;
★ Exam Tip: Best practice: Always declare variables at the top of their scope. Prefer const by
default, use let when you need to reassign, avoid var.
4. JS Variable Scopes
Scope determines the visibility and lifetime of a variable — where in the code a variable can be
accessed or modified.
4.1 Global Scope
Variables declared outside any function or block have global scope. They are accessible from
anywhere in the JavaScript program.
var globalVar = "I am global"; let globalLet = "Also global"; function
showGlobal() { [Link](globalVar); // Accessible: "I am global"
[Link](globalLet); // Accessible: "Also global" } showGlobal();
[Link](globalVar); // Accessible outside too
4.2 Function Scope (Local Scope)
var declarations inside a function are scoped to that function. They cannot be accessed outside
the function.
function myFunction() { var localVar = "I am local"; let localLet = "Also
local"; [Link](localVar); // OK } myFunction(); [Link](localVar);
// ReferenceError! Not accessible outside [Link](localLet); //
ReferenceError! Not accessible outside
4.3 Block Scope
let and const are block-scoped. A block is any code enclosed in curly braces { }.
if (true) { var x = 10; // var - NOT block scoped (accessible outside) let y
= 20; // let - block scoped const z = 30; // const - block scoped }
[Link](x); // 10 (var leaks out of block) [Link](y); //
ReferenceError! [Link](z); // ReferenceError! // For loop example: for
(var i = 0; i < 3; i++) { } [Link](i); // 3 (var i leaks!) for (let j =
0; j < 3; j++) { } [Link](j); // ReferenceError (let j contained)
4.4 Closures
A closure is when an inner function has access to variables from its outer function's scope, even
after the outer function has returned.
function outer() { let count = 0; // Outer variable function inner() { //
Inner function count++; // Accesses outer variable [Link](count); }
return inner; // Return inner function } const counter = outer(); // outer()
executes, returns inner counter(); // 1 counter(); // 2 counter(); // 3 //
count is preserved in closure!
★ Exam Tip: SPPU Exam: var has function scope (not block scope), which is why it 'leaks' out of
if/for blocks. let and const fix this with block scope.
5. JS Data Types
JavaScript is a dynamically typed language. Variables do not have fixed types — the type is
determined by the value they hold at runtime. JavaScript has 8 data types: 7 primitive and 1
reference (Object).
5.1 Primitive Data Types
Type Description Example Values
Integer and floating-point
Number 42, 3.14, -7, NaN, Infinity
numbers
String Sequence of characters 'hello', "world", template literals
Boolean Logical true/false true, false
Variable declared but not
undefined var x; // x is undefined
assigned
null Intentional absence of value let obj = null;
Integers beyond [Link]
BigInt 9007199254740991n
X_SAFE_INTEGER
Symbol Unique identifier (ES6) Symbol('description')
5.2 Reference Data Types
■ Object: Collection of key-value pairs – { name: 'Alice', age: 21 }
■ Array: Ordered list – [1, 2, 3, 'hello']
■ Function: Callable object – function greet() { }
■ Date, RegExp, Map, Set: Built-in reference types
5.3 typeof Operator
typeof 42 // "number" typeof 3.14 // "number" typeof "hello" // "string"
typeof true // "boolean" typeof undefined // "undefined" typeof null //
"object" ← Famous JS quirk (historical bug!) typeof {} // "object" typeof
[] // "object" ← Arrays are objects! typeof function(){} // "function"
typeof Symbol() // "symbol" typeof 42n // "bigint"
5.4 Type Coercion
JavaScript automatically converts types when needed. This is called implicit type coercion.
// String + Number = String (concatenation) "5" + 3 // "53" (3 converted to
string) "Hello" + 5 // "Hello5" // Arithmetic operators coerce to Number "5"
- 3 // 2 ("5" converted to number) "5" * 2 // 10 "5" / 2 // 2.5 "abc" - 1 //
NaN (Not a Number) // Comparison "5" == 5 // true (loose equality, type
coercion) "5" === 5 // false (strict equality, no coercion) null ==
undefined // true (loose) null === undefined // false (strict) // Falsy
values: false, 0, "", null, undefined, NaN // All other values are truthy
★ Exam Tip: Exam: typeof null is 'object' (historical bug). Use === (strict equality) instead of ==
(loose equality) to avoid unexpected type coercion bugs.
6. JS Functions
A function is a reusable block of code that performs a specific task. In JavaScript, functions are
first-class objects — they can be stored in variables, passed as arguments, and returned from
other functions.
6.1 Function Declaration
// Syntax function functionName(param1, param2) { // function body return
value; // optional } // Example function add(a, b) { return a + b; } let
result = add(3, 5); // 8 // Hoisted - can call before declaration
[Link](greet("Alice")); // Works! function greet(name) { return
"Hello, " + name; }
6.2 Function Expression
// Anonymous function expression const multiply = function(a, b) { return a
* b; }; multiply(4, 5); // 20 // Named function expression (useful for
recursion and debugging) const factorial = function fact(n) { return n <= 1
? 1 : n * fact(n-1); }; factorial(5); // 120 // NOT hoisted - calling before
declaration gives TypeError multiply(2,3); // TypeError if called before
this line
6.3 Arrow Functions (ES6)
// Full syntax const add = (a, b) => { return a + b; }; // Concise body
(single expression - implicit return) const add = (a, b) => a + b; // Single
parameter - no parentheses needed const double = x => x * 2; // No
parameters - empty parentheses required const greet = () => "Hello, World!";
// Arrow functions do NOT have their own 'this' const obj = { name: "Alice",
regularFn: function() { return [Link]; }, // "Alice" arrowFn: () =>
[Link] // undefined (uses outer 'this') };
6.4 Parameters & Arguments
// Default Parameters (ES6) function greet(name = "Guest", greeting =
"Hello") { return greeting + ", " + name + "!"; } greet(); // "Hello,
Guest!" greet("Alice"); // "Hello, Alice!" greet("Bob", "Hi"); // "Hi, Bob!"
// Rest Parameters (variable number of arguments) function sum(...numbers) {
return [Link]((total, n) => total + n, 0); } sum(1, 2, 3, 4); // 10
// arguments object (available in regular functions only) function show() {
[Link](arguments); // Array-like object of all args }
6.5 IIFE – Immediately Invoked Function Expression
// IIFE syntax (function() { let privateVar = "I am private";
[Link](privateVar); })(); // () at end invokes it immediately // Arrow
function IIFE (() => { [Link]("Arrow IIFE"); })(); // Use case: Create
private scope, avoid polluting global scope
★ Exam Tip: Exam: Function Declaration is hoisted (can call before definition). Function
Expression and Arrow Function are NOT hoisted. Arrow functions don't have their own 'this'.
7. JS Array
An array is an ordered collection of elements. Arrays in JavaScript are objects that can hold
values of any type (mixed types allowed). Array indices start from 0.
7.1 Creating Arrays
// Array literal (preferred) const fruits = ["Apple", "Banana", "Mango"]; //
Array constructor const nums = new Array(3); // [empty x3] const nums2 = new
Array(1,2,3); // [1, 2, 3] // Mixed types (JavaScript allows this) const
mixed = [1, "hello", true, null, {x: 5}, [1,2]]; // Access elements
fruits[0]; // "Apple" (first element) fruits[2]; // "Mango" (third element)
[Link]; // 3 // Modify elements fruits[1] = "Grapes"; // ["Apple",
"Grapes", "Mango"]
7.2 Important Array Methods
Method Description Example
Add element at end; returns
push(x) [Link]('Orange') // 4
new length
Remove and return last
pop() [Link]() // 'Mango'
element
Add element at start; returns
unshift(x) [Link]('Kiwi')
new length
Remove and return first
shift() [Link]() // 'Apple'
element
splice(i,n,x Remove n elements at index
[Link](1, 2, 'Plum')
...) i, optionally insert x
Return new array from index
slice(i,j) [Link](0, 2)
i to j (exclusive)
indexOf(x) Return first index of x, or -1 [Link]('Banana')
includes(x) Return true if x exists in array [Link]('Apple')
Merge arrays; returns new
concat(arr) [Link](arr2)
array
Convert to string with
join(sep) [Link](', ')
separator
reverse() Reverse array in place [Link]()
Sort array (default:
sort(fn) [Link]((a,b) => a-b)
alphabetical)
New array with fn applied to
map(fn) [Link](f => [Link])
each element
New array with elements
filter(fn) [Link](n => n > 5)
passing fn test
reduce(fn,in
Reduce array to single value [Link]((acc,n) => acc+n, 0)
it)
Execute fn for each element
forEach(fn) [Link]([Link])
(no return)
Return first element
find(fn) [Link](n => n > 5)
satisfying fn
True if any element satisfies
some(fn) [Link](n => n > 10)
fn
every(fn) True if all elements satisfy fn [Link](n => n > 0)
flat() Flatten nested arrays [1,[2,[3]]].flat(Infinity)
7.3 ES6+ Array Features
// Spread operator const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const
combined = [...arr1, ...arr2]; // [1,2,3,4,5,6] const copy = [...arr1]; //
Shallow copy // Destructuring const [first, second, ...rest] = [1, 2, 3, 4,
5]; // first=1, second=2, rest=[3,4,5] // [Link]() [Link]("hello");
// ['h','e','l','l','o'] [Link]({length:3}, (_, i) => i+1); // [1,2,3]
★ Exam Tip: Exam: splice() modifies original array and returns removed elements. slice() returns
new array without modifying original. map/filter always return new arrays.
8. JS Object
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).
8.1 Creating Objects
// 1. Object Literal (most common) const student = { name: "Rahul Sharma",
rollNo: 42, branch: "Information Technology", cgpa: 8.7, greet: function() {
// Method return "Hi, I am " + [Link]; } }; // 2. Using new Object()
const car = new Object(); [Link] = "Toyota"; [Link] = "Camry"; // 3.
Constructor Function function Person(name, age) { [Link] = name; [Link]
= age; [Link] = function() { return "Hello, " + [Link]; }; } const p
= new Person("Alice", 21); // 4. ES6 Class (syntactic sugar over constructor
functions) class Animal { constructor(name, sound) { [Link] = name;
[Link] = sound; } speak() { return [Link] + " says " + [Link]; }
} const dog = new Animal("Dog", "Woof"); [Link](); // "Dog says Woof"
8.2 Accessing & Modifying Properties
// Dot notation [Link]; // "Rahul Sharma" [Link] = 9.0; //
Modify property // Bracket notation (useful for dynamic keys)
student["rollNo"]; // 42 let key = "branch"; student[key]; // "Information
Technology" // Adding new property [Link] = 3; // Deleting property
delete [Link]; // Checking if property exists "name" in student; //
true [Link]("cgpa"); // false (deleted)
8.3 ES6+ Object Features
// Destructuring const { name, rollNo, branch } = student; // With renaming:
const { name: studentName } = student; // Shorthand property names const
name = "Alice"; const age = 21; const person = { name, age }; // { name:
"Alice", age: 21 } // Spread operator const extra = { year: 3, sem: 5 };
const fullProfile = { ...student, ...extra }; // Computed property names
const prefix = "std"; const obj = { [prefix + "Name"]: "Bob" }; // {
stdName: "Bob" } // [Link](), [Link](), [Link]()
[Link](student); // ["name", "rollNo", "branch", ...]
[Link](student); // ["Rahul", 42, "IT", ...]
[Link](student); // [["name","Rahul"], ["rollNo",42], ...] //
Iterating over object for (let key in student) { [Link](key + ": " +
student[key]); }
8.4 this Keyword
The this keyword refers to the object that the function belongs to. Its value depends on how the
function is called.
const obj = { name: "Alice", greet: function() { return "Hi " + [Link];
// this = obj }, greetArrow: () => { return "Hi " + [Link]; // this =
undefined/global (no own 'this') } };
★ Exam Tip: Exam: this in a regular method = the object. this in an arrow function = outer/enclosing
context. Prototype chain: when a property is not found on object, JS looks up the prototype chain.
9. JS Events
An event is an action or occurrence that happens in the browser — like a user clicking a button,
pressing a key, submitting a form, or a page finishing loading. JavaScript can listen and
respond to these events.
9.1 Event Handling Methods
// Method 1: Inline HTML attribute (Not recommended for large apps) <button
onclick="greet()">Click Me</button> <input onkeyup="handleKey(event)" /> //
Method 2: DOM Property const btn = [Link]("myBtn");
[Link] = function() { alert("Button clicked!"); }; // Problem: Can only
assign ONE handler per event // Method 3: addEventListener (Recommended -
Best Practice) [Link]("click", function(event) {
[Link]("Button clicked!"); [Link]([Link]); // The element
that triggered the event }); // Multiple handlers on same element:
[Link]("click", handler1); [Link]("click",
handler2); // Both work! // Remove event listener
[Link]("click", handler1);
9.2 Common Event Types
Category Events Description
click, dblclick, mouseover, mouseout,
Mouse User mouse interactions
mousemove, mousedown, mouseup
Keyboard keydown, keyup, keypress Keyboard key presses
Form submit, change, focus, blur, input, reset Form element interactions
Window/Docum load, DOMContentLoaded, resize, scroll,
Page lifecycle events
ent unload
Clipboard copy, cut, paste Clipboard operations
Drag dragstart, drag, dragover, drop Drag and drop operations
Touch touchstart, touchmove, touchend Mobile touch events
9.3 The Event Object
[Link]("myBtn").addEventListener("click", function(e) {
[Link]([Link]); // "click" [Link]([Link]); // Element that was
clicked [Link]([Link]); // Element listener is attached to
[Link]([Link], [Link]); // Mouse coordinates [Link]();
// Prevent default browser action [Link](); // Stop event from
bubbling up }); // Keyboard event [Link]("keydown",
function(e) { [Link]([Link]); // e.g., "Enter", "a", "ArrowLeft"
[Link]([Link]); // Numeric code (deprecated)
[Link]([Link]); // true if Ctrl held }); // Form submit
[Link]("form").addEventListener("submit", function(e) {
[Link](); // Prevent page reload const data = new
FormData([Link]); [Link]([Link]("username")); });
9.4 Event Bubbling and Capturing
When an event occurs on an element, it propagates through the DOM in two phases:
■ Capturing phase: Event travels from window DOWN to the target element
■ Bubbling phase: Event travels from target element UP through ancestors to window
(default)
// Event Bubbling (default)
[Link]("parent").addEventListener("click", () => {
[Link]("Parent clicked"); // Fires after child });
[Link]("child").addEventListener("click", () => {
[Link]("Child clicked"); // Fires first }); // Use Capturing: pass true
as 3rd argument [Link]("parent").addEventListener("click",
handler, true); // Stop bubbling [Link]("click",
function(e) { [Link](); // Parent's handler won't fire });
★ Exam Tip: Exam: addEventListener allows multiple handlers; onclick/HTML attributes allow only
one. Event bubbling: child → parent → document. [Link]() prevents browser default
actions (like form submission or link navigation).
10. Quick Revision – TEIT InSem Cheat Sheet
Scripting Languages
■ Interpreted (not compiled), runs in host environment
■ JS = Client-side scripting language, runs in browser's JS engine
■ Types: Client-side (JS), Server-side (PHP, Node), Shell (Bash), DB (PL/SQL)
Variables & Constants
■ var: function scope, hoisted (as undefined), re-declarable
■ let: block scope, not hoisted (TDZ), not re-declarable
■ const: block scope, not hoisted, not re-assignable (but object properties can change)
■ Best practice: const > let > var
Scopes
■ Global: accessible everywhere in program
■ Function: var is scoped to function, not accessible outside
■ Block: let/const scoped to { } block
■ Closure: inner function retains access to outer function's variables
■ Hoisting: var declarations moved to top of scope (as undefined)
Data Types
■ 7 Primitives: Number, String, Boolean, null, undefined, BigInt, Symbol
■ Reference: Object, Array, Function (stored by reference, not value)
■ typeof null === 'object' → Famous JS quirk (historical bug)
■ Type coercion: '5' + 3 = '53' (string), '5' - 3 = 2 (number)
■ === (strict) vs == (loose with type coercion) — always prefer ===
Functions
■ Declaration: hoisted, function greet() { }
■ Expression: not hoisted, const f = function() { }
■ Arrow: not hoisted, no own this, const f = (x) => x*2
■ IIFE: (function() { })() — immediately invoked, creates private scope
■ Default params: function f(x=0) { } | Rest: function f(...args) { }
■ Closure: inner function accesses outer function's variables
Arrays
■ push/pop: add/remove from END | unshift/shift: add/remove from START
■ splice(i,n): removes n elements at index i, modifies original array
■ slice(i,j): returns new sub-array from i to j, original unchanged
■ map: transforms each element → new array
■ filter: keeps elements passing test → new array
■ reduce: reduces to single value
■ Spread: [...arr1, ...arr2] merges arrays
Objects
■ Object literal: const obj = { key: value, method() { } }
■ Dot notation: [Link] | Bracket: obj['key'] or obj[variable]
■ this = refers to the object inside a method (not in arrow functions)
■ Destructuring: const { name, age } = obj
■ Spread: const newObj = { ...obj, extra: value }
■ [Link](obj), [Link](obj), [Link](obj)
Events
■ 3 methods: Inline HTML, DOM property (onclick), addEventListener (best)
■ addEventListener allows multiple handlers on same event
■ Event object: [Link], [Link], [Link]/Y, [Link]
■ [Link](): stop browser default (form submit, link navigate)
■ [Link](): stop event bubbling up to parent elements
■ Bubbling: child → parent → document (default direction)
■ Common events: click, keydown, submit, load, mouseover, change
All the best for your SPPU TEIT InSem Examination! ■
Information Technology Department · Savitribai Phule Pune University