Java Script CompleteNotes
Java Script CompleteNotes
JavaScript
Create Your Code Masterpiece for Web Development Success
WHAT IS JAVASCRIPT ?
JavaScript is a programming language for making websites interactive. It
works alongside HTML and CSS, adding dynamic features like form validation and
updating content. It's versatile and widely used for web development.
JavaScript History :
JavaScript was invented by Brendan Eich in 1995. a Netscape programmer
developed a new scripting language in just 10 days. It was originally named Mocha,
but quickly became known as LiveScript and, later, JavaScript.
Timeline of JavaScript :
pg. 1
2
pg. 2
3
//javascript code
</script>
Example :
<script>
function count(){
counter++;
console.log(counter);
}
3.External JavaScript :
External javascript is mainly used for it's reusablility nature. In external
javascript we write the javascript code in a seperate file and will include to the
necessary html document
Syntax :
<script src = "path"> </script>
Example :
<script src = "../javascript/filename.js"></script>
NOTE : To link the CSS file we use the link tag though, for Javascript we use the
script
pg. 3
4
/*
multiple lines of comments
*/
Variables in Javascript:
Variables are containers which will store values inside them temporily. To
name a variable we need to follow some rules.
Rules :
1. Declare the variable :
We have the declare a variable 1st inorder to access it.
We are having the 3 types of declarations.
a. let - can change based on value/ data
b. const - can't change value in the entire the program
c. Var - Var is similar to let but it is functional level variable.
NOTE : We use the let instead of var as it is more flexiable and will not allow
any leakages that will happen with var.
Syntax :
declarationTyle varName;
Note : VarName should be unique, We cannot declare the same variable twice.
Datatypes in javascript :
Datatypes represents the type of data we are storing inside the variable.
JavaScript has several built-in data types that are used to represent different kinds of
values. Here are the main data types in JavaScript:
1. **Primitive Data Types:**
- **Undefined:** Represents an uninitialized or undefined value.
pg. 5
6
Syntax :
let undefinedVar;
console.log(undefinedVar); // Output: undefined
- **Null:** Represents the absence of any object value.
Syntax :
let nullVar = null;
console.log(nullVar); // Output: null
- **Boolean:** Represents a logical entity and can have two values: `true`
or `false`.
Syntax :
let isTrue = true;
console.log(isTrue); // Output: true
pg. 6
7
2. **Object:**
- **Object:** A compound data type that allows you to group related data
and functions together.
Example :
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
isStudent: false,
};
3. **Special Objects:**
- **Function:** A subtype of objects that is callable as a function.
Example :
function add(a, b) {
return a + b;
}
pg. 7
8
pg. 8
9
Operators in javascript :
We use the operators in javascript to perform specific operations with the help
of operators. In javascript we are having 7 operators.
Here are some of the key types of operators in JavaScript:
1. **Arithmetic Operators:**
- `+` (Addition)
- `-` (Subtraction)
- `*` (Multiplication)
- `/` (Division)
- `%` (Modulus - remainder of division)
Example :
let a = 5;
let b = 2;
console.log(a + b); // Output: 7
2. **Assignment Operators:**
- `=` (Assignment)
- `+=`, `-=`, `*=`, `/=` (Compound assignment)
Example :
pg. 9
10
let x = 10;
x += 5; // Equivalent to x = x + 5;
3. **Comparison Operators:**
- `==` (Equality, loose equality)
- `===` (Strict equality)
- `!=` (Inequality, loose inequality)
- `!==` (Strict inequality)
- `>`, `<`, `>=`, `<=` (Greater than, Less than, Greater than or equal, Less
than or equal)
Example :
let num1 = 5;
let num2 = '5';
console.log(num1 == num2); // Output: true (loose equality)
console.log(num1 === num2); // Output: false (strict equality)
4. **Logical Operators:**
- `&&` (Logical AND)
- `||` (Logical OR)
- `!` (Logical NOT)
Example :
let isTrue = true;
let isFalse = false;
console.log(isTrue && isFalse); // Output: false (logical AND)
console.log(isTrue || isFalse); // Output: true (logical OR)
console.log(!isTrue); // Output: false (logical NOT)
5. **Increment/Decrement Operators:**
pg. 10
11
- `++` (Increment)
- `--` (Decrement)
Example :
let count = 10;
count++;
6. **Concatenation Operator:**
- `+` (String concatenation)
Example :
let str1 = 'Hello';
let str2 = 'World';
let greeting = str1 + ' ' + str2; // Output: 'Hello World'
7. **Conditional (Ternary) Operator:**
- `condition ? expr1 : expr2`;
Example :
let age = 20;
let message = (age >= 18) ? 'Adult' : 'Minor';
Type Converstion :
Type converstion is used to convert a value from one datatype to another.
- To type convert we need to use the datatype before the value inorder to change it's
datatype. We use the below function inorder to change the datatype
Number( ) - to convert into number
String( ) - to convert into String
Boolean( ) - to convert into Boolean
Syntax :
varName = dataType( varName/ value);
Example :
let a = '2'; // String
a = Number(a); // converting from String to Number
NOTE : if we are trying to convert any variable which is not initialized then it will
convert them using the default values.
1. NaN - not a number > for nuber
2. undefined - > for values which are not defined
pg. 12
13
Conditional Statments :
Conditional statements in JavaScript are used to make decisions in your code
based on certain conditions. The most common conditional statements in JavaScript
are:
1. **if statement:**
The `if` statement is used to execute a block of code if a specified
condition evaluates to true.
Syntax :
if (condition) {
// code to be executed if the condition is true
}
2. **if-else statement:**
pg. 14
15
The `if-else` statement allows you to execute one block of code if the
condition is true and another block if the condition is false.
Syntax :
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
3. **if-else if-else statement:**
You can use multiple conditions with the `if-else if-else` statement to
check for different cases.
Syntax :
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
4. **switch statement:**
The `switch` statement is useful when you have multiple possible
conditions to check. It's an alternative to using multiple `if-else if` statements.
Syntax :
switch (expression) {
case value1:
// code to be executed if expression matches value1
pg. 15
16
break;
case value2:
// code to be executed if expression matches value2
break;
// ... more cases
default:
// code to be executed if expression doesn't match any case
}
Strings in javaScript :
In JavaScript, strings are sequences of characters, such as text, and they are
used to represent and manipulate textual data. Strings can be created using single or
double quotes, and there are various methods available to perform operations on
strings. Here are some basics about strings in JavaScript:
### Creating Strings:
You can create strings using single or double quotes:
Example :
let singleQuotedString = 'This is a single-quoted string.';
let doubleQuotedString = "This is a double-quoted string.";
Both single and double quotes are acceptable, and you can use them
interchangeably. This flexibility can be useful in certain situations.
### String Concatenation:
You can concatenate (combine) strings using the `+` operator:
Example :
let firstName = "John";
let lastName = "Doe";
pg. 16
17
pg. 17
18
Example :
let a = "Hello";
console.log(a.repeat(5)); // "HelloHelloHelloHelloHello"
- startsWith() and endsWith() :
Used to check where the string starts/end with the give info or not.
Example :
let varname = "String";
varname.startsWith('D'); // false
varname.endsWith('h'); //true
-includes():
The includes() method is a built-in method of the JavaScript String and
Array objects. It is used to check whether a particular value (substring for
strings or element for arrays) is present in the given string or array.
Example :
let text = "Hello, World!";
// Check if the string includes a specific substring
let containsHello = text.includes("Hello");
console.log(containsHello); // Output: true
let containsFoo = text.includes("Foo");
console.log(containsFoo); // Output: false
-replaceAll() :
It is used to replace all occurrences of a specified substring or regular
expression with another string. This method is an improvement over the older
replace() method, which only replaced the first occurrence by default.
Example :
let originalString = "Hello, World! Hello, Universe!";
pg. 19
20
Loops in javaScript :
In JavaScript, loops are used to execute a block of code repeatedly until a
specified condition is met. There are several types of loops in JavaScript, each
serving different purposes. Here are the main types of loops:
### 1. `for` Loop:
The `for` loop is commonly used when the number of iterations is known in
advance.
Syntax :
for (initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0, 1, 2, 3, 4
}
### 2. `while` Loop:
pg. 21
22
The `while` loop is used when you want to execute a block of code as long as
a specified condition is true.
Syntax :
while (condition) {
// code to be executed as long as the condition is true
}
Example:
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}
### 3. `do-while` Loop:
The `do-while` loop is similar to the `while` loop, but it ensures that the block
of code is executed at least once before checking the condition.
Syntax :
do {
// code to be executed
} while (condition);
Example:
let i = 0;
do {
console.log(i); // Output: 0 (even though the condition is false)
i++;
} while (i < 0);
pg. 22
23
Function :
Functions in JavaScript are blocks of reusable code that can be defined and
called to perform a specific task. Functions help organize code, promote reusability,
pg. 23
24
and make it easier to maintain and debug programs. Here's an overview of how
functions work in JavaScript:
### 1. Function Declaration:
You can declare a function using the `function` keyword, followed by the
function name, a list of parameters (if any), and the code block.
Example :
function greet(name) {
console.log("Hello, " + name + "!");
}
// Call the function
greet("John"); // Output: Hello, John!
### 2. Function Expression:
You can also define a function using a function expression, where the function
is assigned to a variable.
Example :
let greet = function(name) {
console.log("Hello, " + name + "!");
};
// Call the function
greet("Jane"); // Output: Hello, Jane!
function example() {
let localVar = "I am a local variable";
console.log(localVar);
}
example(); // Output: I am a local variable
// console.log(localVar); // This would result in an error
### 7. Function Invocation:
Functions can be invoked (called) in various ways, including as standalone
functions, as methods of objects, or using the `call()` and `apply()` methods.
Example :
// Standalone function
function sayHello() {
console.log("Hello!");
}
sayHello(); // Output: Hello!
// Function as a method
let obj = {
greet: function() {
console.log("Greetings!");
}
};
obj.greet(); // Output: Greetings!
Arrays :
pg. 26
27
In JavaScript, an array is a data structure that allows you to store and organize
multiple values in a single variable. Arrays can hold elements of any data type,
including numbers, strings, objects, and other arrays. The elements in an array are
indexed starting from 0, and you can access them using square brackets.
### Creating Arrays:
Arrays can be created using the `Array` constructor or using array literals.
#### Using Array Literals:
Example :
// Array of numbers
let numbers = [1, 2, 3, 4, 5];
// Array of strings
let fruits = ["Apple", "Banana", "Orange"];
// Array of mixed data types
let mixedArray = [1, "two", true, { key: "value" }];
### Accessing Elements:
You can access elements in an array using their index. Remember that array
indices start from 0.
Example :
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
### Modifying Elements:
You can modify elements in an array by assigning new values to specific
indices.
Example :
let numbers = [1, 2, 3, 4, 5];
pg. 27
28
numbers[2] = 10;
console.log(numbers); // Output: [1, 2, 10, 4, 5]
### Array Methods:
JavaScript provides a variety of built-in methods for working with arrays.
Here are a few examples:
#### a. `push()` and `pop()`:
Example :
let numbers = [1, 2, 3];
numbers.push(4); // Add an element to the end
console.log(numbers); // Output: [1, 2, 3, 4]
let poppedElement = numbers.pop(); // Remove and return the last
element
console.log(numbers); // Output: [1, 2, 3]
console.log(poppedElement); // Output: 4
#### b. `shift()` and `unshift()`:
Example :
let fruits = ["Banana", "Orange", "Apple"];
fruits.shift(); // Remove the first element
console.log(fruits); // Output: ["Orange", "Apple"]
fruits.unshift("Mango"); // Add an element to the beginning
console.log(fruits); // Output: ["Mango", "Orange", "Apple"]
#### c. `slice()`:
Example :
let numbers = [1, 2, 3, 4, 5];
let slicedArray = numbers.slice(1, 4); // Extract elements from index 1 to
3 (not including 4)
pg. 28
29
Map() :
pg. 29
30
.filter() :
In JavaScript, you can use the `filter` method to create a new array with
elements that pass a certain condition. The `filter` method is available for arrays and
takes a callback function as its argument. This callback function is applied to each
element of the array, and if the function returns `true`, the element is included in the
new array; otherwise, it is excluded.
Syntax :
const newArray = originalArray.filter(function(element, index, array) {
// Your filtering condition goes here
// Return true if the element should be included in the new array, false
otherwise
});
// or using arrow function for a more concise syntax:
const newArray = originalArray.filter((element, index, array) => {
// Your filtering condition goes here
// Return true if the element should be included in the new array, false
otherwise
});
Explanation:
- `originalArray`: The array you want to filter.
- `element`: The current element being processed in the array.
- `index`: The index of the current element in the array.
- `array`: The array being processed.
Inside the callback function, you provide the condition that determines
whether an element should be included in the new array. If the condition is met
pg. 31
32
Reduce() :
In JavaScript, the `reduce` method is used to reduce an array to a single value.
It takes a callback function as its argument, which is applied to each element of the
array in sequence to accumulate a result.
Syntax :
const result = array.reduce(function(accumulator, currentValue, currentIndex,
array) {
// Your reduction logic goes here
pg. 32
33
Spread Operator :
It is used to unpack the arrays. The spread operator is represented by '...'
infront of variable, the spread operator (...) is a versatile syntax that allows you to
expand elements of an array or properties of an object. It is commonly used for
creating shallow copies of arrays and objects, merging arrays, and passing function
arguments.
Syntax :
...arrayName;
pg. 33
34
Example :
let originalArray = [1, 2, 3];
let copyArray = [...originalArray];
console.log(copyArray); // Output: [1, 2, 3]
Rest Parameters :
In JavaScript, the rest parameter, denoted by the ellipsis (`...`) followed by a
parameter name, allows a function to accept any number of arguments as an array.
The rest parameter collects the remaining arguments into a single array, making it
useful when you want to work with a variable number of parameters.
Here's an example of using the rest parameter in a function:
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
console.log(sum(10, 20, 30)); // Output: 60
In this example, the `...numbers` rest parameter collects all the arguments
passed to the `sum` function into an array called `numbers`. The `reduce` method is
then used to calculate the sum of the numbers in the array.
### Destructuring with Rest:
You can also use the rest parameter in destructuring, which allows you to
extract some elements from an array and collect the remaining elements in a
separate array.
Example :
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // Output: 1
console.log(second); // Output: 2
pg. 34
35
Callback :
callback function is a function that is passed as an argument to another
function and is executed after some operation has been completed.
Syntax :
function functionName( callback ){
// function body
callback(); // calls the next method
}
Example :
function greeting(callback){
pg. 35
36
Function Expression :
In JavaScript, a function expression is a way to define a function using an
expression. Unlike function declarations, which are hoisted to the top of their
containing scope, function expressions are not hoisted. This means that you need to
define a function expression before you can use it in your code.
Syntax :
const myFunction = function(parameters) {
// Function body
// Code goes here
return result; // Optional
};
- `const myFunction`: Defines a constant variable named `myFunction` that holds
the function.
pg. 36
37
Example :
const multiply = (a, b) => a * b;
console.log(multiply(2, 3)); // Output: 6
Arrow Functions :
Arrow functions are a concise way to write function expressions in JavaScript.
They were introduced with ES6 (ECMAScript 2015) and provide a more compact
syntax compared to traditional function expressions. Arrow functions are especially
useful for short, one-line functions.
Syntax :
const myFunction = (parameter1, parameter2, ...) => {
// Function body
// Code goes here
pg. 37
38
SetTimeOut :
In JavaScript, the `setTimeout()` function is used to schedule the execution of
a function or the evaluation of an expression after a specified amount of time has
passed. It allows you to introduce a delay in the execution of code, making it useful
for scenarios like animations, asynchronous operations, or creating timed events.
Syntax :
setTimeout(callback, delay, param1, param2, ...);
pg. 38
39
pg. 39
40
Example :
function greet(name) {
console.log("Hello, " + name + "!");
}
setTimeout(greet, 1000, "John"); // Execute greet("John") after 1000
milliseconds (1 second)
### Clearing Timeout:
The `setTimeout()` function returns a timer ID that can be used to cancel the
execution of the scheduled function using the `clearTimeout()` function:
Example :
let timerId = setTimeout(function() {
console.log("This won't be executed");
}, 5000);
// Cancel the scheduled execution
clearTimeout(timerId);
Objects :
In JavaScript, objects are a fundamental data type that allows you to group
related data and functions together. Objects are instances of classes, but JavaScript
uses a prototype-based inheritance model, which means objects can be created
directly without the need for class definitions.
Syntax :
// Object literal syntax
const myObject = {
key1: value1,
key2: value2,
pg. 40
41
- The `hobbies` property is an array, and the `address` property is another object
nested within the `person` object.
- The `sayHello` property is a method (function) attached to the `person` object.
You can access object properties using dot notation (`objectName.propertyName`)
or bracket notation (`objectName["propertyName"]`). The latter is particularly
useful when the property name contains special characters or spaces.
Example :
console.log(person["age"]); // Output: 30
You can also add, modify, or delete properties of an object dynamically:
Example :
person.gender = "Male"; // Adding a new property
person.age = 31; // Modifying an existing property
delete person["address"]; // Deleting a property
Note : The function inside the objects are called as methods.
NOTE : We can use the nested objects and also arrays in object
Array of objects :
An array of objects is a common data structure in JavaScript where each
element of the array is an object. Each object in the array can have its own set of
properties and values.
Example :
// Array of objects representing people
const people = [
{ firstName: 'John', lastName: 'Doe', age: 30 },
pg. 42
43
Constructors :
In JavaScript, a constructor is a special type of function used to create and
initialize objects. Constructors are typically used in conjunction with the `new`
keyword to create instances of a particular type or class of objects. When a function
is used as a constructor, it is intended to be called with the `new` keyword, and it is
responsible for initializing the properties and methods of the new object.
Syntax :
pg. 43
44
function fName(parameters...);{
this.value = value;
//n -values
}
Example :
function Person(name, age) {
this.name = name;
this.age = age;
}
// Creating an instance of Person
const john = new Person("John", 30);
console.log(john.name); // Output: John
console.log(john.age); // Output: 30
In this example:
- `Person` is a constructor function.
- The `new` keyword is used to create a new instance of `Person`.
- Inside the `Person` constructor, `this` refers to the newly created object, and
properties (`name` and `age`) are assigned to it.
Constructors are often used to define classes in JavaScript, even though JavaScript
itself doesn't have a native class system like some other programming languages.
You can add methods to the constructor's prototype to share them among all
instances created with the constructor.
Example :
function Person(name, age) {
this.name = name;
this.age = age;
pg. 44
45
}
// Adding a method to the prototype
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years
old.`);
};
const john = new Person("John", 30);
john.sayHello(); // Output: Hello, my name is John and I'm 30 years old.
Classes :
Classes provides a more convenient way to define constructor functions and
work with prototypes. Although JavaScript's class syntax resembles that of other
programming languages, it's important to understand that JavaScript's classes are
essentially syntactic sugar over the existing prototype-based inheritance model.
Syntax :
class className{
constructor(){
//constructor Code
}
methodName(){
//Method Code
}
}
Example :
class Person {
constructor(name, age) {
pg. 45
46
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age}
years old.`);
}
}
Static :
In JavaScript, the `static` keyword is used in the context of classes to define
static methods or static properties. Static members are associated with the class
itself, rather than with instances of the class. They are called on the class rather than
on instances of the class.
Here's how you can use the `static` keyword with classes:
### Static Methods:
pg. 46
47
Example :
class MathOperations {
static add(x, y) {
return x + y;
}
static subtract(x, y) {
return x - y;
}
}
// Calling static methods without creating an instance
console.log(MathOperations.add(5, 3)); // Output: 8
console.log(MathOperations.subtract(10, 4)); // Output: 6
In this example, `add` and `subtract` are static methods of the
`MathOperations` class. You can call these methods directly on the class itself
without creating an instance of the class.
Inheritance ;
In JavaScript, inheritance is achieved through prototype-based inheritance.
While the introduction of the `class` syntax in ECMAScript 2015 (ES6) made
working with inheritance more familiar to developers coming from class-based
languages, it's essential to understand that JavaScript's inheritance is based on
prototypes.
Example :
//Animal Constructor
function Animal(){
console.log("animal");
pg. 47
48
}
// adding animalName method to Animal constructor
Animal.prototype.animalName = (name) => {
console.log(name);
}
// child constructor
function Dog(){
console.log("Dog");
}
//creating inheritance from Animal to Dog
Dog.prototype = Object.create(Animal.prototype);
// creating instance of Dog Constructor
const dog = new Dog();
//accessing the parent function
dog.animalName("max");
In this example:
- `Animal` is the parent constructor function, and we add a method `makeSound` to
its prototype.
- `Dog` is the child constructor function, and it calls the `Animal` constructor using
`Animal.call(this, name)` to initialize the common properties.
- `Dog.prototype` is set to an instance of `Animal.prototype` using
`Object.create(Animal.prototype)`, establishing the prototype chain.
Instances of `Dog` inherit the properties and methods of both `Dog` and `Animal`.
With the introduction of the `class` syntax in ES6, achieving inheritance is more
concise:
Example :
pg. 48
49
Super :
In JavaScript, the `super` keyword is used in the context of classes, and it serves
two main purposes:
1. **Accessing the Parent Class:**
pg. 49
50
pg. 50
51
- `super` is also used to call methods from the prototype of the parent class. This
is particularly useful when a method with the same name exists in both the parent
and subclass, and you want to specifically call the method from the parent class.
Example :
class Animal {
makeSound() {
console.log("Some generic sound");
}
}
class Dog extends Animal {
makeSound() {
// Call the makeSound method from the parent class
super.makeSound();
console.log("Woof!");
}
}
const myDog = new Dog();
myDog.makeSound();
// Output:
// Some generic sound
// Woof!
NOTE : If you want to use the parent properties or values 1st you need to call the
parent constructor using the super();
TIP : We can send the parameters to the super() if you want to.
pg. 51
52
pg. 52
53
Destructuring :
Is used to extract the values from objects or arrays to assign them to variable
individually.
1. [] - used to destructure array
2.{} - used to destructure object
### Array Destructuring:
Example :
const numbers = [1, 2, 3, 4, 5];
// Destructuring assignment
const [first, second, , fourth] = numbers;
console.log(first); // Outputs: 1
pg. 53
54
console.log(second); // Outputs: 2
console.log(fourth); // Outputs: 4
### Object Destructuring:
Example :
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
// Destructuring assignment
const { firstName, lastName, age } = person;
console.log(firstName); // Outputs: John
console.log(lastName); // Outputs: Doe
console.log(age); // Outputs: 30
### Renaming Variables during Destructuring:
Example :
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
// Destructuring assignment with variable renaming
const { firstName: fName, lastName: lName, age: personAge } =
person;
console.log(fName); // Outputs: John
pg. 54
55
pg. 55
56
Modules :
ES6 (ECMAScript 2015) introduced the concept of modules to JavaScript.
Modules provide a way to organize code into reusable units and encapsulate the
implementation details. The module system helps in creating a more maintainable
and scalable codebase. Here is a basic overview of ES6 modules:
### Exporting from a Module:
To export variables, functions, or classes from a module, you use the `export`
keyword:
Example :
// myModule.js
export const myVariable = 42;
export function myFunction() {
// function implementation
}
export class MyClass {
// class implementation
}
pg. 56
57
pg. 58
59
### Synchronous:
In a sequential and blocking manner. In a synchronous process, each operation
must complete before the next one starts. This means that if there is a delay in any
operation, it will block the execution of subsequent operations until the current one
finishes.
pg. 59
60
### Asynchronous:
Allow multiple operations to overlap in time. In an asynchronous process, a
task can start without waiting for the previous one to complete. Asynchronous
operations are commonly used in situations where there may be delays, such as
fetching data from a remote server or reading a file.
pg. 60
61
In this asynchronous example, "Step 1" and "Step 3" are executed
immediately, and "Step 2" is executed later when the asynchronous `fetchData`
operation completes.
Asynchronous operations are often used to improve the efficiency and
responsiveness of programs, especially in scenarios where waiting for a task to
complete would result in unnecessary delays.
In modern JavaScript, asynchronous operations are commonly handled using
features like Promises, async/await, and callback functions. These mechanisms
allow developers to work with asynchronous code in a more organized and readable
manner.
Error Handling :
Error handling is a critical aspect of writing robust and reliable software.
Properly managing errors ensures that your program can gracefully handle
unexpected situations, recover from failures, and provide meaningful feedback to
users or developers. Here are some common approaches to error handling in
programming:
1. **Try-Catch Blocks:**
In languages like JavaScript, Java, and Python, you can use `try-catch` blocks to
handle exceptions (errors). Code within the `try` block is executed, and if an
exception occurs, the corresponding `catch` block is executed.
Example :
try {
// Code that may throw an exception
} catch (error) {
// Handle the exception
console.error("An error occurred:", error.message);
}
2. **Error Objects:**
pg. 61
62
When an error occurs, it's often represented by an object that contains information
about the error, such as an error message and a stack trace. This object can be
caught and used for further analysis or logging.
Example :
try {
// Code that may throw an exception
} catch (error) {
if (error instanceof SomeSpecificError) {
// Handle a specific type of error
} else {
// Handle other types of errors
console.error("An error occurred:", error.message);
}
}
3. **Throwing Errors:**
You can throw your own custom errors or exceptions using the `throw` keyword.
This is useful for signaling specific issues in your code.
Example :
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
4. **Promises and Async/Await:**
pg. 62
63
When working with asynchronous code, error handling is often done using
Promises and the `catch` method, or with `async/await` syntax.
Example :
someAsyncFunction()
.then(result => {
// Handle success
})
.catch(error => {
// Handle errors
console.error("An error occurred:", error.message);
});
//javascript
async function someAsyncFunction() {
try {
const result = await fetchSomething();
// Handle success
} catch (error) {
// Handle errors
console.error("An error occurred:", error.message);
}
}
5. **Logging:**
Logging errors is crucial for troubleshooting and debugging. Log error
details, including the error message, stack trace, and any relevant context, to help
identify and fix issues.
Example :
pg. 63
64
try {
// Code that may throw an exception
} catch (error) {
// Log the error
console.error("An error occurred:", error);
}
6. **Graceful Degradation:**
In situations where an error won't cause a critical failure, you may choose to
gracefully degrade the functionality or provide a fallback mechanism.
Example :
try {
// Code that may throw an exception
} catch (error) {
// Use a fallback or provide a degraded functionality
console.warn("An error occurred, using fallback:", error.message);
}
DOM :
The Document Object Model (DOM) is a programming interface for web
documents. It represents the structure of a document as a tree of objects, where each
object corresponds to a part of the document, such as elements, attributes, text
content, etc. The DOM provides a way for programs to manipulate the structure,
style, and content of web documents.
Here's a detailed explanation of key concepts related to the DOM:
pg. 64
65
pg. 68
69
pg. 69
70
first element that matches the specified selector, or `null` if no matching element is
found.
This method takes a CSS selector as an argument and returns the first element in the
document that matches the selector.
#### Example:
<!-- HTML: -->
<div id="myDiv">Hello, World!</div>
<p class="paragraph">This is a paragraph.</p>
// JavaScript:
const myDiv = document.querySelector('#myDiv'); // Selects element
with ID 'myDiv'
const firstParagraph = document.querySelector('.paragraph'); // Selects
first element with class 'paragraph'
console.log(myDiv.textContent); // Outputs: Hello, World!
console.log(firstParagraph.textContent); // Outputs: This is a paragraph.
In this example, `querySelector('#myDiv')` selects the element with the ID 'myDiv',
and `querySelector('.paragraph')` selects the first element with the class 'paragraph'.
### Additional Notes:
- The `querySelector` method allows you to use any valid CSS selector, providing
great flexibility.
- If you want to select multiple elements that match a selector, you can use
`querySelectorAll()`.
- It's a good practice to check if the selected element is not `null` before attempting
to access its properties or call its methods.
#### Example:
const element = document.querySelector('.someClass');
if (element) {
pg. 70
71
DOM Navigation :
DOM (Document Object Model) navigation involves moving around and
accessing different parts of the document tree. In JavaScript, you can navigate the
DOM using various properties and methods provided by the DOM API. Here are
some common methods for DOM navigation:
### 1. **Parent Node:**
- The `parentNode` property is used to get the parent node of an element. We can
also use the parentElement property as well
Syntax :
const childElement = document.getElementById('childElementId');
const parentElement = childElement.parentNode;
const parent = childElement.parentElement;
Example :
const parent = p1.parentNode;
pg. 72
73
p1.textContent = 'para1';
#### 2. **Append the Element to the DOM:**
// Append the new paragraph to the body of the document
Syntax :
pg. 73
74
document.body.appendChild(newElement);
Example :
div.appendChild(p1);
4. **InsertBefore : **
Insert the element before the selected element.
Syntax :
Parent.insertBefore( insertElement, referenceElement);
Example :
div.insertBefore(p4, div.lastChild);
imageElement.setAttribute('src', 'newImagePath.jpg');
#### 4. **Change CSS Style:**
// Change the background color of an existing element
existingElement.style.backgroundColor = 'lightblue';
We can create a complete HTML structure using the js but we need to have the
basic structure of html page. For that we need to follow this procedure.
1. Create a element using "createElement"
2. Edit the element using the "textContent" and also provide Id by using the
".id", for class using ".class"
3. Then append or prepend the element to the HTML document using the
"append" or "prepend". You can even select where you want to insert using
the "insertBefore"
Example :
document.body.insertBefore( createdTag, Target);
4. To remove a created element or existing element, then use the remove
child.
Example :
document.body.removeChild(target);
Event Listeners :
In JavaScript, event listeners are used to detect and respond to events that
occur in the browser, such as user interactions (e.g., clicks, keypresses) or changes
in the DOM (Document Object Model). Event listeners are commonly used to add
interactivity to web pages. Here's a basic overview of how event listeners work:
1. **Event Types:**
- Common events include "click," "mouseover," "keydown," "submit," etc.
- Choose the appropriate event type based on the action you want to capture.
pg. 75
76
2. **Event Target:**
- The event target is the DOM element on which the event occurs.
- It could be the entire document, a specific HTML element, or any other
valid DOM element.
3. **Event Listener:**
- An event listener is a function that is called whenever a specified event
type occurs on a specified target.
- You attach an event listener to an element using the `addEventListener`
method.
**Syntax:**
target.addEventListener(type, listenerFunction);
- `target`: The DOM element to which the event listener is attached.
- `type`: A string representing the event type (e.g., "click," "keydown").
- `listenerFunction`: The function that will be called when the event
occurs.
**Example:**
// HTML:
<button id="myButton">Click me</button>
In this example, the `handleClick` function will be called when the button
with the id "myButton" is clicked.
6. **Removing Event Listeners:**
- You can remove an event listener using the `removeEventListener`
method.
- It's important to use the same function reference that was used during the
`addEventListener` call.
Example :
button.removeEventListener('click', handleClick);
pg. 76
77
7. **Event Object:**
- The event listener function typically receives an event object as a
parameter.
- This object contains information about the event, such as the type, target,
and additional data depending on the event type.
Example :
function handleClick(event) {
console.log('Button clicked!', event);
}
Event object will have a method called matches which is used to match the
selectors like id, class and tags.
Example :
event.target.matches('#parent')
Node List :
A node list is an array-like collection of nodes. Nodes typically represent
elements in the Document Object Model (DOM), which is a hierarchical
representation of the structure of an HTML or XML document. Node lists are
commonly used when selecting multiple elements from the DOM using methods
like querySelectorAll or properties like childNodes.
NOTE : Node lists will not have any built in methods like map and filter or reduce.
But will have foreach loop
Note : Node list will not automatically reflect the changes for that we need to apply
the changes seperately as these are static collection.
Example :
//HTML code
pg. 78
79
Class List :
In JavaScript, the `classList` property is used to interact with the classes of an
HTML element. It provides a convenient way to add, remove, toggle, and check for
the presence of CSS classes on an element. The `classList` property is available on
all elements in the DOM.
Here are some common methods and properties of the `classList` object:
1. **`add(className1, className2, ...)` method:**
Adds one or more class names to the element. If the class already exists, it
will not be duplicated.
Example :
pg. 79
80
Using the `classList` methods, you can easily manipulate the classes of HTML
elements, which is commonly done in dynamic web applications to apply or remove
styles based on user interactions or other events.
function data2(callback){
setTimeout(() => {
console.log("data2 found");
callback();
}, 3000);
}
function data3(callback){
console.log("data3 found");
pg. 81
82
callback();
}
data1(
() => {
data2(
() => {
data3(
() => {
console.log("all data found");
}
);
}
);
}
);
Note : Call backs are complicated as it is having a nested callbacks. To make the
asynchronus functions more simplier we are having the promises and async/ await.
Promises :
Promises are a feature in JavaScript that were introduced to handle
asynchronous operations more elegantly. They provide a cleaner and more readable
syntax for dealing with asynchronous code compared to traditional callback-based
approaches. Promises represent a value which might be available now, or in the
future, or never.
A Promise can be in one of three states:
1. **Pending:** The initial state; the promise is neither fulfilled nor rejected.
2. **Fulfilled:** The operation completed successfully, and the promise has a
resulting value.
3. **Rejected:** The operation failed, and the promise has a reason for the
failure.
Example :
function promiseExample(){
return new Promise((resolve, reject) => {
const found = true;
setTimeout(() => {
if (found) {
pg. 82
83
resolve("Data found");
} else {
reject("data not found");
}
}, 1000);
});
}
console.log(promiseExample());
Handling promises using the method chaining for handling multiple promises
Example :
function p1(){
function p2(response){
return new Promise((resolve, reject) => {
setTimeout(() => {
if (response == 'Data found') {
resolve("Data found");
} else {
reject("data not found");
}
}, 1000);
});
}
console.log(result);
Output :
pg. 83
84
- The `Promise` constructor takes a function with two arguments: `resolve` and
`reject`. These are functions provided by the JavaScript runtime to signal the
completion or failure of the asynchronous operation.
- Inside the function, you perform your asynchronous operation. If it succeeds, you
call `resolve` with the result. If it fails, you call `reject` with an error message.
- The `then` method is used to handle the case when the Promise is fulfilled, and the
`catch` method is used to handle the case when the Promise is rejected.
Promises Methods :
1. Promise.all() :
Can use the array of promises to make them synchronous code and will
return the resolves into an array, but if any promise failed to resolve then it
returns the reject message.
Example :
let p1 = new Promise((resolve, reject) =>{
resolve("p1 completed successfully");
})
pg. 85
86
`async` and `await` are keywords in JavaScript that are used in conjunction
with Promises to write asynchronous code in a more readable and synchronous-
looking style.
1. **`async` Function:**
The `async` keyword is used to declare an asynchronous function. An
asynchronous function always returns a Promise. It allows the use of the `await`
keyword inside it.
Example :
async function myAsyncFunction() {
// Code here
}
2. **`await` Operator:**
The `await` keyword is used to pause the execution of an `async` function
until the Promise is settled (resolved or rejected). It can only be used inside an
`async` function.
Example :
async function fetchData() {
let result = await someAsyncOperation();
console.log(result);
}
In this example, `fetchData` is an asynchronous function that calls
`someAsyncOperation`. The `await` keyword pauses the execution of `fetchData`
until `someAsyncOperation` is resolved, and then it continues with the result.
Here's an example using `async` and `await` with the `fetch` function, which is
commonly used for making asynchronous HTTP requests in modern JavaScript:
Example :
function task1(){
pg. 86
87
function task2(){
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('task2');
}, 2000);
})
}
main();
Note : Using `async` and `await` makes asynchronous code more readable and
easier to reason about compared to traditional callback-based or promise-chaining
approaches.
JSON Files :
JSON (JavaScript Object Notation) files are a lightweight data-interchange
format that is easy for humans to read and write and easy for machines to parse and
generate. They are primarily used to transmit data between a server and a web
application as an alternative to XML.
JSON files consist of key-value pairs and arrays, organized into a hierarchical
structure. The keys are strings, and the values can be strings, numbers, booleans,
arrays, objects, or null.
Example :
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"address": {
"street": "123 Main St",
"city": "Anytown",
"country": "USA"
},
"friends": ["Alice", "Bob", "Charlie"]
}
In this example:
pg. 88
89
- `"name"`, `"age"`, and `"isStudent"` are key-value pairs with string keys and
various types of values.
- `"address"` is a nested object containing its own key-value pairs.
- `"friends"` is an array containing strings as elements.
JSON files are commonly used for configuration files, data storage, and data
exchange between a client and a server in web development. They are also used in
many other contexts, such as APIs, logging, and data serialization. JSON has
become ubiquitous in web development due to its simplicity, flexibility, and ease of
use.
Note : To create JSON files we use the '.json' extension.
Using JSON :
In javascript we use the built-in methods in order to manipulate the JSON.
1. JSON.parse() : parsing JSON strings into JavaScript objects
2. JSON.stringify() : converting JavaScript objects into JSON strings
Example :
let jsonStr = '{"Name": "test", "description": "test description"}';
let jsObj = JSON.parse(jsonStr);
console.log(jsObj); //{Name: 'test', description: 'test description'}
let jsonConvert = JSON.stringify(jsObj);
console.log(jsonConvert); // {"Name":"test","description":"test description"}
NOTE : By default javascript will take the GET method when you are using the
default fetch
Syntax :
fetch(url, {options})
pg. 90
91
return fetch('https://jsonplaceholder.typicode.com/comments/1').
catch(error => console.log(error));
}
Example :
FetchData();
async function FetchData(){
try{
const res = await fetch("https://pokeapi.co/api/v2/pokemon/charizard");
if(res.ok){
const data = await res.json();
console.log(data);
}
pg. 91
92
else{
throw new Error("Cannot fetchPokemon ");
}
}
catch(err){
console.log(err);
}
}
HTTP response codes :
HTTP response codes are standardized status codes returned by a web server
in response to a client's request made to the server. These codes indicate the
outcome of the request and provide information about whether the request was
successful, encountered an error, or requires further action from the client.
- **1xx Informational**:
These are provisional responses indicating that the server has received the
request and is processing it.
- **3xx Redirection**:
These indicate that further action needs to be taken by the client to complete
the request.
- **301 Moved Permanently**: The requested resource has been
permanently moved to a new location.
- **304 Not Modified**: The resource has not been modified since the last
request.
- **4xx Client Error**:
These indicate that there was an error on the client's side, such as invalid
request syntax or unauthorized access.
- **400 Bad Request**: The request could not be understood by the server
due to malformed syntax.
- **403 Forbidden**: The client does not have permission to access the
requested resource.
- **404 Not Found**: The requested resource could not be found on the
server.
- **5xx Server Error**:
These indicate that there was an error on the server's side while processing the
request.
- **500 Internal Server Error**: A generic error message indicating that
something went wrong on the server.
- **503 Service Unavailable**: The server is currently unavailable due to
overload or maintenance.
pg. 93
94
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkbox Example</title>
</head>
<body>
<label for="myCheckbox">Check me:</label>
<input type="checkbox" id="myCheckbox">
<script>
// Your JavaScript code here
</script>
</body>
</html>
This :
In JavaScript, the `this` keyword is a reference to the current execution
context, and its value depends on how a function is called. The behavior of `this`
can be a common source of confusion for developers, as it varies in different
situations. Here are the main rules for determining the value of `this`:
1. **Global Context:**
- In the global scope (outside any function), `this` refers to the global object. In a
browser environment, the global object is usually `window`.
Example :
console.log(this); // Output: [object Window] (in a browser environment)
2. **Function Context:**
- Inside a function, the value of `this` depends on how the function is invoked.
pg. 95
96
- In a regular function (not an arrow function), `this` refers to the object that the
function is a method of or the global object if the function is not a method of any
object.
Example :
function showThis() {
console.log(this);
}
showThis(); // Output: [object Window] (in a browser environment)
3. **Method Context:**
- When a function is a method of an object, `this` refers to the object the method
is called on.
Example :
const myObject = {
myMethod: function() {
console.log(this);
}
};
myObject.myMethod(); // Output: [object Object] (referring to myObject)
4. **Constructor Context:**
- When a function is used as a constructor with the `new` keyword, `this` refers to
the newly created object.
Example :
function Person(name) {
this.name = name;
}
const john = new Person("John");
pg. 96
97
Sort :
In JavaScript, the `sort` method is used to arrange the elements of an array. The
default behavior of `sort` is to convert the elements into strings and then compare
their sequences of UTF-16 code units. This can lead to unexpected results when
sorting numbers. To sort numbers correctly, a compare function should be provided.
Example :
pg. 97
98
pg. 98
99
Date Objects :
In JavaScript, the `Date` object is used to work with dates and times. It
provides a way to represent and manipulate dates and times, allowing you to
perform various operations, such as getting the current date, formatting dates,
adding or subtracting time, and more.
1. **Creating a Date Object:**
You can create a `Date` object using the `new Date()` constructor. If no
arguments are provided, it gives the current date and time.
Example :
const currentDate = new Date();
console.log(currentDate);
2. **Parsing a Date String:**
You can create a `Date` object by parsing a date string.
Example :
const dateString = '2024-01-18T12:00:00';
const specificDate = new Date(dateString);
console.log(specificDate);
3. **Getting and Setting Components:**
The `Date` object has methods to get and set various components of a date, such
as the year, month, day, hour, minute, second, and millisecond.
Example :
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth(); // Months are zero-based (0 = January)
const day = today.getDate();
console.log(`Year: ${year}, Month: ${month + 1}, Day: ${day}`);
pg. 99
100
4. **Formatting Dates:**
You can format dates using methods like `toLocaleString()` or combining
individual components.
Example :
const formattedDate = today.toLocaleString('en-US', { weekday:
'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log(formattedDate);
5. **Adding/Subtracting Time:**
You can perform operations to add or subtract time from a `Date` object.
Example :
const futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7); // Adding 7 days
console.log(futureDate);
Note : When you want a custom date then follow the Date constructor, The date
constructor will have the following order : year, month, day, hour, min, sec, ms)
pg. 100