JS
🔹 1. Document Object Model (DOM) Methods
Methods to interact with HTML elements.
📌 Selecting Elements
document.getElementById("id") → Selects an element by id.
document.getElementsByClassName("class") → Selects elements by class (returns
HTMLCollection).
document.getElementsByTagName("tag") → Selects elements by tag name (returns
HTMLCollection).
document.querySelector("selector") → Selects the first matching element.
document.querySelectorAll("selector") → Selects all matching elements (returns
NodeList).
📌 Manipulating Elements
element.innerHTML = "New content" → Changes the HTML inside an element.
element.textContent = "New text" → Changes only the text inside an element.
element.setAttribute("attribute", "value") → Sets an attribute (href, src, etc.).
element.getAttribute("attribute") → Gets the value of an attribute.
element.classList.add("newClass") → Adds a class.
element.classList.remove("oldClass") → Removes a class.
element.classList.toggle("toggleClass") → Toggles a class on/off.
element.style.property = "value" → Changes CSS styles (element.style.color =
"red").
📌 Creating & Removing Elements
document.createElement("tag") → Creates a new element.
parent.appendChild(childElement) → Adds an element inside another.
parent.insertBefore(newElement, referenceElement) → Inserts before another
element.
parent.removeChild(childElement) → Removes an element.
🔹 2. Event Handling Methods
Methods for handling user interactions (clicks, keyboard input, etc.).
element.addEventListener("event", function) → Attaches an event listener.
element.removeEventListener("event", function) → Removes an event listener.
event.preventDefault() → Stops the default action (e.g., prevent form submission).
event.stopPropagation() → Stops event bubbling (prevent parent elements from
being affected).
Common Events:
Event Description
"click" Fires when an element is clicked.
"mouseove Fires when the mouse hovers over an
r" element.
"keydown" Fires when a key is pressed.
"keyup" Fires when a key is released.
"load" Fires when a page is fully loaded.
"submit" Fires when a form is submitted.
🔹 3. Console & Debugging Methods
Used to log and debug JavaScript code.
console.log(value) → Prints a value to the console.
console.warn(value) → Prints a warning message.
console.error(value) → Prints an error message.
console.table(arrayOrObject) → Displays data as a table.
🔹 4. Timer Methods
Used to delay or repeat functions.
setTimeout(function, milliseconds) → Runs a function after a delay.
setInterval(function, milliseconds) → Runs a function repeatedly.
clearTimeout(timeoutID) → Cancels a timeout.
clearInterval(intervalID) → Cancels an interval.
Example:
js
Copy code
setTimeout(() => console.log("Hello after 2 seconds"), 2000);
🔹 5. String Methods
Methods for manipulating text.
Method Description
"Hello".length Returns the length of the string.
"Hello".toUpperCase
Converts to uppercase.
()
"Hello".toLowerCase
Converts to lowercase.
()
Returns the character at index 1
"Hello".charAt (1)
("e").
"Hello".indexOf
Finds the position of "e".
("e")
"Hello".replace ("H",
Replaces "H" with "J".
"J")
"Hello".substring(1,
Extracts "ell".
4)
" Hello ".trim() Removes spaces from both ends.
Converts to an array ["H", "e", "l",
"Hello".split("")
"l", "o"].
🔹 6. Array Methods
Methods for working with lists of data.
Method Description
array.length Returns the number of elements.
array.push(item) Adds an item at the end.
array.pop() Removes the last item.
Method Description
array.unshift(item) Adds an item at the beginning.
array.shift() Removes the first item.
array.indexOf(item) Finds the index of an item.
Checks if an item exists
array.includes(item)
(true/false).
array.reverse() Reverses the array.
Sorts the array (alphabetically by
array.sort()
default).
array.join(", ") Converts an array to a string.
array.slice(start, end) Copies part of an array.
array.splice(index, deleteCount,
Removes/adds items.
newItems...)
🔹 7. Math Methods
Methods for performing calculations.
Method Description
Math.round(4.6) Rounds to 5.
Math.floor(4.9) Rounds down to 4.
Math.ceil(4.1) Rounds up to 5.
Math.abs(-5) Returns absolute value 5.
Generates a random number (0
Math.random()
to 1).
Math.max(5, 10,
Returns 15.
15)
Math.min(5, 10,
Returns 5.
15)
Math.pow(2, 3) Calculates 2^3 (Result: 8).
Math.sqrt(16) Returns 4 (square root).
🔹 8. Date Methods
Used to work with dates and times.
new Date () → Gets the current date/time.
date.getFullYear () → Returns the year.
date.getMonth () → Returns the month (0-11).
date.getDate () → Returns the day of the month.
date.getDay () → Returns the day of the week (0 = Sunday).
date.getHours () → Returns the hour.
date.getMinutes () → Returns the minutes.
date.getSeconds () → Returns the seconds.
🔹 9. JSON Methods
Used for working with JSON data.
JSON.stringify(object) → Converts an object into a JSON string.
JSON.parse(string) → Converts a JSON string into an object.
Example:
Js code
let obj = {name: "John", age: 30};
let jsonString = JSON.stringify(obj); // '{"name":"John","age":30}'
let parsedObj = JSON.parse(jsonString); // {name: "John", age: 30}
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML or innerText.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
innerHTML property to change the HTML content of the HTML element
innerText property to change the inner text of the HTML element
For testing purposes, it is convenient to use document.write():
document.write(5 + 6);
Using document.write() after an HTML document is loaded, will delete all existing HTML:
the window.print() method in the browser to print the content of the current
window.
Featu CS Programming
re HTML S Language?
Synta ✅
✅ Yes ✅ Yes
x Yes
Computations
❌ No ❌ No ✅ Yes
(2+2)
Conditionals (if-
❌ No ❌ No ✅ Yes
else)
Loops (for,
❌ No ❌ No ✅ Yes
while)
Functio ❌
❌ No ✅ Yes
ns No
Turing
❌ No ❌ No ✅ Yes
Complete?
In jQuery $("p"); means "select all p elements".
Difference Between var, let and const
Scope Redeclare Reassig Hoisted Binds
n this
var No Yes Yes Yes Yes
let Yes No Yes No No
const Yes No No No No
Constant Objects and Arrays
The keyword const is a little misleading.
It does not define a constant value. It defines a constant reference to a value.
Because of this you can NOT:
Reassign a constant value
Reassign a constant array
Reassign a constant object
But you CAN:
Change the elements of constant array
Change the properties of constant object
JavaScript Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016) x ** y produces the same result
as Math.pow(x,y):
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
JavaScript Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
JavaScript Comparison Operators
Operat Description
or
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
JavaScript Logical Operators
Operat Description
or
&& logical and
|| logical or
! logical not
JavaScript Type Operators
Operator Description
typeof Returns the type of a variable
Instanceof Returns true if an object is an instance of an object type
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result
is converted back to a JavaScript number.
Operat Description Examp Sam Resu Decim
or le e as lt al
& AND 5&1 0101 0001 1
&
0001
| OR 5|1 0101 0101 5
|
0001
~ NOT ~5 ~01 1010 10
01
^ XOR 5^1 0101 0100 4
^
0001
<< left shift 5 << 1 0101 1010 10
<< 1
>> right shift 5 >> 1 0101 0010 2
>> 1
>>> unsigned 5 >>> 0101 0010 2
right shift 1 >>>
1
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Shift Assignment Operators
Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y
Bitwise Assignment Operators
Operator Example Same As
&= x &= y x=x&y
^= x ^= y x=x^y
|= x |= y x=x|y
Logical Assignment Operators
Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)
JavaScript has 8 Datatypes
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
The Object Datatype
The object data type can contain both built-in objects, and user defined objects:
Built-in object types can be:
JavaScript Types are Dynamic
75—
1. 1-
2. 2-
3. 3
4. -4
5. -5
6. -6
7. -7
8. -8-
9. let
10. Const
11.