JavaScript Notes QSP
JavaScript Notes QSP
1. History
2. Introduction
4. Token
5. Scope
8. Function
9. Practice Questions
11. Closure
13. Array
14. Object
15. Json
19. Destructuring
21. Prototype
22. Dom
23. Event
#JavaScript Notes###
#History
1. JavaScript was first created by Brendan Eich in just 10 days in May 1995 while he was working
at Netscape Communications Corporation.
2. The initial release was called Mocha and later renamed to LiveScript, and finally JavaScript.
3. Initially, JavaScript was designed to be a lightweight scripting language for adding interactivity
to web pages.
4. At the time, web pages were mostly static and lacked interactivity, and the only way to add
dynamic content to a web page was to use a server-side programming language like PHP or Perl.
5. However, this approach had limitations and was not well-suited to creating responsive,
interactive user interfaces.
6. The idea behind JavaScript was to create a scripting language that could be executed on the
client-side (in the user's web browser) and could be used to add interactivity to web pages.
7. This allowed web developers to create more engaging and interactive websites, without having to
rely on server-side programming languages.
8. Its popularity grew rapidly as it was one of the few languages that could be executed directly in
web browsers, without the need for additional plugins or software.
9. In 1996, Microsoft released JScript as a competitor to JavaScript, which was their own
implementation of the language for their Internet Explorer browser.
10. However, JScript was very similar to JavaScript, and the two languages were largely
interchangeable.
11. Over time, JavaScript has evolved and grown to become a full-fledged programming language,
capable of creating complex applications on both the client and server-side.
12. The development of JavaScript has been heavily influenced by a number of factors, including the
emergence of new web technologies, changes in programming paradigms, and the rise of new
development frameworks and libraries.
13. Today, JavaScript is one of the most widely used programming languages in the world, powering
many of the most popular websites and web applications.
14. It continues to evolve and adapt to the changing needs of the web, with new features and
capabilities being added on a regular basis.
#Introduction
1. Javascript is scripting and programming language.
2. It is purely object based language.This means that variables, functions, and even primitive data types like
numbers and strings are object,everything is object in javascript.
3. It is dynamically typed language , it means type of value stored in memory block is checked at runtime
because of this nature we can store any type of value in variable.
4. It is object oriented programming language , it means we can create our own object. (It is not purely
object oriented programming language)
5. It is interepreted language
6. It is synchronous language , it has single threaded architecture. Instructions get executed line by line.
9. Js helps to provide behavior and functionality to webpage and helps to develop dynamic webpage
10. Every browser have js engine to run js code. Therefore browser become environment to run js code.
11. To run Js code outside browser we just need Javascript runtime environment (Node).
#Browser
1. A browser is a software application that is used to access and view information on the World Wide Web
(WWW).
2. It allows users to interact with web pages, view multimedia content, and surf the internet.
3. The Browser acts as a JavaScript runtime environment because it includes a JavaScript engine that
interprets and executes JavaScript code
#JavaScript Engine
1. A JavaScript engine is a computer program that executes JavaScript code.
2. It is a core component of web browsers, server-side JavaScript platforms, and other JavaScript-
based environments.
4. Chakra : developed by Microsoft, used in Microsoft Edge and Internet Explorer (legacy)
#Node.Js
1. The main reason of javascript popularity.
2. Node.js is a software application that executes JavaScript code. It is not a framework or a library.
3. It allows developers to run JavaScript code outside of a web browser, such as on a server or command-
line interface.
4. Node.js uses the V8 JavaScript engine, which is also used in Google Chrome.
5. It is built on top of an event-driven, non-blocking I/O model, which allows it to handle large numbers of
simultaneous connections without blocking the execution of other code.
6. This makes it well-suited for building scalable, high-performance applications that can handle a large
amount of traffic.
7. Because after introduction of Nodejs, we were able to run javascript anywhere like in web servers, as
command-line tools, desktop applications, and even IoT (Internet of Things) devices.
Features of JavaScript
1. **Scripting Language**:
- **What it means**: JavaScript is used to write small programs that automate tasks in web pages.
- **Why we call it that**: It helps make web pages interactive. For example, it can change text when
you click a button or show a pop-up message.
2. **High-Level Language**:
- **Why we call it that**: You don’t need to know the details of how the computer works to use
JavaScript. It uses simple commands and is close to human language, making it accessible for beginners.
3. **Interpreted Language**:
- **What it means**: JavaScript code runs directly in the web browser without needing to be
converted into another form first. It has interpretor which runs the code line by line.
- **Why we call it that**: You can see the results of your code immediately in the browser. This makes
it easy to test and fix your code quickly.
4. **Synchronous Language**:
- **Why we call it that**: When you write JavaScript code, it does each task step by step, making it
easier to understand what’s happening in your program.
5. **Object-Based Language**:
- **What it means**: JavaScript uses objects to store and organize data and functions.
- **Why we call it that**: In javaScript most of the things are are internally objects. Objects help keep
related code together. For example, you can have an object for a car that includes properties like color
and methods like drive.
6. **Object-Oriented Language**:
- **What it means**: JavaScript supports creating complex structures using classes and objects.
- **Why we call it that**:We can create our own objects using classes in javascript.
- **What it means**: In JavaScript, you don’t have to specify what type of data (like a number or text)
a variable holds. Also we don’t need to follow the syntax very strictly eg. No need to write semicolons.
- **Why we call it that**: This makes writing code faster and easier because you don’t have to worry
about declaring data types and don’t need to strictly follow the syntax. You can just start using variables
right away.
- **What it means**: The type of data a variable holds can change as your program runs.
- **Why we call it that**: You can have a variable that starts as a number and then later hold a string
(text) without any extra work. This flexibility makes JavaScript powerful for writing dynamic programs.
9. **Single-Threaded Language**:
- **Why we call it that**: This simplicity makes it easier to write and understand JavaScript code. Even
though it does one task at a time, JavaScript can handle many tasks quickly by using techniques like
callbacks and promises.
#Token
1. It is the smallest unit of programming language.
javascript
javascript
javascript
javascript
javascript
javascript
let x = 10;
javascript
x += 5; // x is now 15
javascript
x -= 3; // x is now 12
x *= 2; // x is now 24
javascript
x /= 4; // x is now 6
javascript
x %= 5; // x is now 1
javascript
x **= 3; // x is now 1
javascript
5 == '5'; // true
- === (Strict equal to): Checks if two values are equal and of the same type.
javascript
javascript
5 != '5'; // false
- !== (Strict not equal to): Checks if two values are not equal and/or not of the same type.
javascript
- > (Greater than): Checks if the left value is greater than the right.
javascript
10 > 5; // true
- < (Less than): Checks if the left value is less than the right.
javascript
10 < 5; // false
- >= (Greater than or equal to): Checks if the left value is greater than or equal to the right.
javascript
- <= (Less than or equal to): Checks if the left value is less than or equal to the right.
javascript
10 <= 5; // false
javascript
javascript
javascript
!true; // false
- & (AND): Returns a 1 in each bit position for which the corresponding bits of both operands are 1.
javascript
- | (OR): Returns a 1 in each bit position for which the corresponding bits of either or both operands are
1.
javascript
5 | 1; // 5 (0101 | 0001)
- ^ (XOR): Returns a 1 in each bit position for which the corresponding bits of either but not both
operands are 1.
javascript
5 ^ 1; // 4 (0101 ^ 0001)
javascript
- << (Left shift): Shifts bits to the left by the specified number of positions.
javascript
- >> (Sign-propagating right shift): Shifts bits to the right, preserving the sign.
javascript
javascript
javascript
javascript
- condition ? expr1 : expr2: Returns expr1 if the condition is true, otherwise returns expr2.
javascript
javascript
javascript
These operators are essential for performing various operations in JavaScript, from simple arithmetic to
complex logical expressions.
#Punctuators
1. These are symbols used to group, separate, or punctuate code.
2. Examples include parentheses (), curly braces {}, square brackets [], commas ,, semicolons ;, and the
period . (used to access object properties).
#Keywords
1. These are reserved words that have a special meaning in the language.
2. Examples like if, else, for, while, function, and return,etc.
#Identifiers
1. These are user given names to variables, functions, and other objects in the code.
5. identifier name should not have special character but can start with underscore(_) and dollar($).
#Literals
1. These are values used in our program like number(2),string('hello world') , etc.
2. Non-Primitive
#Primitive Literals
1. In JavaScript, a primitive data type is a data type that represents a single value.
2. JavaScript treats primitive values as immutable values, means that their value cannot be changed.
Instead, when you perform an operation that appears to modify a primitive value, you are actually creating a
new object with new value and assigning it to a variable. Here , variable will hold the reference of latest
object with new value and the previous object with it's value will garbage collected.
3. We have 8 primitive types of literals -number , bigint , boolean , nan , undefined , null , symbol , string..
#Primitive Datatypes
1. Number
1. This data type represents a numeric value. It can store both integers and floating-point values.
2. BigInt
1. It is used to represent integers that are larger than the Number data type
3. To represent the given integer as bigint , we have to suffix 'n' after the integer.
Example : 10 is number type and 10n is bigint type.
3. Boolean
1. This datatype represents a logical entity and can only have two values: true or false.
4. Null
5. Undefined
2. When memory block is unintialized , js engine implicitly initialize that memory block with 'undefined' in
variable phase.
4. For variable declared with 'let' and 'const' it will not initialize it in variable phase.
6. NaN
7. Symbol
2. We have Symbol function which is used to generate unique idenitifiers in our program.
8. String
2. We have two types of strings :- single line and multi line string.
#Non-Primitive Literals
1. In JavaScript, a non primitive data type is a data type that represents multi value.
2. JavaScript treats non-primitive values as mutable values, means that their value can be changed. When
we try to update a value , new object is not created . Here value is changed in the same memory block.
#Scope
1. Scope defines the visibility or accessibility of a variable.
2. Local Scope
#Global Scope
1. The variable declared in global scope can be accessed anywhere in the program.
2. The variable declared in local scope can be accessed in that block only i.e. we can not access the
variable from outside.
4.
Note: Variables declared with let and const are also locally scoped.
Firefox represent it as - Block scope.
Chrome represent it as - Script scope.
2. Here, we have a window variable which have reference of Global Execution Context.
#Window Variable
1. Window variable or window object -> everything is object in js.
2. Window is a global variable which store the reference of Global Execution Context
3. Window object is also known as Global Object because it is available anywhere in the program.
5. Variable declared with var always goes to global scope and can be accessible by window object.
6. Any variable created in global scope will be addes in Window object implicitly by JS Engine.
2. Execution phase
#Variable Phase
1. In variable phase, JS Engine will check the complete JS Code and it will search for variable declaration
statement.
3. Variable declared with var will be initialized storing "undefined" at the time of memory block creation.
Variable declared with let and const will remain uninitialized (empty) at the time of memory block
creation.
#Execution Phase
1. In Execution phase, JS Engine will execute the instruction line-by-line.
#Var
1. Variable declared with var goes to global scope.
7. Variable declared inside function , will not go to global scope. It will be accessible inside function only.
#Let
1. Variable declared with let is block scoped.
4. We can declare variable using let without initialization. But js engine will keep that memory block
uninitialized (empty) untill js engine reads declaration statement in execution phase.
5. Because let variable is uninitialized (empty) in variable phase , it belongs to Temporal Dead Zone.
6. The variable declared using let does not belongs to global scope , we cannot access them with the
help of window variable.
7. The variable declared using let is hoisted and belongs to temporal deadzone. Therefore it cannot be
used before initialization (because at that moment it is uninitialized - TDZ) .
#Const
1. Variable declared with const is block scope.
5. The variable declared using const is hoisted and belongs to temporal deadzone. Therefore it cannot
be used before initialization (because at that moment it is uninitialized - TDZ) .
6. The variable declared using const inside block ,does not belongs to global scope we cannot use them
with the help of window.
console.log("start");
let a = 10;
var b = 20;
const c = 30;
{
let a = 100;
var b = 200;
const c = 300;
console.log(a);
console.log(b);
console.log(c);
}
console.log(a);
console.log(b);
console.log(c);
console.log("end");
2.
console.log("start");
let a = 10;
console.log(b);
{
var b = 200;
}
console.log(a);
console.log(b);
console.log("end");
3.
console.log("start");
let a = 10;
{
console.log(a);
let a = 10;
}
console.log(a);
console.log(b);
console.log("end");
4.
console.log("start");
var b = 20;
const c = 30;
{
let a = 100;
console.log(a);
console.log(b);
console.log(c);
}
console.log(a);
console.log(b);
console.log("end");
5.
console.log("start");
let a = 10;
var b = 20;
const c = 30;
{
let a = 10;
console.log(a);
const c = 300;
console.log(b);
b = 200;
c = 30;
console.log(b);
}
console.log(a);
console.log(b);
console.log("end");
#Functions
1. Function is object.
9. When we try to log function name the entire function defination is printed.
11. Any member with local scope cannot be used outside the function block.
13. Variable written inside function even using var have local scope.
15. In javascript 'this' is a property of every function.(every function will have 'this' Keyword except
arrow function)
#Parameter
1. The variables declared in the function defination is known as parameters.
2. The parameters have local scope (can be used only inside function body).
3. Parameters are used to hold the values passed by caller (or calling statement).
#Arguments
1. The values passed in the method call statement is known as arguments.
#Return Keyword
1. It is a keyword used as control transfer statement in a function.
2. Return will stop the execution of the function and transfer control along with data to the caller.
1.
Syntax :
function func_variable(parameters) {
//statements
}
func_variable()
2.
Example : Create a function 'greet' which should print a message "Good Morning" when it is
called.
function func_variable(parameters) {
//statements
}
func_variable()
3.
greet();
function greet() {
console.log("Good Morning");
}
#Functional Programming
1. Functional Programming is a programming technique where we pass a function along with a value to
another function.
2. In this approach, we generate Generic Function. Here function task is not predefined. It perform
multiple task not only single task
3. The Function which accept another function as a parameter or return a function is known as 'Higher
Order Function'.
4. The Function which is passed to another function or the function which is returned by another
function is known as 'Callback Function'.
#Types Of Functions
1. Function decalaration statement : Using function keyword
1. when a function is called as soon as it's object is created is known as Immediate Invoke Function.
2. We have to write the function inside the paranthesis to group it. [using Group operator -> (function
code) ].
4. Arrow Function
6. Implicit return :- If there is only one statement and If block is not created then JS Engine will return
that statement automatically.
7. Explicit return :- If block is created and function is not returning any value, JS Engine will return
undefined. To return a value Explicitly from block, we have to use return keyword.If block is created
then we have to use return keyword to return value otherwise JS Engine will return undefined.
1. The Function which accept another function as a parameter or return a function is known as 'Higher
Order Function'.
6. Callback Function
1. The Function which is passed to another function or the function which is returned by another
function is known as 'Callback Function'.
#Nested Function
1. The function inside another function is called as nested function.
2.
Example :
function outer(){
function inner(){
}
return inner
}
3. The outer function is known as parent and the inner function is known as child.
4. The inner function is local to outer function, it cannot be accessed from outside.
5.
To use inner function outside, the outer function must return the reference of inner function.
function outer(){
function inner(){
}
return inner
}
1st Way:
let fun=outer();
fun(); // -----> inner() is called
2nd Way:
Hoisting
Hoisting in JavaScript means that variable and function declarations are moved to the top of their scope
before the code runs. This allows you to use them before they are actually declared in your code.
Variable Hoisting
1. **var**
- Variables declared with `var` are moved to the top of their function scope.
- They start as `undefined` until the line of code where they are assigned a value.
```javascript
console.log(x); // undefined
var x = 5;
console.log(x); // 5
```
- Variables declared with `let` and `const` are also moved to the top of their block scope.
- They are not initialized until the code reaches their declaration.
```javascript
let y = 10;
console.log(y); // 10
const z = 15;
console.log(z); // 15
```
1. **Function Declarations**
- Function declarations are moved to the top of their scope.
- You can call these functions before they are declared in the code.
```javascript
console.log(sum(2, 3)); // 5
function sum(a, b) {
return a + b;
```
2. **Function Expressions**
```javascript
console.log(multiply); // undefined
return a * b;
};
```
```javascript
return a / b;
};
```
- **`var` variables**: Moved to the top of the function scope, start as `undefined`.
- **`let` and `const` variables**: Moved to the top of the block scope, not initialized until declared.
- **Function declarations**: Fully moved to the top, can be used before they appear in the code.
- **Function expressions**: Only the variable part is moved, not the function assignment.
```javascript
let a = 10;
console.log(a); // 10
```
- These variables are in the TDZ from the start of the block until they are declared.
2. **Purpose of TDZ**:
- The TDZ helps catch mistakes by not allowing the use of variables before they are properly declared.
```javascript
function example() {
let b = 20;
console.log(b); // 20
example();
```
In this function, `b` is in the TDZ until `let b = 20;` is executed.
```javascript
function exampleVar() {
var c = 30;
console.log(c); // 30
exampleVar();
```
For variables declared with `var`, there is no TDZ. They are hoisted to the top and initialized as
`undefined`.
### Summary
- **Error**: Using these variables before they are declared gives an error.
Example of a Closure
function outerFunction() {
function innerFunction() {
return innerFunction;
```
Here, `innerFunction` remembers `outerVariable` from `outerFunction` even after `outerFunction` has
finished running. This is a closure.
Key Points
2. Remembering Variables:
- The inner function "remembers" the variables from the outer function's scope even after the outer
function has finished running.
3. Practical Use :
Simple Example
function createCounter() {
let count = 0;
return function() {
count += 1;
console.log(count);
};
counter(); // Logs: 1
counter(); // Logs: 2
counter(); // Logs: 3
```
In this example, the inner function increments and logs the `count` variable each time it is called. The
`count` variable is remembered between calls because of the closure.
Summary
- Closure : A function that remembers and can use variables from outside its own scope.
- How : Defined inside another function, accessing the outer function's variables.
- Use : Useful for maintaining state or creating private variables and functions.
- **Description:** Returns the day of the week (0 for Sunday, 1 for Monday, ..., 6 for Saturday).
```javascript
switch (dayOfWeek) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
```
### 2. `getDate()`
```
### 3. `getHours()`
```javascript
```
### 4. `getMinutes()`
```javascript
```
### 5. `getSeconds()`
```javascript
```
### 6. `getMilliseconds()`
```javascript
```
### 7. `getMonth()`
- **Description:** Returns the month (0 for January, 1 for February, ..., 11 for December).
```javascript
switch (month) {
case 0:
console.log("January");
break;
case 1:
console.log("February");
break;
case 2:
console.log("March");
break;
case 3:
console.log("April");
break;
case 4:
console.log("May");
break;
case 5:
console.log("June");
break;
case 6:
console.log("July");
break;
case 7:
console.log("August");
break;
case 8:
console.log("September");
break;
case 9:
console.log("October");
break;
case 10:
console.log("November");
break;
case 11:
console.log("December");
break;
```
### 8. `getFullYear()`
```javascript
```
Math methods:
### 1. `Math.cbrt()`
```javascript
```
### 2. `Math.floor()`
- **Description:** Returns the largest integer less than or equal to a given number.
```javascript
```
### 3. `Math.min()`
```javascript
const num2 = 5;
```
### 4. `Math.max()`
const num2 = 5;
```
### 5. `Math.pow()`
- **Description:** Returns the base to the exponent power, that is, base^exponent.
```javascript
const base = 2;
const exponent = 3;
```
### 6. `Math.random()`
```javascript
### 7. `Math.sqrt()`
```javascript
```
#Practice Questions
1. Write a program to find square and cube of a given number.
3. Write a program to calculate the sum of the first 100 natural numbers.
5. Write a program to print the sum of all even numbers from 1 to any given number.
6. Write a program to print the sum of all odd numbers from 1 to any given number.
10. Write a program to reverse a given number. For example, if the input is 12345, the output should be
54321.
11. Write a program that prints the numbers from 1 to 100. But for multiples of three, print 'Fizz' instead
of the number, and for multiples of five, print 'Buzz.' For numbers that are multiples of both three and
five, print 'FizzBuzz.'
12. Write a program to calculate the power of a number without using the Math.pow() function.
14. Write a program to find and print all the prime numbers within 1-100.
17. Write a program to calculate the sum of the first 20 Fibonacci numbers.
23. Print numbers up to 500 that are divided by 7 and end with 7.
24. Write a program to print the factors of a number and also print the number of factors of that
number.
2. It is ability of child to access variable from outside if its not present in local scope
3. Lexical scope : A function and global object.
let a = 10;
function test() {
a++;
console.log( a );
}
test();
Output : 11
When test function is executed js engine looks for ' a ' in local scope. Since it will not available it will look
for a in outer scope that is global window object .
4. Lexical scope : The child function and parent function with a help of closure.
function outer() {
let a = 10;
function inner() {
console.log(a);
}
return inner;
}
Output : 10
When the function inner is executed and console.log a is encountered, js engine looks for a in the local
scope of function inner.
Since, a is not present and function inner is child of function outer js engine will search for a in the
parent function outer scope with the help of closure.
#Closure
1. A closure is created when a function is defined within another function and inner function need to
access variables in the outer function's scope.
2. Closure helps to achieve lexical scope from child function to parent function.
3. Closure preserves the state of parent function even after the execution of parent function is
completed.
#Interview Questions
1. What is JavaScript? (Write 6 points)
3. Write the names of JavaScript engines for Chrome, Firefox, Edge, and Safari.
4. What is a JS engine?
6. What is hoisting?
11. What is explicit and implicit return in arrow functions? Provide an example.
12. What is closure? When is a closure created? Explain with an example.
#Array
1. Array is object in javascript.
3. It is a block of memory which is used to store multiple type of value (any type of literal) in same
memory block.
4. Array size is dynamic (size is not fixed like JAVA) , it means we can store 'N' number of elements and JS
engine will handle memory usage automatically.
6. Array elements are arranged in a sequence that is represented by integer number called as index.
Array index starts from zero to array size - 1 (suppose array has 5 elements it's first index will be - 0 and
last index will be 4).
7. We can access the array element with the help of array object reference , square brackets and
index ( array_object_ref[index] ).
8. If we try to access the index that it greater than the array length we will get undefined.
NOTE : Here , 'arr' is a variable which holds the reference of array object. To access array element at
index -> 1Syntax : array_object_ref[index]Example : console.log(arr[1]); // 20
#Array Methods
1. push(value) method
3.
Example:
let arr=[10,20,30,40,50];
arr.push(100);
output: [10,20,30,40,50,100]
2. pop() method
3.
Example:
let arr=[10,20,30,40,50];
arr.pop();
output: [10,20,30,40]
3. unshift(value)
3.
Example:
let arr=[10,20,30,40,50];
arr.unshift(200);
output: [200,10,20,30,40,50]
4. shift() method
3.
Example:
let arr=[10,20,30,40,50];
arr.shift();
output: [20,30,40,50]
5. splice() method
4.
Example:
arr_ref.splice(a,b,c)
a - starting index
b - number of elements to be deleted
c - elements to be inserted
5.
let arr=[10,20,30,40,50];
arr.splice(1,3); // deleted: [20,30,40]
console.log(arr);
Output : [10,50]
6.
let arr=[10,20,30,40,50];
arr.splice(3,1,500);
console.log(arr);
Output : [10,20,30,500,50]
7.
let arr=[10,20,30,40,50];
arr.splice(2,0,100,200,300);
console.log(arr);
Output : [10,20,100,200,300,30,40,50]
6. slice() method
1. It is used to copy array elements.
4.
Syntax :
arr.slice(a,b);
a - starting index
b - last index
5.
let arr=[10,20,30,40,50];
let copy_elements = arr.slice(0,3);
console.log(copy_elements);
Output: [10,20,30]
7. indexOf() methods
4.
Syntax :
arr.indexOf(a,b)
a - value to be searched
b - search starting index
5.
Example : Check given array has element 30 or not and search from index 0 and 3 , if present
print index.
let arr=[10,20,30,40,50];
console.log(arr.indexOf(30)); // 2
console.log(arr.indexOf(30,3)); // -1
8. includes() method
4.
Syntax :
arr_ref.includes(a,b);
a - value to be searched
b - search starting index
5.
Example : Check given array has element 30 or not and search from index 0 and 3 , if present
print true.
let arr=[10,20,30,40,50];
console.log(arr.includes(30)); // true
console.log(arr.includes(30,3)); // false
9. reverse() method
3.
Example:
let arr=[10,20,30,40,50];
console.log(arr.reverse());
Output: [50,40,30,20,10]
10. sort(callback) method
5.
6.
11. foreach(callback)
4.
Syntax :
arr_ref.foreach((value,index,array)=>{
// statements
})
5.
6.
Syntax :
arr_ref.map((value,index,array)=>{
// statements
})
7.
Example: Create new array where each element of given array is multiple of 8.
let arr=[10,20,30,40,50];
let new_arr = arr.map(value => value * 8 );
console.log(new_arr);
Output: [80,160,240,320,400]
13. filter(callback)
5. Here, element will be inserted in new array only when callback function returns true.
6.
Syntax :
arr_ref.filter((value,index,array)=>{
// statements
})
7.
Example: Create new array where elements are greater than 40.
let arr=[10,20,30,40,50,60,70];
let new_arr = arr.filter(value => {
if(value > 30)
return true;
});
console.log(new_arr);
Output: [40,50,60,70]
14. reduce(callback,initial_value)
5. Here , single value is returned after complete iteration of array. Value is stored in a variable which
is used to result , we refer it as accumulator.
6.
Syntax :
arr_ref.reduce((accumulator,value,index,array)=>{
// statements
},initial_value_of_accumulator)
If we does not pass initial value of accumulator first element of array will be stored
automatically.
7.
let arr=[10,20,30,40,50,60,70];
let result = arr.reduce((acc,value) => {
acc = acc + value;
return acc;
},0);
console.log("Sum of all elements : ",result);
15. Array.isArray(literal)
5.
console.log(Array.isArray({})); //false
console.log(Array.isArray(10)); //false
console.log(Array.isArray([10,20,30])); //true
16. Array.from(literal)
4.
#Object
1. An Object is a block of memory which has state(variable) , behaviour(methods) and where we can
store heterogenous data.
2. An object is a collection of key-value pairs that can contain various data types, such as numbers,
strings, arrays, functions, and other objects.
3. In one object we can have multiple key value pair and it should be separated by ',' comma.
4. We can access value of object using (.) Operator or square bracket [] , object reference and
key_name.
2. If keys name are in Number , js engine will convert them into string and arrange them in ascending
order.
3. To write space separated key names , we have to enclose key name with double quotes.
4. If we want to give computed or user defined property then we have to use square brackets and
variable name.
5.
If key-name is same as variable name which hold the value , instead of writing two times we can
write varaiable name only once.
1.
let obj = {}
// empty object
2.
4. By using class
1.
console.log(obj.name)// chombi
console.log(obj.age)// 16
2.
console.log(obj["name"])// chombi
console.log(obj["age"])// 16
3. If we try to access property which is not available in object we will get undefined.
#Object Methods
1. In JavaScript, object methods are functions that are attached to the object, and can be called on that
object reference.
3.
4.
Access object property inside function - function declared with function keyword.
5.
let obj1 = {
name: "chombi",
age: 16,
speak: () => {
console.log(
"My name is" + obj1.name + " , age " + obj1.age + " and i
can speak"
);
},
};
console.log(obj1["speak"]());
//My name is chombi , age 16 and i can speak
// Here, we can access object property, by using object
reference.
Here , we can can access object property , by using object reference because arrow function is not
having 'this' property.
1. To add key-value pair we can using dot operator and square brackets
2.
obj.country = "india";
//new key-value added in object
// {
name:"chombi",
age:16,
country:"india",
}
NOTE : If property is already available with same name it will updated with new value.
Example:
let obj = { name:"chombi",age:16 }
obj.age = 18;
//age property value is updated
// {
name:"chombi",
age:18,
}
1.
obj.country = "india";
//new key-value added in object
// {
name:"chombi",
age:16,
country:"india",
}
1. Shallow copy
2. Deep Copy
2. Shallow copy
1. The copy of object that is directly connected with original object is called as shallow object.
2. Here, we store reference of original object in a new varaiable , now new variable starts pointing to
same memory block.
3. So if we make any changes in copy , it will be reflected to original object because both variables are
pointing to same memory block.
4.
obj_copy.age=20;
console.log(obj_copy);
//{ name:"chombi",age:20 }
console.log(obj);
//{ name:"chombi",age:20 }
3. Deep copy
1. The copy in which original object is not connected with it's copy , is called as Deep copy.
2. Here , we create separate empty object and after that we copy key-value pair of original object into
new empty object.
3. Now , if we make any changes in copy , it will not be reflected to original object because we have
create separate memory blocks.
4.
let obj2 = { }
// new empty object
obj2.age=20;
console.log(obj2);
//{ name:"chombi",age:20 }
console.log(obj1);
//{ name:"chombi",age:16 }
#Object In-Built Methods
1. Object.keys(obj_ref)
2.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));
// Output: ["a", "b", "c"]
2. Object.values(obj_ref)
2.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));
// Output: [1,2,3]
3. Object.entries(obj_ref)
2.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));
// Output: [[a,1],[b,2],[c,3]]
4. Object.assign(target_obj,src1,...,srcn)
1. Copies key-value pair from one or more source objects to a target object.
2.
const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };
const result = Object.assign(target, source);
console.log(result);
// Output: { a: 1, b: 2, c: 4, d: 5 }
#What Is JSON?
1. JSON stands for javascript object notation.
5. It supports six data types: object, array, string, number, boolean, and null.
6. It supports nested structures, allowing objects and arrays to be nested within each other.
#JSON Methods
1. JSON.stringify(value)
- JSON.stringify() is a method that converts a JavaScript object or value into a JSON string.
- Returns JSON.
- It does not support : function properties,symbolic keys and values and Properties that store undefined.
2. JSON.parse(value)
- JSON.parse() is a method that converts JSON string into JavaScript object or value.
#Introduction
1. Call , Apply and Bind methods are used to store the object reference in 'this' keyword of function.
2. When function's 'this' have reference of object, then we can access states and behaviours of that
object.
3.
let human1 = {
name: "Chombi",
age: 20,
};
let human2 = {
name: "Dinga",
age: 19,
};
let human3 = {
name: "Nimbi",
age: 18,
};
Below function we will use to access object's properties by using call, apply and bind methods.
function detailsAll(a, b, c) {
console.log("Name : " + this.name);
console.log("Age : " + this.age);
console.log("value of a : " + a);
console.log("value of b : " + b);
console.log("value of c : " + c);
}
#Call
1. Call method accepts object reference as first argument And accepts 'n' number of arguments.
4.
Example : Print name , age of object human1 and print function arguments.
detailsAll.call(human1, 10,20,30);
Output -
Name : Chombi
Age : 20
value of a : 10
value of b : 20
value of c : 30
#Apply
1. Apply method accepts of 2 arguments where object reference is first argument and 2nd argument is
the array of arguments.
4.
Example : Print name , age of object human2 and print function arguments.
detailsAll.apply(human2,[11,22,33]);
Output -
Name : Dinga
Age : 19
value of a : 11
value of b : 22
value of c : 33
#Bind
1. Bind method accepts object reference as 1st argument and excepts 'n' number of arguments.
2. Here 'n' number of arguments are passed to the function's parameter list.
4. It returns a new function in which 'this' Keyword is pointing to the object reference we have passed.
6.
Example : Print name , age of object human3 and print function arguments.
#Constructor Function
1. A function which is used to create an object is known as constructor function.
2. A constructor function behaves like blueprint or template for object , and there is no need to write
code again and again
5. If the function is designed to use as a constructor than name of function should be upper camel case.
6. The list of parameter provided to the function will be treated as keys/properties of the object.
8. We can copy the values into the keys of the object from parameter using this keyword.
9. We can create a object using the constructor function with the help of new keyword.
10. To create constructor function we will not use arrow function because they does not have 'this'
keyword .
12.
Example :
function Car(model,color,engine) {
this.model = model;
this.color = color;
this.engine = engine;
}
#This Keyword
1. It is a keyword.
4. It is a local variable of every function in js, and holds the address of window object. Except in Arrow
function (for arrow function is stores undefined).
5. Inside object methods, 'this' holds the reference of current object(not in arrow function).
In javascript this keyword refers to the object that executes the current function.
In the global execution context (outside of any function), `this` refers to the global object. In a web
browser, this is usually the `window` object.
```javascript
```
```javascript
function showThis() {
showThis();
```
When a function is called as a method of an object, `this` refers to the object the method is called on.
```javascript
const person = {
name: 'Prasad',
greet: function() {
};
person.greet();
```
When a function is used as a constructor with the `new` keyword, `this` refers to the newly created
object.
```javascript
function Person(name) {
this.name = name;
```
Arrow functions do not have their own `this`. Instead, they inherit `this` from the surrounding lexical
context.
```javascript
const person = {
name: 'Alice',
greet: () => {
console.log(this.name);
};
person.greet(); // Logs undefined because `this` is inherited from the global context
```
In an event handler, `this` refers to the element that received the event.
```javascript
document.getElementById('myButton').addEventListener('click', function() {
});
```
You can explicitly set `this` using `call`, `apply`, and `bind`.
```javascript
function greet() {
console.log(this.name);
```
- **`apply`**: Calls a function with a given `this` value and an array of arguments.
```javascript
function greet(greeting) {
```
```javascript
function greet() {
console.log(this.name);
```
### Summary
- **Function context**: `this` is the global object in non-strict mode, `undefined` in strict mode.
#Destructuring
1. The process of extracting the values from the array or object into the variables is known as
destructuring.
2. The two most used data structures in JavaScript are Object and Array, both allows us to unpack
individual values into variables.
#Object Destructuring
1. The process of extracting the values from the object into the variables is known as object
destructuring.
2. All the key names provided on LHS are consider as variable and these variables should be declared
and written inside curly braces.
5. If the key is present , the value is extracted and copy into variable.
7. After destructuring , we can directly access variable names , without using object reference.
8.
Example :
let obj = {
name:"chombi" ,
age:16 ,
}
Here , we are trying extract name , age and country from obj. name and age is present in obj but
country is not , so inside country js engine stored undefined and for name , and age we have
respective values.
#Array Destructuring
1. The process of extracting the values from the array into the variables is known as array destructuring.
2. All the key names provided on LHS are consider as variable and should bewritten inside square
brackets.
3. Js engine will extract the array values and stored them variables in the same order as they are present
inside array.
4. if we try to access value which is not present inside array , js engine will store undefined inside that
variable.
5.
Example :
2.
function details({name,age}) {
console.log(name);
// chombi
console.log(age);
// 16
let obj = {
name:"chombi" ,
age:16 ,
}
Here , we have passed object as an argument to details function , and we have destructured
values in parameter only.
3.
Here , we have passed array as an argument to details function , and we have destructured values
in parameter only.
1. Rest parameter is used to accept multiple values , stored them in an array and array's reference will
stored the variable that we have used for rest.
5. We can use rest in function when we don't know the exact number arguments.
6. In function , there can be only one rest parameter and it should be the last parameter.
7.
}
details(10,20,30,40,50,60,70);
//function call
Here , if we pass two values it will be stored in a,b respectively and further value will stored by
rest in an array. We can pass n number of values.
8.
9.
2.
Use cases :
- The unpack data can be sent to the function as an argument by using spread operator in the
function call statement.
function sum(...data) {
let acc = 0;
for (let val of data) {
acc = acc + val;
}
return acc;
}
let result = sum(...arr);
console.log(result);
Output: 561
- We can ask the spread operator to store the unpack element in array object by using spread
operator inside [ ] brackets.
let human1 = {
name: "Chombu",
age: 21,
};
console.log(human2);
3.
#Introduction to Prototype
1. In JavaScript, every function is associated with an object called as prototype.
2. It serves as a blueprint or a template from which other objects can inherit properties and methods.
4. When you access a property or method on an object, JavaScript first looks for that property or
method directly on the object itself. If it doesn't find it there, then it looks at the object's prototype, and
continues up the prototype chain until it either finds the property/method or reaches the end of the
chain (where the prototype is null).
5. This allows us to define common properties and methods in a prototype, and all objects that inherit
from that prototype will have access to those properties and methods.
#_ _proto_ _
1. The reference of prototype object is stored in _ _proto_ _
2. When an object is created a prototype object is not created instead the object will have reference of
the prototype object (from which properties are to be inherited) referred using _ _proto_ _.
#Prototypal Inheritance
1. Prototypal inheritance is a fundamental concept in JavaScript's object-oriented programming model.
2. It allows objects to inherit properties and methods from other objects, forming a prototype chain.
#Prototype Chain
1. The prototype chain is a mechanism in JavaScript that allows objects to inherit properties and
methods from other objects.
2. The prototype chain forms a hierarchy of objects, where each object's prototype is linked to its parent
object's ptototype, creating a chain of inheritance.
3. By following this chain, objects can inherit properties and methods from their prototype objects.
#Dom
1. The Document Object Model (DOM) is a programming interface for web documents that represents
the HTML or XML document as a tree structure, where each node represents an element, attribute, or
piece of text in the document.
2. When a web page is loaded, the browser creates a DOM tree that represents the document's
structure and content.
3. Each node in the tree is represented as js object , which we can access and manipulate using the DOM
API.
4. Here , Html elements , comments , text , content , etc are refered as nodes of DOM tree.
#Dom Api
1. The DOM API (Application Programming Interface) is a set of programming interfaces and methods
that allow developers to interact with the DOM tree and manipulate the content and structure of web
documents.
2. The DOM API provides a standardized way to create, modify, and delete elements and attributes,
change styles and classes, handle events, and more.
#Html Structure
1.
<body>
<h1>Falling In Love With Javascript</h1>
<div class="container">
<div class="item item1" id="itemone">1</div>
<div class="item item2">2</div>
<div class="item item3">3</div>
<div id="itemfour" class="item item4">4</div>
<div class="item item5">5</div>
</div>
<p>hello i'm paragraph</p>
</body>
#Target Elements
1. getElementById('id_name')
2.
Example:
2.
2.
divs[0].style.backgroundColor = "yellow";
divs[0].style.padding = "10px";
divs[0].style.display = "flex";
divs[0].style.gap = "10px";
divs[0].style.justifyContent = "space-between";
divs[i].style.fontSize = "32px";
divs[i].style.padding = "10px";
divs[i].style.color = "white";
}
4. querySelector('css_selector')
1. It returns reference of the first element that matches a specified CSS selector.
2.
2.
1. It is used to create a new html element of the specified type and returns a reference to it as a
javascript object.
2.
2.
Example: Insert the section tag inside div tag having class 'container'.
.
3. insertAdjacentElement('posiiton',element)
3.
Example: Show how to display element as child and sibling of div having class 'container'.
pdiv.insertAdjacentElement("beforebegin", sec);
pdiv.insertAdjacentElement("afterend", sec);
pdiv.insertAdjacentElement("afterbegin", sec);
pdiv.insertAdjacentElement("beforeend", sec);
#Insert Text And Elements
1. textContent
2.
let p = document.getElementsByTagName("p")[0];
p.textContent="Hello";
Example: Insert "Hello" text inside p tag and preserve previous text also.
let p = document.getElementsByTagName("p")[0];
p.textContent +="Hello";
2. innerHTML
2.
Example: Insert "<strong>Hello</strong>" inside p tag .
let p = document.getElementsByTagName("p")[0];
p.innerHTML="<strong>Hello</strong>";
Example: Insert "<strong>Hello</strong>" inside p tag and preserve previous text and element.
let p = document.getElementsByTagName("p")[0];
p.innerHTML+="<strong>Hello</strong>";
#Insert And Remove Attribute
1. setAttribute('attribut_name','value')
2.
2.
divs[2].removeAttribute("id");
#Traverse Html Nodes
1. parentElement
1. It returns the reference of parent html element.
2.
2.
Example: Print next sibling element of third div whose class is "item".
2.
Example: Print previous sibling element of third div whose class is "item".
2.
1. It returns Nodelist of all types of nodes like string , text , comment , etc.
2.
2.
let p = document.getElementsByTagName("p")[0];
p.remove();
2. Whenever event occurs browser creats an object which contains all information about the event and
object on which event occured.
3. Example: Like if user click on <h1> tag , browser automatically creates an object which have
information about h1 tag and type of event occured (here , type is 'click').
2. Event object is passed to respective event handler , every time event occured.
3. So, we can access event object in callback function.
2. By writting logic in callback , we can control what to do when event occurs like change text color, hide
or show, etc.
1. As an HTML attribute
- Example : When user clicks on div , it's color should change to red.
<script>
function handleButtonClick() {
let div = document.querySelector('div');
div.style.backgroundColor='red';
}
</script>
2. As a JS Property
- In this approach , first we need the reference of element then we attach listener to it (the way we add
property to an object).
- Example : When user clicks on div , it's color should change to red.
<script>
function handleButtonClick() {
div.style.backgroundColor='red';
}
</script>
3. Using addEventListener Method
- In this approach , first we need the reference of element then we attach listener to it (the way we add
property to an object).
- Syntax : element.addEventListener(event_name,function_reference)
- First argument will be the event name (no need prefix 'on') and pass function reference.
- Example : When user clicks on div , it's color should change to red.
<script>
function handleButtonClick() {
div.style.backgroundColor='red';
}
</script>
#Type Of Events
1.
Keyboard Events
2.
Mouse Events
3.
Form Events
Event Name Info
#Exception
1. Exception is an unwanted or unexpected problem, which occurs during the execution of a program.
#Exception Handling
1. The process of handling unwanted or unexpected problem at runtime without affecting program
execution is called as
Exception handling
1. The try block contains the code that might throw an exception.
2. If an exception occurs within the try block, control is immediately transferred to the corresponding
catch block.
2. catch
1. The catch block is used to handle exceptions that are thrown within the corresponding try block.
2. It contains code that will be executed if an exception is thrown, and is typically used to handle the
exception in some way (e.g., logging an error message, displaying a user-friendly error message, or
taking some other appropriate action).
3. finally
1. The finally block is used to specify code that should be executed regardless of whether or not an
exception is thrown.
2. This block is typically used to clean up resources (e.g., closing files or closing network connections)
that were allocated within the try block.
4. Example
1.
try {
// Code that might throw an exception
console.log("Execution complete");
}
#Throw
1. throw is a keyword used to manually trigger an exception.
2. When throw is used, it causes the JavaScript interpreter to stop executing the current block of code
and transfer control to the nearest catch block that can handle the exception.