JavaScript full note
JavaScript full note
Tip { always link your JavaScript file at the bottom of your html body. }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" /> <!-- linking css file
-->
<title>js</title>
</head>
<body>
<p id="myp" > < p >
<script src="script.js"></script> <!--linking js file-->
</body>
</html>
color in css
hsla(hue, saturation, lightness, alpha)
The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at
all):
comments
// single line comment
/ multi line comment */
output
console.log("hello"); //to output on console ( you can also use single quote or
backticks ) { use it like print or cout }
window.alert("how are you"); // this is an alert ( popup window)
VARIABLES
let x; // variable declaration {variable name needs to be unique}
x=10; // variable assignment
let x = 10; // declaration and assignment together.
Note:
you can use ${ } for a formatted string like python but only with backticks.
eg: let age = 10 ;
console.log( you are ${age} years old. ) // output: you are 10 years old.
Arithmetic operations
we have + , - , * , / , ** , % and increment/decrement
example: ```let product = 3;
product = product 7; // same as product =2;
let remainder = 17 % 5; // Result: 2;
we use "BODMAS"
Accepting input
- we have to ways
username = document.getElementById("txt").value;
`window.alert(Hi , ${username} ); } `
the above code takes a value from the input text box and assigns it to the variable username
and then displays the message in alert mode
Implicit Conversion:
JavaScript automatically converts types in certain situations. For example, when you
use non-numeric strings with minus ( - ), multiplication ( * ), or division ( / ) operators,
JavaScript tries to convert the strings to numbers.
If you try to add a number to a string, the number will be converted into a string and
concatenated.
Explicit Conversion:
Math in js
Math.PI , Math.E , Math.log(x) , Math.sin(x) , Math.sqrt(x) , Math.pow(x,y);
, Math.abs(x);
Math.round(x); // rounds the number x
Math.floor(x); // always rounds to smallest
Math.ceil(x); // always rounds to largest
Math.trunc(x); // removes the decimal part
Math.sign(x); // to find the sign of x. (+1 , -1 or 0)
Math.min(x,y,z);
Math.max(x,y,z);
Math.random(); // gives you random number b/n 0 and 1
IF statement
if (condition 1) {
task to be done
}
else if(condition 2){
task 2
}
else {
task 3
}
.checked
used to determine the checked state of an HTML checkbox or radio button element
example : checked.html in the programs folder
Ternary operator
condition ? value_if_true : value_if_false
Switch
switch (expression) {
case value1:
// Code block executed if expression matches value1
break;
case value2:
// Code block executed if expression matches value2
break;
// More cases...
default:
// Code block executed if no match is found
}
example:
let score = 80;
let grade;
switch (true) {
default:
grade = "F";
break;
}
console.log(grade);`
string methods
used to manipulate text (string).
8. .endsWith(searchString) :
Checks if a string ends with the specified searchString .
Example: JavaScript
9. .includes(searchString) :
Checks if a string contains the specified searchString .
Example: JavaScript
13. .slice(starting index, ending index) creates a new string without modifying the
original one.
example:
let text = "Hello, World!";
let slicedText = text.slice(7, 12);
console.log(slicedText); // Output: "World"
method chaining
calling one method after the other in a continuous line of code.
example:
let username = window.prompt("what is your name?");
username= username.trim().charAt(0).toUpperCase() +
username.trim().slice(1,).toLowerCase();
window.alert(your name is ${username} );`
logical operators
! Not
&& and "NAOL" // PRECIDENCE
|| or
operators
= // Assignment operator
== // comparision operator 3 == "3"
!= // inequality operator
=== //strict equality operator(compare if values & datatype are equal)
!== //strict inequality operator 3 !== "3"
While Loop
while(condition){
task
}
do While Loop
do{
task
}while(condition);
for loop
for(let i = 0; i < 3; i++){
console.log(i);
}
continue; //skips an iteration
break; // ends the loop
function
function name(){ //function declaration
task
}
name() //function calling
example:
function add(x,y){
let z = x + y;
return z; //if there is no return the output will be undefined
}
window.alert(add(1,2));
Array
let x = [1,2,3]; // array
console.log(x[0]); //1
console.log(x[3]); // undefined
x[1]=4; // modifying
Methods in array
x.push(4); // adds 4 to the end of an array
x.pop(); // removes the last element
x.unshift(0); // adds 0 to the beginning of the array
x.shift(); // removes the 1st object
x.length; // number of elements of an array
x.indexOf(3); // 2 if the element doesn't exist it returns -1
x.sort(); //ascending order
x.reverse(); //descending order
//we can use string methods for an array
callback
A function that is passed as an argument to another function.
used for asynchronous operations. like : reading a file and network request.
example:
function x (result) {
console.log(result);
}
function sum(callback , a , b ){
let result = a + b;
callback(result);
}
sum(x , 1 , 2); //displays 3
.forEach()
method used to iterate over the elements of an array and apply a specified function
(callback) to each elements
For each element in the array, the callback function is executed.
The callback function receives three parameters: the current element , its index ,
and the entire array .
Does not create a new array; operates on the original array in place.
array.forEach(callback);
example:
let x = [1, 2, 3, 4, 5];
.map()
accepts a callback and it applies that function to each elements of an array and then
returns a new array.
same as forEach but this creates new array(doesn't modify the original).
example:
const x = [1, 2, 3, 4, 5];
function square(element, index, array) {
return Math.pow(element, 2);
}
let y = x.map(square);
console.log(x); //(5) [1, 2, 3, 4, 5]
console.log(y); //(5) [1, 4, 9, 16, 25]
.filter()
creates a new array by filtering out elements.
example:
.reduce()
reduces elements of an array to a single element.
example:
const price = [5 ,30 ,10 ,25 ,15 , 20];
const total = price.reduce(sum);
console.log($${total.toFixed(2)}); //$105.00
function sum (accumulator , element){
return accumulator + element;
}
accumulator : The value previously returned by the callback.
With Initial Value:
- The accumulator ( acc ) starts with the provided initial value.
- The iteration includes all elements of the array.
example: const grades = [75, 50, 90, 80, 65, 95];
function getMax(acc, curr) {
return Math.max(acc, curr);
}
// Initializing the accumulator with -Infinity to ensure it works with
any set of numbers
const maximum = grades.reduce(getMax, -Infinity);
console.log(maximum); // Output: 95
Without Initial Value:
- The accumulator ( acc ) starts with the first element.
- The iteration starts from the second element.
currentValue : Each element in the array, one by one.
}
Initial Accumulator ( acc ): Not specified, so the first element of the array is used by default
( 75 ).
Step-by-Step Execution
First Iteration:
acc = 75 , curr = 50
Math.max(75, 50) = 75
New acc = 75
Second Iteration:
acc = 75 , curr = 90
Math.max(75, 90) = 90
New acc = 90
Third Iteration:
acc = 90 , curr = 80
Math.max(90, 80) = 90
New acc = 90
Fourth Iteration:
acc = 90 , curr = 65
Math.max(90, 65) = 90
New acc = 90
Fifth Iteration:
acc = 90 , curr = 95
Math.max(90, 95) = 95
New acc = 95
Final acc (maximum value) = 95
Function expression
defining a function as a value or variable.
example: Anonymous Function Expression(You create an unnamed function and
assign it to a variable.)
const hello = function(){
console.log("Hello , World")
};
hello(); // Hello , World
setTimeout( function () {
console.log("Hello , World"); } , 3000);
clearTimeout(timeoutid)
cancel a timeout before it triggers.
example:
JavaScript
JavaScript
2. Shorter Syntax:
If the function has only one statement that returns a value, you can omit the curly
braces and the return keyword.
Example: JavaScript
3. Parameters:
JavaScript
```javascript
const greet = (name) =>console.log( "Hello, " + name);
greet("Henok"); // Hello, Henok
```
here if you do more than 1 task use curly brace:
```javascript
const greet = (name) => {console.log( "Hello, " + name);
console.log("Welcome!"); }
greet("Henok"); // Hello, Henok
// Welcome!
``````
more example:
setTimeout( ( ) =>console.log( "hello") , 2000); // will output "hello" after 2s
OBJECT
collection of related properties and/or methods( functions that belong to an object ) that
can represent real world objects.(people ,p products , places ).
object = { key:value or/and function() }
example:
const student1 = {
name: "Henok",
age: 19,
year: 2,
employed: false, //this and the above 3 are properties
greet: function () { console.log("how are you?"); }, // method
};
console.log( student1.name ); //Henok
student1.greet(); // how are you?
delete student1.age // delete age property
console.log( year in student1); // true
this
is a reference to the object where this is used. example:
1. Object Methods:
In an object method, this refers to the object itself. It allows access to the
object’s properties and methods within the method’s scope.
Example: JavaScript
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;//same as
person.lastName
}
};
3. Strict Mode:
In strict mode, when used alone, this is undefined .
Example: JavaScript
"use strict";
let x = this; // Now, `this` is `undefined`
JavaScript
```javascript
// Define a class named 'Person'
class Person {
constructor(name , age) {
this.name = name;
this.age = age;
}
sayHi() {
console.log(`Hello, my name is ${this.name}!`);
}
}
class are like a blue print for the house and the object is the
house. and we use the constructor in side of the class + the
"new" key word are used to change the class (blue print ) into
an object( house ).
example :
//class
class House{
constructor(color){
this.color = color;
}
furniture(){
return "sofa";
}
}
//object
const house1 = new House("red");
const house2 = new House("green");
//output
console.log(house1.color);
console.log(house2.color);
console.log(house1.furniture());
Static
A static method is a function that belongs to the class itself, not to its instances
(objects).
You define a static method using the static keyword within the class.
These methods are often utility functions, like creating or cloning objects.
Example
class User {
static pi = 4;
static staticMethod() {
console.log("This is a static method.");
}
}
console.log(user.pi); //4 * we just use the name of the class
we dont nedd to create an
object to access it. *
User.staticMethod(); // Output: "This is a static method."
Inheritance
allows a new class to inherit properties and methods from an existing class using the
extends keyword.
example:
class animal{
alive = true;
eat() {
console.log(`This ${ this.name} is eating`);
}
}
//child class(extended from parent)
class fish extends animal{
name="fish";
}
//objects
const fish1 = new fish();
const cat1 = new cat();
//output
fish1.eat(); //This fish is eating
console.log(cat1.alive); // true
super
allows you to access properties and methods from the parent class (also known as the
superclass).
Note that super() must be called before using this in the constructor of the derived
class.
```javascript
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
// Other methods...
}
JavaScript
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
study() {
console.log(`${this.name} is studying.`);
}
}
getter/setter
getters and setters are used to define how object properties are accessed and updated.
example:
class Person {
constructor(name, age) {
this._name = name; // Use a private variable (conventionally with
an underscore)
this._age = age;
}
// Using getters
console.log(person.name); // John
console.log(person.age); // 25
// Using setters
person.name = 'Jane';
person.age = 30;
console.log(person.name); // Jane
console.log(person.age); // 30
// Invalid assignments
person.name = 123; // Name must be a string
person.age = -5; // Age must be a positive number
destructuring
used for extracting values from arrays and objects, then assign them to variables in a
convenient way.
[] = to perform array destructuring
{ } = to perform object destructuring
5 - examples
1)Swap the value of two variables
let a = 1;
let b = 2;
[a,b] = [b,a];
console.log(a); //2
console.log(b); //1
const person1 = {
name = "henok",
age = 19,
job = "freelancer",
}
const person2 = {
name = "samri",
age = 14,
}
const {Name1 , Age1 , Job1 = "Unemployed"} = person1;
const {Name2 , Age2 , Job2 = "Unemployed"} = person2;
console.log(Name1); //henok
console.log(Age1); //19
console.log(Job1);//freelancer
console.log(Name2); //samri
console.log(Age2); //12
console.log(Job2);//Unemployed
}
display(person1); //afomia
//13
//Unemployed
Nested objects
Objects inside of other objects.
Allows you to represent more complex data structures.
child object is inside of parent object
example: person{ Address{ }, contactInfo{ } }
example2:
const person = {
name:spongebob ,
age: 30 ,
hobbies: ["karate" , "jellyFishing" , "cooking"] , //we can also add an
array
adress: { //nested object
street:"124 conch st." ,
city: "bikini bottom"
}
}
console.log(person.hobbies[0]); //karate
console.log(person.adress.city); //bikini bottom
Arrays of object
example:
const fruits = [{name:"apple" , color : "red"},
{name:"orange" , color : "orange"}
{name:"banana" , color : "yellow"}
{name:"mango" , color : "green"} ]
console.log(fruits[0].name); //apple
.sort()
is used to sort the elements of an array.
By default, it sorts the elements as strings in ascending order.
1. Alphabetical Sorting:
If you have an array of strings (e.g., ["Banana", "Orange", "Apple",
"Mango"] ), calling .sort() will arrange them alphabetically: ["Apple",
"Banana", "Mango", "Orange"] .
Keep in mind that this method overwrites the original array.
2. Numerical Sorting:
When sorting numbers, the default behavior can be problematic. For
example, "25" is considered greater than "100" because "2" comes
after "1" .
To sort numbers correctly, you can provide a custom comparison function. For
ascending order, use:
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => b - a);
const highest = points[0];
// Result: 100
```
more examples:
Date objects
Can be changed or formatted.
Date(year, month, day, hour, minute, second, millisecond)
const date = new Date();
Closure
created when a function is defined within another function.
The inner function has access to the variables and scopes of the outer function.
Allows for privet variables and state maintenance used frequently in js frameworks like
react ,Vue ,Angular.
example:
function outer(){
let message = "Hello";
function inner(){
console.log(message);
}
return inner();
}
function createGame(){
let score = 0;
function increaseScore(points){
score += points;
console. log(`+${points}pts`);
}
function decreaseScore(points){
score-=points;
console. log(`+${points}pts`);
}
function getScore(){
return score;
}
return {increaseScore,decreaseScore, getScore};
}
const game =createGame();
game.increaseScore(5); // +5pts
game.decreaseScore(2);// -2pts
console.log(game.getScore(5));//3
ES6 Module
An external file that contains reusable code that can be imported into other JavaScript
files.
We can Write reusable code for many different applications. and can contain variables,
classes, functions and more.
Introduced as part of ECMAScript 2015 update
example:
HTML-File:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<style></style>
</head>
<body>
<script src="index.js" type="module"></script>
</body>
</html>
Module-File: ( mathUtill.js )
Js-File (index.js)
console.log(pi); //3.14159
console.log(Math.floor(area(2)); // 25
synchronous
Executes line by line consecutively in a sequential manner Code that waits for an
operation to complete.
Each operation waits for the previous one to complete before executing.
example:
console.log('One');
console.log('Two');
console.log('Three');
// LOGS: 'One', 'Two', 'Three'
asynchronous
Allows multiple operations to be performed concurrently without waiting Doesn't block
the execution flow and allows the program to continue (1/0 operations, network
requests, fetching data) Handled with: callbacks, promises, A sync/Await
Error
An Object that is created to represent a problem that occurs.
Occur often with user input or establishing a connection.
Errors can be generated from different issues like : NETWORK ERRORS, PROMISE
REJECTION, SECURITY ERRORS
types of errors
1. Syntax Error: This error occurs when the code contains invalid syntax. For example,
missing a closing bracket or using a reserved keyword incorrectly.
2. Reference Error: This happens when a non-existent variable is referenced. For
example, trying to use a variable that hasn’t been declared.
3. Type Error: This error is thrown when a value is not of the expected type. For example,
calling a non-function as if it were a function.
4. Range Error: This occurs when a value is not within the set or expected range. For
example, creating an array with an invalid length.
Handling Errors
1. try { }
Encloses code that might potentially cause an error
2. catch { }
Catch and handle any thrown Errors from try { }
3. finally { } ¯
(optional) Always executes.
used mostly for clean up.
ex. close files, close connections, release resources
example:
try{
console.log(x);
}
catch(error){
console.error(error);
}
finally {
// CLOSE FILES
// CLOSE CONNECTIONS
// RELEASE RESOURCES
console.log("This always executes");
}
console.log("You have reached the end")
/* output : ReferenceError: x is not defined
at practice.html:10:21
This always executes
You have reached the end
*/
4. throw : keyword is used to create a custom error. When you use throw , it stops the
execution of the current function and passes control to the nearest catch block in the
call stack. If no catch block is found, the program will terminate.
function checkNumber(num) {
if (typeof num !== 'number') {
throw new Error('Not a number!');
}
return num;
}
try {
checkNumber('abc');
} catch (e) {
console.error(e.message); // Outputs: Not a number!
}
DOM
The DOM (Document Object Model) is a structured representation of an HTML
document that the web browser creates when it loads a page. It’s like a tree of objects
where each element on the page (like a heading, paragraph, or button) is a node in this
tree.
JavaScript can interact with the DOM, allowing you to dynamically change the content,
structure, and style of a web page. This means you can add or remove elements,
modify text, change styles, and more—all without needing to reload the page.
Example:
Hello, World!
Click Me
In this example, clicking the button changes the text of the heading from "Hello, World!" to
"Hello, DOM!" using JavaScript to interact with the DOM.
Key Points:
DOM Structure: Elements are arranged in a tree-like structure.
Access: JavaScript can access and manipulate the DOM.
Dynamic Changes: You can modify content, structure, and styles dynamically.
This interaction between JavaScript and the DOM is what makes web pages dynamic and
interactive.
2. document.getElementsByClassName()
What it does: Selects all elements with a given class name.
Example:
let elements = document.getElementsByClassName('myClass');
elements[0].style.fontSize = '20px';
3. document.getElementsByTagName()
What it does: Selects all elements with a given tag name (like div , p , etc.).
Example:
let paragraphs = document.getElementsByTagName('p');
paragraphs[0].textContent = 'Updated paragraph text';
4. document.querySelector()
What it does: Selects the first element that matches a CSS selector.
Example:
let element = document.querySelector('.myClass'); // use . when using class
name
// let element = document.querySelector('h4'); //we can also use a tag name
element.style.backgroundColor = 'yellow';
5. document.querySelectorAll()
What it does: Selects ( by id, class or element) all elements that match a CSS selector.
and returns a Node list ( we use indexing to access each one )
A NodeList is a static collection of HTML elements obtained
using querySelectorAll() . It’s similar to an array, but it lacks methods
like map , filter , or reduce . Additionally, a NodeList won’t automatically update to
reflect changes in the DOM.
Example:
let elements = document.querySelectorAll('div');
elements.forEach(el => el.style.border = '1px solid black');
6. element.textContent
What it does: Gets or sets the text content of an element.
Example:
let heading = document.getElementById('heading');
heading.textContent = 'New Heading Text';
7. element.innerHTML
What it does: Gets or sets the HTML content of an element.
Example:
let div = document.getElementById('myDiv'); div.innerHTML = '
New paragraph inside the div
';`
8. element.style
What it does: Directly modifies the inline styles of an element.
Example:
let button = document.querySelector('button');
button.style.backgroundColor = 'green';
9. element.setAttribute()
What it does: Sets the value of an attribute on an element.
Example:
let img = document.querySelector('img');
img.setAttribute('alt', 'A descriptive text');
10. element.getAttribute()
What it does: Gets the value of an attribute from an element.
Example:
let link = document.querySelector('a');
let hrefValue = link.getAttribute('href');
11. element.classList.add()
What it does: Adds a class to an element.
Example:
let div = document.getElementById('myDiv');
div.classList.add('newClass');
12. element.classList.remove()
What it does: Removes a class from an element.
Example:
let div = document.getElementById('myDiv');
div.classList.remove('oldClass');
13. element.classList.toggle()
What it does: Toggles a class on or off.
Example:
let div = document.querySelector('div');
div.classList.toggle('highlight');
14. element.addEventListener()
What it does: Attaches an event listener to an element.
Example:
let button = document.querySelector('button');
button.addEventListener('click', function() { alert('Button clicked!');
});
15. element.remove()
What it does: Removes an element from the DOM.
Example:
let div = document.getElementById('myDiv');
div.remove();
16. document.createElement()
What it does: Creates a new element.
Example:
let newDiv = document.createElement('div');
newDiv.textContent = 'I am a new div!';
document.body.appendChild(newDiv);
17. element.appendChild()
What it does: Adds a new child element to a parent element.
Example:
let parent = document.getElementById('parentDiv');
let child = document.createElement('p');
child.textContent = 'New Child Element';
parent.appendChild(child);
18. element.insertBefore()
What it does: Inserts a new element before another specified element.
Example:
let parent = document.getElementById('parentDiv'); let newElement =
document.createElement('p'); newElement.textContent = 'Inserted Before!';
parent.insertBefore(newElement, parent.firstChild);
19. element.removeChild()
What it does: Removes a child element from a parent element.
Example:
let parent = document.getElementById('parentDiv');
let child = document.getElementById('childDiv');
parent.removeChild(child);
20. element.replaceChild()
What it does: Replaces a child element with a new element.
Example:
let parent = document.getElementById('parentDiv');
let newChild = document.createElement('p');
newChild.textContent = 'Replaced Child';
parent.replaceChild(newChild, parent.firstChild);
DOM navigation
1. firstElementChild :
Explanation: Returns the first child element of a specified element.
Example: If you have an element with an ID of “myDiv,” you can get its first child
element like this:
2. lastElementChild :
Explanation: Returns the last child element of a specified element.
Example: To get the last child element of a parent element with the class “myList,”
you can do:
const lastChild =
document.querySelector(".myList").lastElementChild;
3. nextElementSibling :
Explanation: Returns the next sibling element at the same tree level.
Example: If you have an element with the class “current,” you can get its next
sibling element like this:
const
nextSibling=document.querySelector(".current").nextElementSibling
;
4. previousElementSibling :
Explanation: Returns the previous sibling element at the same tree level.
Example: To find the previous sibling of an element with the ID “myLink,” you can
use:
javascript
constprevSibling=document.getElementById("myLink").previousElementSi
bling;
5. parentElement :
Explanation: Returns the parent element of a specified element.
Example: If you want to access the parent element of an element with the class
“childItem,” use:
const parent =
document.querySelector(".childItem").parentElement;
6. children :
Explanation: Returns a collection of child elements (excluding text and comment
nodes) of a specified element.
Example: To get all child elements of an element with the ID “myContainer,” you
can do:
const childElements =
document.getElementById("myContainer").children;
```
3. **Removing an Element:**
- If you want to remove an element, use `removeChild()`:
```javascript
document.getElementById("box").removeChild(newH1);
```
# Event Listeners
1. **Adding Multiple Event Handlers:** You can add multiple event handlers
to the same element without overwriting existing ones:
```javascript
const myElement = document.querySelector("#myElement");
myElement.addEventListener("click", myFunction);
myElement.addEventListener("mouseover", mySecondFunction);
// ... add more event handlers
```
4. **Using Named Functions:** You can also refer to an external named
function:
```javascript
function myFunction() {
console.log("Hello from myFunction!");
}
myElement.addEventListener("click", myFunction);
```
function myCustomFunction(message) {
console.log(message);
}
```
### Example Using an Image
Let’s create an example using an image. Suppose you have an image element
with the ID `"myImage"` and you want to change its source when clicked:
1. **HTML:**
```html
<img id="myImage" src="initial-image.jpg" alt="My Image">
<button id="changeImage">Change Image</button>
```
```javascript
const imageElement = document.querySelector("#myImage");
const buttonElement = document.querySelector("#changeImage");
buttonElement.addEventListener("click", () => {
imageElement.src = "new-image.jpg";
});
```
## Common Events
# 1. **Mouse Events**:
```javascript
document.getElementById("myButton").addEventListener("click",
function() {
console.log("Button clicked!");
});
```
```javascript
document.getElementById("myElement").addEventListener("dblclick",
function() {
console.log("Double-clicked!");
});
```
```javascript
document.getElementById("myDiv").addEventListener("mouseover",
function() {
console.log("Mouse over the div!");
});
```
D. **`mouseout`**: Triggers when the mouse leaves an element. Example:
```javascript
document.getElementById("myLink").addEventListener("mouseout",
function() {
console.log("Mouse left the link!");
});
```
```javascript
document.addEventListener("mousemove", function(event) {
console.log(`Mouse position: X=${event.clientX},
Y=${event.clientY}`);
});
```
# 2. **Keyboard Events**:
==Note: - `event.key`: Returns the character that has been pressed (e.g.,
‘z’ for the ‘z’ key).==
==- `event.code`: Returns the physical key code (e.g., ‘KeyZ’ for the
‘z’ key).==
```javascript
document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});
```
```javascript
document.addEventListener("keyup", function(event) {
console.log(`Key released: ${event.key}`);
});
```
==// USE KEYDOWN INSTEAD OF KEYPRESS==
C. **Keypress Event**:
- The `keypress` event occurs when the user presses a key that produces a
character value. These include keys such as alphabetic, numeric, and
punctuation keys.
- Modifier keys like ‘Shift’, ‘CapsLock’, and ‘Ctrl’ do not produce a
character value, so they do not trigger a keypress event].
example:
```javascript
document.addEventListener("keypress", () =>
console.log(event.key));
```
# 3. **Submit Event**:
```javascript
const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent actual form submission
// Process form data here
});
```
# 4. **Load Event**:
- Fires when an element (e.g., an image or entire page) finishes loading.
- Example: Execute code after the page has loaded:
```javascript
window.addEventListener("load", function() {
console.log("Page loaded!");
});
```
# **Callback hell**
refers to the situation in JavaScript where multiple nested callbacks
create complex, deeply indented code, often called the “pyramid of doom.”
This structure makes the code difficult to read, debug, and maintain,
resulting in poor code quality and scalability issues.
```javascript
function firstTask(callback) {
setTimeout(() => {
console.log('First Task');
callback();
}, 1000);
}
function secondTask(callback) {
setTimeout(() => {
console.log('Second Task');
callback();
}, 1000);
}
function thirdTask(callback) {
setTimeout(() => {
console.log('Third Task');
callback();
}, 1000);
}
In this example:
Each task is executed after the previous one completes, leading to deeply nested
callbacks.
This structure can quickly become unmanageable as more tasks are added.
To avoid callback hell, you can use Promises or async/await syntax, which makes
the code more readable and easier to maintain.
Promises in JavaScript
A Promise is an object representing the eventual completion or failure of an asynchronous
operation. It allows you to write asynchronous code in a more synchronous fashion, making
it easier to handle asynchronous operations.
States of a Promise:
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed!");
}
});
In this example:
Promise Chaining
When you want to perform a series of asynchronous tasks one after another, you can
chain .then() calls.
You can handle errors in a promise chain using .catch() . If any promise in the chain is
rejected, the control jumps to the nearest .catch() .
more example
Promise.all()
Is a static method that takes an iterable (such as an array) of promises as input and
returns a single promise. This returned promise resolves when all of the input
promises have resolved, or it rejects if any of the input promises reject.
When you use Promise.all() , it returns a single promise that resolves to an array
containing the resolved values of all the input promises, in the same order as they were
passed in.
getData();
In this example:
General Example
//creating a Promise
task1
.then((message) => {
console.log(message);
return task2;
})
.then((message) => {
console.log(message);
return task3;
})
.then((message) => {
console.log(message);
return task4;
})
.then((message) => {
console.log(message);
});
//using Promise.all
Promise.all([task1,
task2,task3,task4]).then((messages)=>console.log(messages));
JSON.parse()
fetch()
Used for making HTTP requests to fetch resources such as JSON data, images, or
files. It simplifies asynchronous data fetching and is commonly used for interacting with
APIs.
It initiates a network request and returns a promise that resolves to
the Response object representing the response to that request.
Example:
// GET request
fetch('https://api.example.com/data')
.then(response => response.json()) // Parses JSON response into a JS
object
.then(data => console.log(data)) // Use the data
.catch(error => console.error('Error:', error));
// POST request
const data = { name: "Alice", age: 25 };
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // Convert JS object to JSON string
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Explanation:
GET request:
fetch('https://api.example.com/data') initiates a GET request to the
specified URL.
.then(response => response.json()) parses the JSON response into a
JavaScript object.
.then(data => console.log(data)) handles the parsed data.
.catch(error => console.error('Error:', error)) catches and logs any
errors.
POST request:
fetch('https://api.example.com/data', { method: 'POST', headers: {
'Content-Type': 'application/json' }, body: JSON.stringify(data)
}) initiates a POST request with the specified options.
The body contains the JSON stringified data to be sent.
The rest of the .then and .catch methods handle the response and errors
similarly to the GET request.
.json()
A method of the Response object that parses the JSON response into a JavaScript object.
Example:
fetch('https://api.example.com/data')
.then(response => response.json()) // Parses JSON response
.then(data => console.log(data)) // Use the data
.catch(error => console.error('Error:', error));
Explanation: