Javascript Notes
Javascript Notes
With the help of the typeof operator we can find the type of data a
variable is holding.
1. Scope
2. Hoisting
Difference in Chart
return userName;
class UserAccount {
constructor(name) {
this.name = name;
}
3. Snake Case (snake_case)
String Conversion
● String()
● .toString() (only works for non-null and non-undefined
values)
● Template literals
2. Number Conversion
● Number()
● parseInt() (for integers)
● parseFloat() (for decimals)
3. Boolean Conversion
String Coercion
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Divide
% Modulus (Reminder)
** Exponentiation (Power Operator)
Note: If the operators are on the same level , it will solve from left to
right.
Assignment Operator: The assignment operator works by taking the
value on the right-hand side (called the right operand) and storing it in
the variable on the left-hand side (called the left operand).
Operator Description
= Assign
+= Addition Assign
-= Subtraction Assign
*= Multiplication Assign
/= Divide Assign
%= Modulus (Reminder) Assign
**= Exponentiation (Power Operator)
Assign
Operator Description
++ Increment Operator
– Decrement Operator
1. if Statement
if (condition) {
// Code to execute if condition is true
}
2. if-else Statement
if (condition) {
// Code to execute if condition is true }
else {
// Code to execute if condition is false
}
if (condition1) {
// Code to execute if condition1 is true
}
else if (condition2) {
// Code to execute if condition2 is true
}
else {
//execute if none of the above conditions are true
}
4. switch Statement
switch (expression) {
case value1:
break;
case value2:
break;
default:
truthy & falsy : Everything in JS is true or false (in boolean context). This
doesn't mean their value itself is false or true, but they are treated as false
or true if taken in a boolean context.
alert() : is used to show a small popup message to the user. This popup
stops the rest of the webpage until the user clicks "OK." It’s often used to
give quick information or warnings.
for loop: a for loop is used to repeatedly execute a block of code as long
as a specified condition is true.
Syntax:-
let i = 1; // Initialization
console.log(i);
// Output: 1, 2, 3, 4 ,5
methods : a method in JavaScript is a function that is associated with an
object. Methods are used to perform actions on data or to interact with
objects in your code.
let firstName="Tony";
let lastName='Stark';
String index
Null : the null value represents the intentional absence of any object
value.
var a = null;
String all Methods
Creating an array:-
Array can be accessed by its index values, the array index starts from 0
and ends at size-1.
Array methods
Array constant: arr is a constant reference, but you can still modify the
array's contents (e.g., adding elements). However, you cannot reassign
arr itself to a new array.
let person = {
name: "John",
age: 30
};
Key Points
let person={
id : 101
};
console.log(person["myname"]);
console.log(person.name);
let person={
id : 101,
city : "indore"
};
console.log(person);
Note : We can’t use dot operators with variables to access object literals
values.
let person={
id : 101
};
Const : if we use const keyword with object literals , we can’t reassign the
same object name , but values can be changed using key name.
nested objects: object literals inside object literals is called nesting of
objects.
let person = {
name: "John",
age: 30,
address: {
country: "USA"
},
education: {
degree: "Bachelor's",
graduationYear: 2015
};
Math object : The Math object in JavaScript provides built-in properties
and methods for mathematical constants and functions.
Rounding Methods
1. Math.round(x)
Rounds x to the nearest integer.
2. Math.floor(x)
Rounds x down to the nearest integer.
3. Math.ceil(x)
Rounds x up to the nearest integer.
4. Math.trunc(x)
Truncates the decimal part of x (removes fractional digits).
5. Math.abs(x)
Returns the absolute value of x.
6. Math.pow(base, exponent)
Returns base raised to the power of exponent.
7. Math.sqrt(x)
Returns the square root of x.
8. Math.cbrt(x)
Returns the cube root of x.
9. Math.hypot(...values)
Returns the square root of the sum of squares of its arguments.
Logarithmic and Exponential
10. Math.exp(x)
Returns exe^xex, where eee is Euler's number.
11.Math.expm1(x)
Returns ex−1e^x - 1ex−1.
12. Math.log(x)
Returns the natural logarithm (base eee) of x.
13. Math.log10(x)
Returns the base-10 logarithm of x.
14. Math.log2(x)
Returns the base-2 logarithm of x.
15. Math.log1p(x)
Returns the natural logarithm of 1+x1 + x1+x.
Trigonometric
16. Math.sin(x)
Returns the sine of x (in radians).
17. Math.cos(x)
Returns the cosine of x (in radians).
18. Math.tan(x)
Returns the tangent of x (in radians).
19. Math.asin(x)
Returns the arcsine of x.
20. Math.acos(x)
Returns the arccosine of x.
21. Math.atan(x)
Returns the arctangent of x.
22. Math.atan2(y, x)
Returns the angle between the positive x-axis and the point (x, y).
Hyperbolic Trigonometry
23. Math.sinh(x)
Returns the hyperbolic sine of x.
24. Math.cosh(x)
Returns the hyperbolic cosine of x.
25. Math.tanh(x)
Returns the hyperbolic tangent of x.
26. Math.asinh(x)
Returns the hyperbolic arcsine of x.
27. Math.acosh(x)
Returns the hyperbolic arccosine of x.
28. Math.atanh(x)
Returns the hyperbolic arctangent of x.
Miscellaneous
29. Math.max(...values)
Returns the largest value from a list of numbers.
30. Math.min(...values)
Returns the smallest value from a list of numbers.
31. Math.random()
Returns a pseudo-random number between 0 (inclusive) and 1
(exclusive).
32. Math.sign(x)
Returns the sign of x:
○ 111 if positive
○ −1-1−1 if negative
○ 000 if zero
33. Math.clz32(x)
Returns the number of leading zero bits in the 32-bit binary
representation of x.
34. Math.imul(a, b)
Performs 32-bit integer multiplication of a and b.
35. Math.fround(x)
Returns the nearest 32-bit single precision float representation of x.
Constants
While not methods, these constants are available in the Math object:
● Math.PI (π)(\pi)(π)
● Math.E (Euler's number)
● Math.LN2 (Natural logarithm of 2)
● Math.LN10 (Natural logarithm of 10)
● Math.LOG2E (Base-2 logarithm of eee)
● Math.LOG10E (Base-10 logarithm of eee)
● Math.SQRT1_2 (Square root of 1/2)
● Math.SQRT2 (Square root of 2)
Random Number Generator 1 to 10 :-
Task for student write four digit OTP verification program using
HTML,CSS and JS.
Key Features:
1. Reusable: You can use the same function multiple times with
different inputs.
2. Organized: It makes your code easier to read and maintain.
3. Customizable: Functions can accept inputs (parameters) and give
back results (return values).
function greet() {
console.log("Welcome to india");
function greet(name) {
greet("Vishal Jain");
return keyword : In JavaScript, the return keyword is used inside a
function to send a value back to where the function was called. When
return is executed, the function stops running, and the specified value is
returned.
function add(a, b) {
console.log(result); // Output: 8
Scope : the scope determines the accessibility of variables, objects and
functions from different parts of the code.
function sumOfN(n)
for(let i=1;i<=n;i++){
sum+=i;
return sum;
console.log(sumOfN(10));
function sumOfN(n)
let sum=0;
for(let i=1;i<=n;i++){
sum+=i;
return sum;
console.log(sumOfN(10));
console.log(name1);
function outerFunction() {
function innerFunction() {
innerFunction();
function greet() {
console.log("Hello!");
// function body
};
Characteristics:
console.log("Hello!");
};
if (n === 0) return 1;
};
console.log("Hello!");
};
setTimeout(function() {
}, 2000);
High order functions : A function that does one or both:
function hello(myFunc,count){
for(let i=1;i<=count;i++){
myFunc();
function myFunc() {
console.log("namaste");
hello(myFunc,5);
IIFE
let calc ={
add : function(a,b){
return a+b;
},
sub : function(a,b){
return a-b;
},
mul : function(a,b){
return a*b;
},
console.log(calc.add(3,5));
console.log(calc.sub(20,5));
console.log(calc.mul(5,5));
Methods shorthand way to write
let calc ={
add(a,b){
return a+b;
},
sub(a,b){
return a-b;
},
console.log(calc.add(3,5));
console.log(calc.sub(20,5));
This keyword : The this keyword in JavaScript refers to the object that
is currently executing the code. Its value changes depending on where
and how it is used.
let student ={
subject : "PCM",
physics : 75,
math : 75,
chemistry : 75,
totalMarks(){
console.log(this);
console.log("Total Marks
:",this.physics+this.math+this.chemistry);
student.totalMarks();
Global Context If this is used in the global scope (outside of any function
or class), it refers to the global object. In a browser environment, the global
object is the window.Which is automatically created when the browser is
opened.Higher level is window object.
console.log(this);
Try and catch
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
Arrow functions
setInterval
forEach
In JavaScript, the forEach loop is a concise way to iterate over arrays.
Here's the syntax:
Map
The .filter() method in JavaScript creates a new array with elements that
pass a given test.It doesn’t modify the original array, only returns a new
filtered one.
every
reduce
The .reduce() method in JavaScript executes a reducer function on
each element of an array, returning a single value.
Default Parameters
Spread Operator
The spread operator (...) copies properties from one object to another.
Rest Parameters
Object Destructuring
Extract properties from an object into variables.
OOPS in JS
Benefits of Inheritance
Multilevel Inheritance
Note: if child & parent have same method, child’s method will
be used. [Method overriding]
Super keyword : the super keyword is used to call the
constructor of its parent class to access the parent properties
and methods.
Error
Calling parent class constructor
Calling Parent class method using super keyword
Encapsulation : Encapsulation in Object-Oriented
Programming (OOP) is the concept of hiding data and
restricting direct access to it. Instead, we use getter and setter
methods to control how the data is accessed and modified.
Abstraction : Abstraction is an Object-Oriented Programming
(OOP) principle that hides complex implementation details and
only exposes necessary functionalities. This makes the code
simpler to use and maintain.
Polymorphism : Polymorphism is an OOP concept that allows
multiple classes to have methods with the same name but
different behaviors.
document.getElementById()
document.getElementByClassName()
document.getElementByTagName()
Attribute manipulating
obj.getAttribute(‘attr’);
obj.setAttribute(‘attr’,’value’);
Styling manipulating
obj.style.backgroundColor=”Orange”;
Adding elements
Creating an Element
document.createElement(‘p’)
Parameters:
position (string) – Specifies where to insert the element. The
possible values are:
Removing Elements