Basic
JavaScript
Notes
Linking in JavaScript :
1. Internal Linking - The JavaScript code is part of the HTML file using a <script> tag.
<script>
[Link]("Hello World!");
</script>
2. External Linking - The JavaScript code is a different file.
<script src = "[Link]"> </script>
Variables in JavaScript :
1. Var - This has global scope, it is accessible from everywhere in the code. JS is a
dynamically typed language, there is no need to define the datatype beforehand.
var age = 22;
var firstName = "Akshat";
2. Let - Same as Var, but it has local scope. The value of both these datatypes can be
changed later in the code.
let age = 22;
let firstName = "Akshat";
3. Const - It has local scope but has one addition. The value of const cannot be changed.
This is the most preferred type.
const age = 22;
const firstName = "Akshat";
String and Integer Case :
1. String + String = String
2. String + Number = String
3. String * Number = Number
TypeOf Operator - This is used to find the data type of a variable.
//string will be printed
[Link](typeof [Link]);
DataTypes in JavaScript :
//numbers
let num1 = 3.14;
let num2 = 10;
[Link](num1 + num2);
//strings
const firstName = "Akshat";
const lastName = "Pandey";
[Link](firstName + ' ' + lastName);
//booleans
let isLoggedIn = false;
let isLoggestOut = true;
[Link](isLoggedIn);
//vo chiz hai, par uski value nhi hai
let lastLoginDate = null;
//delete from memory
let lastLoginDate2 = undefined;
//objects
const person = {
firstName: "Akshat",
lastName: "Pandey",
age: 18,
isLoggedIn: false;,
}
//prints entire object
[Link](person);
//prints only firstName
[Link]([Link]);
Conditional Statements :
const age = 22;
if(age >= 18) {
[Link]("Yes, you can vote.");
}
else if(age >= 60) {
[Link]("You are a senior citizen, who can vote.");
}
else {
[Link](No, you can't vote.);
}
//ternary operator
age >= 18 ? [Link]("Yes") : [Link]("No");
Switch Statement :
switch(option) {
case 1: [Link]("Case 1");
break;
case 2: [Link]("Case 2");
break;
case 3: [Link]("Case 3");
break;
default: [Link]("Invalid Option");
}
Logical Operators :
//AND (&&) -> All conditions must be true
//OR (||) -> At Least one condition must be true
//NOT (!) -> Nahi hona chahiye, reverse kar deta hai
if(age >= 18 && gender == "male") {
[Link]("You are an adult male");
}
if(!(number % 2 == 0)) {
[Link]("Odd");
}
Loops in JavaScript :
//for loop -> if you know how many times
for(let i = 1; i <= 10; i = i + 1) {
[Link]('Run');
}
//while loop -> you don't know how many times
let ip = 0;
let house = 50;
while(ip != house) {
ip = ip + 1;
[Link]('Step Taken');
}
//do while loop -> first code is executed then check
do {
ip = ip + 1;
[Link]('Step Taken');
} while(ip <= house);
Take Input from User :
let number = 40;
let guess = 0;
do {
guess = parseInt(prompt("Guess the number"));
if(guess == number) {
alert("You Won!");
break;
}
} while(guess != 0);
Take “N” Arguments in a Function :
function addNumbers() {
let ans = 0;
for(let i = 0; i < [Link]; i = i + 1) {
ans = ans + arguments[i];
}
return ans;
}
Functions in JavaScript :
//plain function
function sayHello() {
[Link]("Hello");
}
//function with parameters
function add(a, b) {
[Link](a + b);
}
//these 5 and 10 are called parameters
//a and b in the function are called arguments
add(5, 10);
//return value from a function
function multiply(a, b) {
return a * b;
}
let a = multiply(10, 9);
[Link]("The product is:", a);
Arrow Functions :
//syntax
const sayHello = () => {
[Link]("Hello");
};
const add = (a, b) => {
return a + b;
};
[Link](add(2, 3));
//short form if one line
const add = (a, b) => a + b;
//no "arguments" function, use "spread" operator
const addNumbers = (...nums) => {
[Link](nums);
};
addNumbers(10, 22, 33, 44, 55);
//hoisting - function in memory before hand
//this works for normal functions only
//this won't work in case of arrow functions
sayHey();
const sayHey = () => {
[Link]("Hey");
};
//this will work
sayHey();
//"this" keyword
//normal function - this refers to the object
const obj = {
value = 20,
myFunction: function() {
[Link](this);
},
};
[Link]();
//arrow function - this refers to the entire window
High Order Function : It is a function that either takes another function as an argument or
returns a function as a result.
CallBack Function : It is a function that is passed as an argument to another function and is
executed at a later time. They are used for asynchronous operations like fetching data,
reading files, or handling events.
//synchronous callback
function add(a, b, callback) {
const result = a + b;
callback(result);
};
add(3, 4, function(sum) {
[Link](sum);
});
//asynchronous callback
setTimeout(function () {
[Link]("This is async callback!");
}, 2000);
//function can also return a another function
function add(a, b, cb) {
let result = a + b;
cb(result);
result () => [Link](result);
}
let resultFunction = add(2, 4, () => {});
resultFunction();
Arrays in JavaScript :
const students = ["Akshat", "Pandey", "Bennett"];
//print the array
[Link](students);
//print length of array
[Link]([Link]);
//print element of a specific index
[Link](students[0]);
//you can change the values in the array
//adds an element at the end
[Link]("University");
//array can have values of different data types
//find the index of a specific value
[Link]([Link]("Akshat"));
//delete the last element
[Link]();
//reverse the array
[Link]();
Higher Order Functions in Arrays
const students = ["Akshat", "Pandey", "Bennett"];
//this is the for(auto &it: arr) of javascript
[Link]((val) => [Link](val));
//map returns a new array, forEach does not
[Link]((val) => [Link](val));
//find element in array
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
let ans = [Link]((num) => num === 4);
[Link](ans);
//use to find an element - returns true or false
[Link](3);
//make change in the array
const newArr = [Link]((num) => num % 2 == 0);
[Link](newArr);
//subarray of an array
let newArr = [Link](1, 5);
let newArr2 = [Link](2); //2 se saare
//deletes a subarray
let newArr = [Link](1, 4);
[Link](numbers);
Document Object Model :
All the HTMl tags are called DOM elements in browser terms. Using JavaScript we can
create and delete these elements. Additionally, we can also add some interactivity in these
elements.
//creates a type of pop-up
alert("This is an Alert!");
//take input from user
prompt("What is your name?");
//document is our code
[Link](document);
//you can access the tags using this
[Link]([Link]);
//you can even make changes to the code
[Link] = "ABCD";
[Link]("This will be added at the end");
//usecase
const name = prompt("what is your name?")
[Link]("Hello" + name);
Query Selector :
//select the entire body
const body = [Link]("body");
const div = [Link]("div");
[Link](body);
//ques - if there are multiple "div" in code?
//ans - the first div will be affected
//returns the entire code as a string
[Link]([Link]);
//change the code of body
[Link] = '<h1> SuperPower </h1>';
//select and change element by "id"
const username = [Link]("#username");
[Link] = "Akshat Pandey";
[Link]([Link]);
//select class
const ele = [Link](".block");
[Link]([Link]); //andar ke tags returned
[Link]([Link]); //parent tag
//element ke parent ke saare children
[Link]([Link]);
//return an array (node list) of all
const ele = [Link](".block");
Document Get Element by ID : This is same as selecting an element by ID using query
selector, this is just a more specific way to do so.
const el = [Link]("username");
[Link] = "Akshat Pandey";
[Link](el);
//inject a class using js
[Link]("red-color", "underline");
[Link]([Link]);
//remove a class using js
[Link]("red-color");
//add inline css
[Link] = "underline";
[Link] = "blue";
//set attribute - aria = "123"
[Link]("aria", "123");
//remove element from DOM
[Link]();
DOM by Class Selector :
//returns multiple elements
const el = [Link]("block");
[Link](el);
//you have to loop over it, to make change in all
const ele = [Link]("block");
for(let i = 0; i < [Link]; i++) {
[Link](i).[Link] = "blue";
}
Events in JavaScript - Click Button :
//bad way
<button Click </button>
function handleButtonClick() {
[Link]("Button is clicked!")
alert("Clicked");
}
<button Cl </button>
//best way
<button id = "clickButton"> Click </button>
const el = [Link]("clickButton");
[Link]('click', function() {
[Link]("I am clicked!");
});
//change color to red on click + arrow function
const nameB = [Link]("name-block");
[Link]("click", () => {
[Link] = "red";
});
Create Elements Dynamically :
const button = [Link]("clickButton");
const container = [Link]("my-cont");
let count = 1;
[Link]("click", () => {
const el = [Link]("li");
[Link] = count;
[Link](el);
count++;
});
Promises, Async, Fetch and Await :
//this will return a promise
//jab ho jayege tab output aayege
//tab tak ke leye promise
// 1
let resultFromServer = fetch(
"url"
);
// 2 : best
async function getData() {
let resultFromServer = fetch(
"url"
);
[Link](resultFromServer);
}
getData();
//then -> result sahi aa gaya
//catch -> error aa gaya
//finally -> chalta hee chalte hai
fetch("url")
.then((data) => {
[Link](data);
})
.catch((error) => {
[Link](error);
});
[Link](result);
Local Storage
const button = [Link]('clickButton');
const uname = [Link]('in-username');
const user = [Link]('username');
[Link]('click', () => {
const value = [Link];
[Link]("name", value);
[Link]();
});
[Link]("load", () => {
const value = [Link]("name");
[Link] = value;
});
Set Timeout and Set Interval :
//only once
setTimeout(() => [Link]('hi'), 1000);
//keep repeating
setInterval(() => [Link]('hi'), 1000);
//stop the setInterval
let interval = setInterval(showTime, 1000);
[Link]("click", () => {
clearInterval(interval);
});
Closures in JavaScript : It is the combination of a function bundled together with reference
to its surrounding state. In other words, a closure gives you access to an outer function’s
scope from an inner function.
//basic example
function adder(num) {
function add(b) {
[Link](num + b);
}
return add;
}
const addTo5 = adder(5);
const addTo5 = adder(10);
addTo5(2); //7
addTo10(2); //12
Currying in JavaScript : It is a technique of transforming a function that takes multiple
arguments into a sequence of functions, each taking a single argument. Instead of calling
the function with all arguments at once, you call it with one argument at a time.
//normal function curry
function add(a) {
return function(b) {
return function(c) {
return a + b + c; }; };
};
[Link](add(2)(3)(10));
//arrow function curry
const add = (a) => (b) => (c) => a + b + c;
[Link](add(2)(3)(10));
Composition in JavaScript : It creates modular and maintainable code by chaining or
nesting functions to process data step-by-step.
function add(a, b) {
return a + b;
}
function square(val) {
return val * val;
}
function composeTwoFunctions(fn1, fn2) {
return function (a, b) {
return fn2(fn1(a, b));
};
}
const c2f = (fn1, fn2) => (a, b) => fn2(fn1(a, b));
const task = composeTwoFunctions(add, square);
[Link](task(2, 3));
//compose unlimited functions
function compose(...fns) {
return function(...values) {
[Link]((a, b) => b(a), value);
};
}
const composeAll = (...fns) => (...val) => [Link]((a, b) =>
b(a), val);
IIFE (Immediately Invoked Function Expression) : It runs as soon as it is defined. This
can be used to limit the number of global variables by directly using them in the IIFFE. You
can also execute async functions.
//basic example
(function add(a, b) {
[Link](a + b);
})(2, 3);
(() => [Link]("I am Es6"))();
//In a variable directly
const value = (() => 100)();
[Link](value);
Iterators and Generators : They bring the concept of iteration directly into the core
language and provide a mechanism for customizing the behaviour of for…of loops.
Iterator :
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;
const rangeIterator = {
next() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false };
nextIndex += step;
iterationCount++;
return result;
}
return { value: iterationCount, done: true };
},
};
return rangeIterator;
}
const iter = makeRangeIterator(1, 10, 2);
let result = [Link]();
while (![Link]) {
[Link]([Link]);
result = [Link]();
}
[Link]("Iterated over sequence of size:", [Link]);
Generator Function : While custom iterators are a useful tool, their creation requires careful
programming due to the need to explicitly maintain their internal state. Generator functions
provide a powerful alternative: they allow you to define an iterative algorithm by writing a
single function whose execution is not continuous. Generator functions are written using the
function* syntax.
function *makeRangeIterator(start = 0, end = Infinity, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
yield i;
}
return iterationCount;
}
x.