Values and Variable in JavaScript
In JavaScript, values and variables are fundamental concepts that form the basis of
programming.
//* Values: A value is a piece of information that a program can work with. It can be a
number, text, true/false, or more complex data.
//* Variables: A variable is a container that holds a value. It has a name and can be used to
store and manipulate data in a program.
console.log("welcome to best js course "); //output: welcome to best js course.
var myAge = 30;
console.log(myAge); //output: welcome to best js course.
//! Let's test
var my_firstName = "John";
//? Explanation: This is a valid variable name. It starts with a letter, and the subsequent
characters include letters, numbers, and an underscore. Follows JavaScript naming rules.
var _myLastName$ = "Doe";
//? Explanation: This is a valid variable name. It starts with an underscore, and the
subsequent characters include letters, numbers, and a dollar sign. Follows JavaScript naming
rules.
var 123myAge = 25;
//? Explanation: This is not a valid variable name. It starts with a number, which is not
allowed as per JavaScript naming rules. Variable names cannot begin with a digit.
var $cityName = "New York";
//? Explanation: This is a valid variable name. It starts with a dollar sign, and the
subsequent characters include letters. Follows JavaScript naming rules.
var my@Email = "[email protected]";
//? Explanation: This is not a valid variable name. It includes the special character '@',
which is not allowed in JavaScript variable names. Only letters, numbers, underscores, and
dollar signs are allowed.
Data Types Section
Data types define the type of values that a variable can hold.
//? Types of Primitive Data types
//? Number: Represents numeric values, including integers and floating-point numbers.
Example:
var myFavNum = -5;
console.log(myFavNum); // Output: -5
//? String: Represents a sequence of characters enclosed in single or double quotes.
Example:
var myName = 'vinod';
console.log(myName); // Output: vinod
//? Boolean: Represents a logical entity with two values: true or false.
Example:
var isRaining = false;
var areYouAwesome = true;
console.log(isRaining); // Output: false
//? undefined: Represents the absence of a value or an uninitialized variable.
Example:
var vinod;
console.log(vinod); // Output: undefined
//? Null: Represents the absence of a value. It is often used to explicitly indicate that a
variable or object property has no assigned value.
Example:
var badMemories = null;
console.log(badMemories);
//? BigInt: Represents integers of arbitrary precision (available since ECMAScript 2020).
Example:
const bigNumber = 1234567890123456789012345678901234567890n;
//? Symbol: Represents a unique and immutable data type, often used to create unique
identifiers.
Example:
/const mySymbol = Symbol("description");
//! Data Types Interview Questions
/? 1: What is the difference between null and undefined in JavaScript❓
null: Imagine an Empty Box
// //* Explanation: Think of a variable as a box. When we say a box has null inside, it's like
having an empty box. The box exists, but there's nothing valuable or meaningful inside it.
// //? Example: You have a toy box, but if it's null, it means there are no toys inside. It's not
that the box is broken; it just doesn't have anything interesting in it right now.
// undefined: Imagine a Box That Wasn't Opened Yet
//* Explanation: Now, if we talk about undefined, it's like having a box that you haven't
opened yet. You know the box is there, but you haven't put anything inside or looked to see
what's in it.
//? Example: You have a gift box, and until you open it, you don't know what's inside. Right
now, it's undefined because you haven't checked or filled it with anything yet.
// Putting It Together
// Summary: So, null is like having an empty box on purpose, and undefined is like having a
box you haven't opened yet. Both tell us that there's nothing meaningful or known inside,
but they imply different reasons why.
//todo Real-life Comparison: If you have an empty lunchbox (null), it means you decided
not to put any food in it. If you have a closed lunchbox (undefined), it means you haven't
checked or filled it yet.
//? 2: What is the purpose of typeof operator in JavaScript❓
var myName = 1;
console.log(myName); // Output: 1
console.log(typeof myName); // Output: number
//? 3: What is the result of `typeof null` in JavaScript❓
var badMemories = null;
console.log(badMemories); // Output: null
console.log(typeof null); // Output: "object"
//? 4: What are primitive data types in JavaScript❓
//? 5: Convert a string to a number?
We just need to add the '+' sign before the string
Example:
var myFavNum = "10";
console.log(typeof +myFavNum); // Output: number
console.log(typeof Number(myFavNum)); // Output: number
//? 6: Convert a number to a string?
We just need to add an empty string after the number
Example:
var str = 5;
console.log(typeof str);// Output: string (but this line is a bit confusing)
//? 7: Explain the concept of truthy and falsy values in JavaScript. Provide examples.❓
In JavaScript, values are either considered "truthy" or "falsy" when evaluated in a boolean
context.
//? Truthy values are treated as true when used in conditions. Examples include:
👉 true
👉 Any non-empty string ("hello")
👉 Any non-zero number (42)
👉 Arrays and objects, even if they're not empty
// Falsy values are treated as false in boolean contexts. Examples include:
👉 false
👉 0 (zero)
👉 '' (an empty string)
👉 null
👉 undefined
👉 NaN (Not a Number)
//? 8: To check if a non-empty string is truthy or falsy in JavaScript, we can directly use if
statement.
var myName = -5;
if (true) {
console.log("this is truthy value");
} else {
console.log("its a falsy value");
}
Output:this is truthy value
//* ========== Data Types End Section ==========
//todo ---------------- todo Bonus ----------------------
//* ========== parseInt & parseFloat Section ==========
//? parseInt and parseFloat are both functions in JavaScript used for converting strings to
numbers, but they have different use cases.
//* parseInt: Definition: parseInt is used to parse a string and convert it to an integer (whole
number).
const myString = "42";
const myNumber = parseInt(myString);
console.log(myNumber); // Output: 42
const myString = "42.5";
const myNumber = parseInt(myString);
console.log(myNumber); // Output: 42
//* parseFloat: Definition: parseFloat is used to parse a string and convert it to a floating-
point number (decimal number).
const myString = "42.5";
const myNumber = parseFloat(myString);
console.log(myNumber); // Output: 42.5
//TODO Key Differences:
//? parseInt is used for converting to integers and ignores anything after the decimal point.
//? parseFloat is used for converting to floating-point numbers, preserving the decimal part.
//? Both functions will attempt to convert as much of the string as possible until an invalid
character is encountered.
//! Here are more examples
console.log(parseInt("123"));
// // Output:123 (default base-10)
console.log(parseInt("123", 10)); // // Output:123 (explicitly specify base-10)
console.log(parseInt(" 123 ")); // // Output:123 (whitespace is ignored)
console.log(parseInt("077"));// Output: 77
console.log(parseFloat("077"));// Output: 77(leading zeros are ignored)
console.log(parseInt("1.9")); // Output: 1
+console.log(parseFloat("1.9"));// Output: 1 (decimal part is truncated)
//! When we will not get an Output
console.log(parseInt("&123")); // Output: NaN
console.log(parseInt("-123")); // Output: -123
/console.log(parseInt("xyz"));// Output: NaN
// NaN (input can't be converted to an integer)
//? What is the purpose of the NaN value in JavaScript❓
//? NaN stands for "Not a Number" and is returned when a mathematical operation
doesn't yield a valid number.
//? Also, to check whether a value is number or not we can use isNaN() function.
console.log(isNaN("vinod"));
// Output: true
console.log(parseInt("xyz"));
// Output: NaN
console.log(parseInt("@#$"));
// Output: NaN
// //! NaN === NaN, Why is it false ❓
if (NaN == NaN) {
console.log("both are equal ");
} else {
console.log("not equal");
}
// Output: not equal
// Explanation: NaN is never equal to NaN
//* ========== parseInt & parseFloat End Section ==========
//* Data Types Section - part 2
//* Concatenation in JavaScript
//? In JavaScript, the + sign is not only used for arithmetic addition but also for string
concatenation. When the + operator is used with strings, it concatenates the strings
together.
//? It's important to note that if any operand of the + operator is a string, JavaScript will
treat the other operands as strings as well, resulting in string concatenation. If both
operands are numbers, the + operator performs numeric addition.
const str = "Hello " + "World";
console.log(str);// Hello World
//* Type coercion is the automatic conversion of "values" from one data type to another.
//? It is a fundamental part of JavaScript and can be used to make code more readable and
efficient.
//? There are two types of coercion in JavaScript: implicit and explicit. Implicit coercion
happens automatically, while explicit coercion is done manually by the programmer.
//! It's worth noting that type coercion can lead to unexpected results, so it's essential to be
aware of how JavaScript handles these situations.
let sum = "5" + 10;
console.log(sum);
//Output: 510
//* Tricky Interview Questions
console.log(10 + "20");
// 👉 Output: "1020"
console.log(9 - "5");
// 👉 Output: 4
console.log("Java" + "Script");
// 👉 Output: "JavaScript"
console.log("Java" + "Script");
// 👉 Output: "JavaScript"
console.log(" " + " ");
// 👉 Output: " "
let sum = " " + 0;
console.log(typeof sum);
// 👉 Output: "string"
console.log("vinod" - "thapa");
// 👉 Output: NaN
console.log(true + true);
// 👉 Output: 2
console.log(true + false);
// 👉 Output: 1
console.log(false + true);
// 👉 Output: 1
console.log(false - true);
// 👉 Output: -1
//* ===================================
//* EXPRESSIONS AND OPERATORS Section
//* ====================================
//? 1st we will see what is expression means and also what is operand and operator in any
expression?
Types of Operators in JS
Assignment operators
Arithmetic operators
In arithmetic we increment and decrement operator.
Comparison operators
Logical operators
String operators
Conditional (ternary) operator
//* 1: Assignment operators
//? Assignment operators in programming are symbols used to assign values to variables.
They take the value on the right side of the operator and assign it to the variable on the left
side.
// examples
var myFavNum = 15;
Assigns the value 15 to the variable myFavNum
var channelName = 'thapa tecnical'
//* 2: Arithmetic operators
//? Arithmetic operators in programming perform basic mathematical operations on
variables or values. They include addition, subtraction, multiplication, division, and
modulus.
//? Addition (+): Adds two values or variables.
// Example:
var x = 5;
var y = 10;
var sum = x + y;
console.log(sum); // 👉 Output: 15
//? Subtraction (-): Subtracts the right operand from the left operand.
// Example:
var a = 10;
var b = 7;
var difference = a - b;
console.log(difference); // 👉 Output: 3
//? Multiplication (*): Multiplies two values or variables.
// Example:
var p = 4;
var q = 6;
var product = p * q;
console.log(product); // 👉 Output: 24
//? Division (/): Divides the left operand by the right operand.
// Example:
var m = 15;
var n = 3;
var quotient = m / n;
console.log(quotient); // 👉 Output: 5
//? Modulus (%): Returns the remainder when the left operand is divided by the right
operand.
// Example:
var c = 17;
var d = 5;
var remainder = c % d;
console.log(remainder); // 👉 Output: 2
//* Challenge Time
//! What will be the Output 🤔💭
var result = "hello" / 2;
console.log(result); // 👉 Output: NaN
//* InterView Question
var result = 0.1 + 0.2;
console.log(result.toFixed(2)); // 👉 Output: "0.30"
// when working with floating-point numbers in JavaScript, consider using methods like
toFixed() when precise decimal representation is necessary.
var result = 55 * "hello";
console.log(result); // 👉 Output: NaN
//* 3: String Operators
//? There are a few ways to concatenate strings in JavaScript. The most common way is to
use the + operator. For example, to concatenate the strings "Hello" and "World", you would
use the following code:
var str1 = "Hello";
var str2 = "World";
var str3 = str1 + str2;
console.log(str3); // 👉 Output: "HelloWorld"
//* InterView Question
console.log("5" + 3); // 👉 Output: "53"
//* 4: comparison operators
//? Comparison operators in JavaScript are used to compare values and return a Boolean
result (true or false).
//? Equal (==): Checks if two values are equal, performing type coercion if necessary.
console.log(5 == "5"); // 👉 Output: true
//? Strict Equal (===):Checks if two values are equal without performing type coercion.
console.log(5 === "5"); // 👉 Output: false
//? Not Equal (!= 👉 ! =):Checks if two values are not equal, performing type coercion if
necessary.
console.log(5 != 5); // 👉 Output: false
//? Greater Than (>):Checks if the value on the left is greater than the value on the right.
// Example: 10 > 5 evaluates to true.
console.log(5 > 2); // 👉 Output: true
//? Less Than (<):Checks if the value on the left is less than the value on the right.
// Example: 5 < 10 evaluates to true.
console.log(5 < 10); // 👉 Output: true
//? Greater Than or Equal To (>=):
// Checks if the value on the left is greater than or equal to the value on the right.
// Example: 10 >= 10 evaluates to true.
console.log(10 <= 10); // 👉 Output: true
//? Less Than or Equal To (<=):
// Checks if the value on the left is less than or equal to the value on the right.
// Example: 5 <= 10 evaluates to true.
// console.log(5 >= 10); // 👉 Output: false
//* InterView Question
//! What is the difference between == and === operators in JavaScript❓
//? The equality == operator is a comparison operator that compares two values and
returns true if they are equal. The strict equality === operator is also a comparison operator,
but it compares two values and returns true only if they are equal and of the same type.
let num1 = 1;
let num2 = "1";
if (num1 === num2) {
console.log("equal");
} else {
console.log("not equal");
}// 👉 Output: "not equal"
//* 5: Logical operators in JavaScript
//* There are three main logical operators: && (logical AND), || (logical OR), and ! (logical
NOT).
//? Logical AND (&&): Returns true if both operands are true, otherwise, it returns false.
// Example:
var x = 5;
var y = 10;
console.log(x > 0 && y < 0); // 👉 Output: false
//? Logical OR (||): Returns true if at least one of the operands is true, otherwise, it returns
false.
// Example:
var a = 15;
var b = 0;
console.log(a > 10 || b > 10); // 👉 Output: true
//? Logical NOT (!):Returns true if the operand is false, and false if the operand is true.
// Example:
var isOpen = false;
console.log(!isOpen); // 👉 Output: true
//* InterView Question
//? Combining logical operators allows you to create complex conditions:
//! Q: Write a program that determines if a person is eligible to drive based on their age
being greater than or equal to 18 and having a valid driver's license❓
var age = 19;
var hadDrivingLicense = false;
console.log(age >= 18 && hadDrivingLicense); // 👉 Output: false
//! How would the result change if hasDriverLicense was set to false❓
//* 6: Unary operator
//? Unary operators in JavaScript are operators that work with only one operand. They
perform various operations such as negation, incrementing, decrementing, type conversion,
and more.
//? Unary Plus (+): Converts its operand into a number. If the operand is not already a
number, it attempts to convert it.
console.log(+3); // 👉 Output: 3
console.log(+"5"); // 👉 Output: 5
//? Unary Negation (-): Negates its operand, converting non-numbers into numbers and
then negating them.
console.log(-5); // 👉 Output: -5
console.log(-"3"); // 👉 Output: -3
//? Prefix Increment (++x) and Prefix Decrement (--x): In prefix form, the value of the
operand is first incremented or decremented, and then the result is returned.
var x = 5;
var y = --x;
console.log(y); // 👉 Output: 4
console.log(x); // 👉 Output: 4
//? Postfix Increment (x++) and Postfix Decrement (x--): In postfix form, the value of the
operand is first returned, and then it is incremented or decremented.
x = 5;
y = x++;
console.log(y); // 👉 Output: 5
console.log(x); // 👉 Output: 6
//todo The current value of x (which is 5) is assigned to y. After the assignment, the value of
x is then incremented by 1.
//* 7: Conditional (ternary) operator
//? syntax: condition ? expressionIfTrue : expressionIfFalse;
// ! write a program to check if the candidates isEligibleForDrive or not? Age must be equal
to or greater then 18.
var age = 19;
var result = age >= 18 ? "Yes" : "No";
console.log(result); // 👉 Output: "Yes"
//! Q: Let say you have a variable score representing a student's exam score. If the score is
greater than or equal to 60, the student passes; otherwise, they fail. Use the conditional
(ternary) operator to determine the result and store it in a variable called result. Log the
result to the console❓
var score = 99;
var result = score >= 60 ? "Pass" : "Fail";
console.log(result); // 👉 Output: "Pass"
//* Combined Interview Questions
console.log(typeof ("5" - 3));
// 👉 Output: "number"
console.log(2 < 12 < 5);
// 👉 Output: true
// Reason: 2 < 12 → true → true is coerced to 1 → 1 < 5 → true
console.log("20" + 10 + 10);
// 👉 Output: "201010"
// Explanation: "20" + 10 → "2010", then + 10 → "201010"
//* Conditional statement Section
//* If Statement
//? If Else: The if...else statement executes a statement if a specified condition is truthy. If
the condition is falsy, another statement in the optional else clause will be executed.
//? Syntax
if (condition) {
Code to be executed if the condition is true
} else {
Code to be executed if the condition is false }
//? Let check the temperature
var temperature = 25;
if (temperature > 30) {
console.log("lets go to beach");
} else {
console.log("tv dekhte hai yr");}
// 👉 Output: tv dekhte hai yr
//? We can also use an else if clause to check additional conditions:
var temperature = 15;
if (temperature >= 30) {
console.log("lets go to beach");
} else if (temperature >= 20 && temperature < 30) {
console.log("tv dekhte hai yr");
} else {
console.log("kambhal oodo so jawo");}
👉 Output: kambhal oodo so jawo
//* Interview Question//*
//! Requirements:
//? If the person is 18 years or older, a citizen, and registered to vote, display a message
saying they are eligible to vote.
//? If the person is younger than 18, not a citizen, or not registered to vote, display a
message saying they are not eligible to vote.
//? If the person is 18 or older but not a citizen, display a message saying they are not
eligible due to citizenship status.
//? If the person is 18 or older, a citizen, but not registered to vote, display a message saying
they are not eligible due to registration status.
//? Extended voting eligibility checker with additional conditions
Assume the user's age, citizenship status, and registration status as inputs
let userAge = 19;
let isCitizen = true; // Assume true for citizen, false for non-citizen
let isRegistered = true; // Assume false for not registered, true for registered
// //! Check eligibility using if...else statements with multiple conditions
if (userAge >= 18) {
if (isCitizen) {
if (isRegistered) {
console.log("You are eligible to vote");
} else {
console.log("You are not eligible due to registration status");}
} else {
console.log("you are not eligible due to citizenship status");}
} else {
console.log("You are not eligible to vote (Younger)"); }
//* Interview Questions
//! 1: Write a program to check if a number is even or odd.
var num = "7";
if (num % 2 === 0) {
console.log("Num is even");
} else {
console.log("Num is odd");
}// 👉 Output: Num is odd
//! 2: Write a program to check if a number is prime.
//todo Prime numbers are numbers that have only 2 factors: 1 and themselves.
//? All prime numbers greater than 2 are odd.
//? However, not all odd numbers are prime.
var num = 13;
var isPrime = true;
for (var i = 2; i < num; i++) {
if (num % i === 0) {
isPrime = false;
break; }}
if (isPrime) {
console.log("Num is prime");
} else {
console.log("Num is not prime");}
// 👉 Output: Num is prime
//! 3: Write a program to check if a number is positive, negative, or zero.
var num = -10;
if (num === 0) {
console.log("NUm is zero");
} else if (num > 0) {
console.log("NUm is positive ");
} else {
console.log("NUm is negative ");}
// 👉 Output: NUm is negative
//* Switch Statement
//? Switch Statement: The switch statement is used to perform different actions based on
different conditions.
//? Syntax:
switch (expression) {
case value1:
Code to be executed if expression === value1
break;
case value2:
Code to be executed if expression === value2
break;
More cases can be added as needed
default:
Code to be executed if none of the cases match }
//todo let's see the example
//! Explain how the switch statement works and what will be the output when the variable
day is set to different values.
var day = "Friday";
switch (day) {
case "Monday":
console.log("today is monday");
break;
case "Friday":
console.log("omg lets have party today");
break;
case "Sunday":
console.log("Lets go to movie");
break;
default:
console.log("no condition match"); }
// ? Challenge time
//! Write a JavaScript switch statement that takes a variable areaOfShapes representing
different shapes, and based on its value, calculates and logs the area of the corresponding
shape. Consider three shapes: 'Rectangle,' 'Circle,' and 'Square.' For 'Rectangle,' use
variables a and b as the sides; for 'Circle,' use a variable r as the radius; and for 'Square,' use
variable a as the side length. If the provided shape is not recognized, log a message saying,
'Sorry the shape is not available.' Test your switch statement with areaOfShapes set to
'Square' and sides a and b set to 5 and 10, respectively. Ensure that the correct area (25 in
this case) is logged to the console.
var areaOfShapes = "square";
var a = 5;
var b = 10;
var result;
switch (areaOfShapes) {
case "square":
result = a * a;
console.log(result);
break;
case "rectangle":
result = a * b;
console.log(result);
break;
case "circle":
var r = 2;
result = 3.142 * (r * r);
console.log(result);
break;
default:
console.log("No shape matches");
}// 👉 Output: 25
//! Question: Explain the purpose of the code. What is it calculating based on the values
of areaOfShapes, a, and b?
//? The code calculates and logs the area of different shapes (rectangle, circle, square)
based on the value of the areaOfShapes variable.
//! Question: What will be the output if areaOfShapes is set to "Square" and why?
//? The output will be the square of the variable a (25) since the case matches "Square."
//! Question: Why is there a break statement after each case in the switch statement?
//? The break statement is used to exit the switch statement after the corresponding case is
executed, preventing fall-through to subsequent cases.
//! Question: If areaOfShapes is set to "Circle," what will be logged to the console, and
why is the variable r defined within the case block?
//? The output will be the area of a circle with radius r (28.26) since the case matches
"Circle," and r is defined within the case block.
//! Question: What will happen if areaOfShapes is set to a shape that is not covered by
any of the existing case statements?
//? The default case logs "Sorry, the shape is not available" if areaOfShapes is set to a shape
not covered by any existing case.
//! Question: How does the switch statement handle the flow of control based on the
value of areaOfShapes?
//? The switch statement evaluates the value of areaOfShapes and executes the code block
corresponding to the matching case. The break statements ensure that only the relevant
code block is executed.
//* While Loop
// ? While Loop: A while loop in JavaScript is a control structure that repeatedly executes a
block of code as long as a specified condition remains true. The loop continues iterating
while the condition is true, and it terminates when the condition becomes false.
while (condition) {
Code to be executed as long as the condition is true}
//* Simple while loop to count from 1 to 10 🧑💻
var num = 1;
while (num <= 10) {
console.log(num);
num++; }// Output:1 2 3 4 5 6 7 8 9 10
//! practice 🧑💻
//? let's create a table of 5
// 5*1 = 5
// 5*2 = 10
var num = 1;
while (num <= 10) {
console.log("5 * " + num + " = " + 5 * num);
console.log(`5 * ${num} = ${5 * num}`);
num++;}
// Output:
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40
5 * 9 = 45 5 * 10 = 50
//* Do-While Loop
//? Do...While Loop: A do...while loop in JavaScript is similar to a while loop, but it
guarantees that the loop body will be executed at least once before checking the loop
condition. The loop continues to execute while the specified condition is true, and it
terminates when the condition becomes false.
// Syntax: do {
// // Code to be executed at least once
// } while (condition);
//* Simple do...while loop to count from 1 to 10 🧑💻
var num = 1;
while (num <= 10) {
console.log(num);
num++;}
var num = 1;
do{ console.log(num);
num++;
}while (num <= 10) // Output: Same as while loop counting 1 to 10
//? Common Use Cases:
//? When you want to guarantee the execution of the loop body at least once.
//? When the number of iterations is not known beforehand, and you want to validate the
condition after the first iteration.
//? Example: Validating User Input with a Do...While Loop(user need to write a valid
number) 🧑💻
// let userInput;
let positiveNumber;
do {
userInput = prompt("enter any positive number");
positiveNumber = parseFloat(userInput);
} while (isNaN(positiveNumber) || positiveNumber < 0);
console.log("You entered a valid positive number:", positiveNumber);
//* For Loop
//? For Loop: A for loop in JavaScript is a control flow statement that allows you to
repeatedly execute a block of code a specified number of times. It's particularly useful when
you know the exact number of iterations needed.
// example: for (initialization; condition; iteration) {
// // Code to be executed in each iteration
// }
// Initialization: Executed before the loop starts. Often used to initialize a counter variable.
// Condition: Evaluated before each iteration. If false, the loop terminates.
// Iteration: Executed after each iteration. Typically used to update the loop control
variable.
//* Simple for loop to count from 1 to 10
var num = 1;
do {
console.log(num);
num++;
} while (num <= 10);
for (var num = 1; num <= 10; num++) {
console.log(num);}
//? Key Point:
// The initialization, condition, and iteration expressions are optional. You can omit any or
all of them, but you must include the semicolons.
//* The code for (;;) {} represents an infinite loop in JavaScript. This construct is commonly
used when you want a loop to run indefinitely or until a break statement is encountered
within the loop. It's equivalent to while (true) {}.
//* use case: Game Development:
//? In game development, an infinite loop can be used to continuously update and render
game frames until a specific condition (e.g., game over) is met.
// for (;;) {
// // Update game logic and render frames
// }
//? Common Use Cases:
When you know the exact number of iterations needed.
Iterating over elements in an array.
Performing a task a specific number of times.
//! Calculate the sum of numbers from 1 to 10 using a for loop 🧑💻
var sum = 0;
for (var num = 1; num <= 10; num++) {
sum = sum + num;
}
console.log(sum); // Output: 55
//! Example 3: Generating a times table of 5 with a for loop.
var num = 1;
while (num <= 10) {
console.log("5 * " + num + " = " + 5 * num);
// console.log(`5 * ${num} = ${5 * num}`);
num++;}
for (var num = 1; num <= 10; num++) {
console.log("5 * " + num + " = " + 5 * num);
}
//! Homework ➡️JavaScript program to print table for given number (8,9,12,15) using for
Loop?
//? More Practice
//!1: program To check if a year is a leap year🧑💻
//? If a year is divisible by 4 and not divisible by 100, or
//? If a year is divisible by 400,
// then it is a leap year. Otherwise, it is not a leap year.
var year = 2020;
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log(year, "it's a leap year");
} else {
console.log(year, "it's not a leap year");}// 👉 Output: 2020 it's a leap year
//! 2: Drawing Patterns with Asterisks: 🧑💻
//* i\j 1 2 3 4 5
//* ----------------------------
//* 1 * - - - -
//* 2 * * - - -
//* 3 * * * - -
//* 4 * * * * -
//* 5 * * * * *
for (var i = 1; i <= 5; i++) {
var pattern = "";
for (var j = 1; j <= i; j++) {
pattern = pattern + " *";
}console.log(pattern);}
//* Function in JavaScript
//? In JavaScript, a function is a block of reusable code that performs a specific task or set of
tasks. Functions are used to organize code into modular and manageable pieces, promote
code reuse, and make programs more readable.
// 3 students at a same time wants to find the sum of two numbers
var a = 5, b = 10;
var sum1 = a + b;
console.log(sum1); //output: 15
var a = 15, b = 15;
var sum2 = a + b;
console.log(sum2); // output: 30
var a = 55, b = 15;
var sum3 = a + b;
console.log(sum3); // output: 70
// lets make a reusable code
function sum(a, b) {
return a + b;}
console.log(sum(5, 5)); // output: 10
console.log(sum(15, 50)); // output: 65
console.log(sum(25, 750)); // output: 775
//* Function Declaration:
//? Declare a function using the function keyword, followed by the function name,
parameters (if any), and the function body.
//? This step defines the function and specifies what code should be executed when the
function is called.
function greet() {
console.log("Hello Guys, Welcome to Thapa Technical JS Course ");
}
greet();
// Output:Hello Guys, Welcome to Thapa Technical JS Course
//* Function Invocation (Calling a Function):
//?After declaring a function, you can invoke or call it by using its name followed by
parentheses.
//? If the function has parameters, provide values (arguments) for those parameters inside
the parentheses.
//? How to call a function
greet();
//! 1. Write a function to find the sum of two numbers.
//todo Tips "1st declare the function & then call it" In JavaScript, it's a good practice to
declare (define) your functions before you call them. This ensures that the function is
available for use when you try to call it.
// Function definition
function sum() {
var a = 15,
b = 10;
console.log(a + b);}
// Calling the function
// sum();
//* Function Parameter:
//? A function parameter is a variable that is listed as a part of a function declaration. It acts
as a placeholder for a value that will be provided when the function is called. Parameters
allow you to pass information into a function, making it more versatile and reusable.
//Syntax: function functionName(parameter1, parameter2, ...params) {
// // Function body
// // Code to be executed when the function is called
// }
//* Function Argument:
//? A function argument is a value that you provide when you call a function. Arguments are
passed into a function to fill the parameters defined in the function declaration.
//? syntax:
//? functionName(argument1, argument2, ...);
//! Practice Time
//? Let's say we want to greet students with one same line
//! Write a JavaScript program that defines a function called greet to welcome individuals to
the Thapa Technical JS Course. The function should take a name parameter and output the
message "Hello [name], Welcome to Thapa Technical JS Course". Call the function twice,
once with the argument "vinod" and once with the argument "ram".
function greet(name) {
console.log("Hello " + name + ", Welcome to Thapa Technical JS Course");}
greet("ram");
greet("sita");
Output:
Hello ram, Welcome to Thapa Technical JS Course
Hello sita, Welcome to Thapa Technical JS Course
//! 1. Write a function to find the sum of two numbers with parameters.
function sum(a, b) {
console.log(a + b);}
sum(5, 10); // Output: 15
sum(50, 10); // Output: 60
//* Function expressions
//? A function expression is a way to define a function as part of an expression. It can be
either named or anonymous. If it's named, it becomes a named function expression.
var result = function sum(a, b) {
console.log(a + b); };
// result(10, 15); // Output: 25
//* Anonymous Function
//? An anonymous function is a function without a name. It can be created using either a
function expression or a function declaration without a specified name.
var result = function (a, b) {
console.log(a + b);}
// result(10, 15); // Output: 25
//* Return Keyword
//? Return Keyword: In JavaScript, the return statement is used within a function to specify
the value that the function should produce or provide back to the code that called it. The
return statement stops the execution of a function and sends a value back to the caller
//? Syntax
return expression;
//! Example 1: Returning a Sum of two number
function sum(a, b) {
return a + b;
console.log("hello I am function"); // Unreachable code
}
var result = sum(5, 5); // result = 10
console.log("the sum of two number is " + result); // the sum of two number is 10
console.log(sum(5, 5)); // 10
console.log(sum(15, 50)); // 65
console.log(sum(25, 750)); // 775
//* IIFE - immediately invoked function expression
//? An IIFE, or Immediately Invoked Function Expression, is a JavaScript function that is
defined and executed immediately after its creation. It is a way to create a self-contained
block of code that doesn't interfere with the surrounding code and executes immediately
// Syntax
// (function () {
// // code to be executed
// })();
var result = (function (a, b) {
console.log(a + b);
return a + b;
})(5, 10);
console.log("the sum of two number is " + result); // Output: 15
the sum of two number is 15
// !Practice Time ( IIFE with Parameters)
//? Interview Questions
//! Question 1: Calculator Function
//! Write a JavaScript function calculator that takes two numbers and an operator as
parameters and returns the result of the operation. The function should support addition,
subtraction, multiplication, and division.
console.log(calculator(5, 2, '+')); // Output: 7
console.log(calculator(8, 4, '-')); // Output: 4
console.log(calculator(10, 2, '/')); // Output: 5
const calculator = (num1, num2, operator) => {
let result;
switch (operator) {
case "+":
return num1 + num2;
case "-":
result = num1 - num2;
return result;
case "*":
result = num1 * num2;
return result;
case "/":
if (num2 === 0) {
return "0 is not allowed";
} else {
result = num1 / num2;
return result;
}
default:
return "no operator found";}};
console.log(calculator(5, 2, "+")); // Output: 7
console.log(calculator(8, 4, "-")); // Output: 4
console.log(calculator(10, 0, "/")); // Output: 5
//! Reverse a String:
//! Write a function to reverse a given string without using built-in reverse methods.
const isReverse = (str) => {
let reverse = "";
for (let char = str.length - 1; char >= 0; char--) {
reverse = reverse + str[char];
}
return reverse;
};
console.log(isReverse("vinod thapa"));
// Output: apaht doniv
//! Palindrome Check:
//! Create a function to determine if a given string is a palindrome (reads the same
backward as forward).
const isPalindrome = (str) => {
let reverse = "";
for (let char = str.length - 1; char >= 0; char--) {
reverse = reverse + str[char];
}
return str === reverse ? true : false;
};
console.log(isPalindrome("level")); // Output: true
//* ARRAYS IN JAVASCRIPT
//! Iterable - object where you can use the for-of loop
//! Array-like object - Any object with length property and use indexes to access items
//! Arrays as Objects: Arrays in JavaScript are a specific type of object that has numeric
keys (indices) and a length property. The indices are automatically maintained, and the
length property is automatically updated when you add or remove elements from the array.
//! typeof Operator: The typeof operator in JavaScript returns "object" for both arrays and
regular objects.
//* JavaScript Array is a data structure that allows you to store and organize multiple values
within a single variable. It is a versatile and dynamic object. It can hold various data types,
including numbers, strings, objects, and even other arrays. Arrays in JavaScript are zero-
indexed i.e. the first element is accessed with an index 0, the second element with an index
of 1, and so forth.
//* Creating Arrays:
//? Arrays in JavaScript can be created using the Array constructor or with array literals
(square brackets []).
//? Using Array constructor
let fruits = new Array('apple', 'orange', 'banana')
//? Using array literal
let fruits = ["apple", "orange", "banana"];
console.log(fruits);//output: ["apple", "orange", "banana"]
//? we can also create an empty array
let arr = [];
console.log(typeof arr); //output: object
//* Accessing Elements:
//?👉 Accessing Elements: Array elements are accessed using zero-based indices.
let fruits1 = ["apple", "orange", "banana"];
console.log("fruits[3]:", fruits1[3]); // undefined (no element at index 3)
console.log('fruits["apple"]:', fruits1["apple"]); // undefined (invalid key)
//* Modifying Elements:
//?👉 Modifying Elements: You can modify array elements by assigning new values to
specific indices.
let fruits2 = ["apple", "orange", "banana"];
fruits2[2] = "mango";
console.log("Modified Fruits:", fruits2); // ["apple", "orange", "mango"]
//* Array Traversal / Iterating Over Arrays
let fruits = ["apple", "orange", "mango", "grapes", "banana"];
//? 1: for of loop , also known as iterable
//* for...of Loop: The for...of loop is used to iterate over the values of an iterable object,
such as arrays, strings, or other iterable objects.
for (let item of fruits3) {
console.log(item); // apple, orange, mango, grapes, banana
}
for (let i = 0; i < fruits3.length; i++) {
console.log(fruits3[i]); // apple, orange, mango, grapes, banana
}
//? 2: for in loop
//* for...in Loop: The for...in loop is used to iterate over the properties (including indices) of
an object.
for (let item in fruits3) {
console.log(item); // 0, 1, 2, 3, 4 (indexes)
}
// ? 3: forEach Method
//* The arr.forEach() method calls the provided function once for each element of the array.
The provided function may perform any kind of operation on the elements of the given
array.
const fruits = ["apple", "orange", "banana"];
const myMapArr = fruits.map((curElem, index) => {
return `${curElem} ${index}`;});
console.log(myMapArr);
["apple 0", "orange 1", "banana 2"]
// ? 4: map function
//* map() creates a new array from calling a function for every array element. map() does
not change the original array.
const fruits = ["apple", "orange", "banana", "grapes", "mango"];
const myMapArr = fruits.map((curElem, index, arr) => {
return ` my fav fruit is ${curElem} `;
// console.log(arr);
})
console.log(myMapArr);
// Output: [
// " my fav fruit is apple ",
// " my fav fruit is orange ",
// " my fav fruit is banana ",
// " my fav fruit is grapes ",
// " my fav fruit is mango "
// ]
console.log(fruits);
// Output: ["apple", "orange", "banana", "grapes", "mango"]
//! Practice Time
// write a program to Multiply each element with 2
const numbers = [1, 2, 3, 4, 5];
// forEach - Performs an action on each element
numbers.forEach((curElem) => {
console.log(curElem * 2);
});
// Output:
// 2
// 4
// 6
// 8
// 10
// map - Creates a new array with transformed elements
const doubleValue = numbers.map((curElem) => {
return curElem * 2;
});
console.log(doubleValue);
// Output: [2, 4, 6, 8, 10]
//* Key Differences
//! Return Value:
//? forEach: It doesn't return a value. The forEach method is used for iterating over the
elements of an array and performing a side effect, such as modifying the array or
performing a task for each element.
//? map: It returns a new array containing the results of applying a function to each
element in the original array. The original array remains unchanged.
//! Chaining:
//? forEach: It doesn't return a value, so it cannot be directly chained with other array
methods.
//? map: Since it returns a new array, you can chain other array methods after using map.
//* Use Case:
//? forEach: Used when you want to iterate over the array elements and perform an action
on each element, but you don't need a new array.
//? map: Used when you want to create a new array based on the transformation of each
element in the original array.
//* How to Insert, Add, Replace and Delete Elements in Array(CRUD) - p1
//? 👉 How to Insert, Add, Replace and Delete Elements in Array(CRUD)
let fruits = ["apple", "orange", "mango", "grapes", "banana"];
//? 1: push(): Method that adds one or more elements to the end of an array.
console.log(fruits.push("guava"));
// Output: 6 ← New length of array
console.log(fruits);
// Output: ["apple", "orange", "mango", "grapes", "banana", "guava"]
//? 2: pop(): Method that removes the last element from an array.
console.log(fruits.pop());
// Output: "guava"
console.log(fruits);
// Output: ["apple", "orange", "mango", "grapes", "banana"]
//? 3: unshift(): Method that adds one or more elements to the beginning of an array.
console.log(fruits.unshift("guava"));
// Output: 6 ← New length of array
console.log(fruits);
// Output: ["guava", "apple", "orange", "mango", "grapes", "banana"]
//? 4: shift(): Method that removes the first element from an array.
console.log(fruits.shift());
// Output: "guava"
console.log(fruits);
// Output: ["apple", "orange", "mango", "grapes", "banana"]
//* what if, we want to add or remove anywhere in an elements - p2
//? The splice() method of Array instances changes the contents of an array by removing or
replacing existing elements and/or adding new elements in place
//* syntax
//? splice(start, deleteCount, item1, item2, /* …, */ itemN)
let fruits = ["apple", "orange", "banana", "mango"];
fruits.splice(1, 1, "grapes");
console.log(fruits); // Output: ["apple", "grapes", "banana", "mango"]
fruits.splice(-1, 0, "grapes");
console.log(fruits); // Output: ["apple", "grapes", "banana", "grapes", "mango"]
//* Searching in an Array
//?👉 Searching and Filter in an Array
//? For Search we have - indexOf, lastIndexOf & includes
const numbers = [1, 2, 3, 4, 6, 5, 6, 7, 8, 9];
//?1: indexOf Method: The indexOf method returns the first index at which a given
element can be found in the array, or -1 if it is not present.
// syntax
// indexOf(searchElement);
// indexOf(searchElement, fromIndex);
// console.log(numbers.indexOf(4, 5));
//? 2: lastIndexOf Method: The lastIndexOf() method of Array instances returns the last
index at which a given element can be found in the array, or -1 if it is not present. The
array is searched backwards, starting at fromIndex.
const numbers = [1, 2, 3, 6, 4, 5, 6, 7, 8, 9];
console.log(numbers.indexOf(6)); // Output: 3
console.log(numbers.lastIndexOf(6)); // Output: 6
console.log(numbers.includes(5)); // Output: true
//? 3: The includes method checks whether an array includes a certain element, returning
true or false.
// Syntax
// includes(searchElement);
// includes(searchElement, fromIndex);
const numbers = [1, 2, 3, 6, 4, 5, 6, 7, 8, 9];
const result = numbers.includes(5);
console.log(result);//output: true
//todo Challenge time
//? 1: Add Dec at the end of an array?
//? 2: What is the return value of splice method?
//? 3: Update march to March (update)?
//? 4: Delete June from an array?
const months = ["Jan", "march", "April", "June", "July"];
// // 1
months.splice(months.length, 0, "Dec");
console.log(months); //output: ["Jan", "march", "April", "June", "July", "Dec"]
// // 2:
// // When used to add elements, the splice method returns an empty array ([]).
// // 3
const indexToUpdate = months.indexOf("march");
months.splice(indexToUpdate, 1, "March");
console.log(months); output: ["Jan", "March", "April", "June", "July", "Dec"]
// // 4
const indexToDelete = months.indexOf("June");
months.splice(indexToDelete, 1);
console.log(months);//output: ["Jan", "March", "April", "July", "Dec"]
//* Filter in an Array
//? Search + Filter
const numbers = [1, 2, 3, 4, 5, 4, 6, 7, 8, 6, 9];
//? 1: find Method: The find method is used to find the first element in an array that
satisfies a provided testing function. It returns the first matching element or undefined if
no element is found.
const result = numbers.find((curElem) => {
return curElem > 6;});
console.log(result); // Output: 7
//? 2: findIndex Method: The findIndex() method of TypedArray instances returns the
index of the first element in a typed array that satisfies the provided testing function. If no
elements satisfy the testing function, -1 is returned.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// Step 1: Multiply each element by 5
const result = numbers.map((curElem) => curElem * 5);
console.log(result); output: [5, 10, 15, 20, 25, 30, 35, 40, 45]
// Step 2: Find the index of the first element > 15
const result2 = result.findIndex((curElem) => {
return curElem > 15;
});
console.log(result2);output: 3
//* 3: filter Method: The filter method creates a new array with all elements that pass
the test implemented by the provided function.
// syntax:
//? filter(callbackFn)
//? filter(callbackFn, thisArg)
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = numbers.filter((curElem) => {
return curElem > 4;});
console.log(result); //output : [5, 6, 7, 8, 9]
// UseCase: In E-commerce website when we want to Remove or delete any product from
addToCart page.
//! Ex. le'ts say user wants to delete value 6.
let value = 6;
const numbers = [1, 2, 3, 4, 6, 5, 6, 7, 8, 9];
let updatedCart = numbers.filter((curElem) => {
return curElem !== value;
});
console.log(updatedCart); // Output: [1, 2, 3, 4, 5, 7, 8, 9]
// Practice time
// !Example 2: Filtering Products by Price
const products = [
{ name: "Laptop", price: 1200 },
{ name: "Phone", price: 800 },
{ name: "Tablet", price: 300 },
{ name: "Smartwatch", price: 150 },];
// Filter products with a price less than or equal to 500
const filterProducts = products.filter((curElem) => {
return curElem.price <= 500;
});
console.log(filterProducts);
// Output: [
// { name: "Tablet", price: 300 },
// { name: "Smartwatch", price: 150 }
// ]
// //! Filter unique values
const numbers = [1, 2, 3, 4, 6, 5, 6, 7, 8, 9];
// Using filter and indexOf to get unique values
let uniqueValues = numbers.filter((curElem, index, arr) => {
return arr.indexOf(curElem) === index;
});
console.log(uniqueValues);
// Output: [1, 2, 3, 4, 6, 5, 7, 8, 9]
// Using Set to get unique values
console.log([...new Set(numbers)]);
// Output: [1, 2, 3, 4, 6, 5, 7, 8, 9]
//* How to Sort and Compare an Array
//? Sorting an Array: The sort method sorts the elements of an array in place and returns
the sorted array. By default, it sorts elements as strings.
const fruits = ["Banana", "Apple", "Orange", "Mango"];
const numbers = [1, 2, 4, 3, 6, 5, 6, 7, 4, 8, 9];
console.log(numbers);
// Output: [1, 2, 4, 3, 6, 5, 6, 7, 4, 8, 9]
//? compare callback function
// syntax
const sortedNumbers = numbers.sort((a, b) => a - b);
if(a>b) return 1 => switch the order
if(b>a) return -1 => keep the order
numbers.sort((a, b) => {
if (a > b) return -1;
if (b > a) return 1;
});
console.log(numbers);
// [9, 8, 7, 6, 6, 5, 4, 4, 3, 2, 1]
//? For ascending order
const numbers = [1, 2, 4, 3, 6, 5, 6, 7, 4, 8, 9];
const sortedNumbers = numbers.sort((a, b) => {
if (a > b) {
return 1;
} else if (b > a) {
return -1; }});
console.log(sortedNumbers); // [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9]
//? For descending order
const numbers = [1, 2, 4, 3, 6, 5, 6, 7, 4, 8, 9];
const sortedNumbers = numbers.sort((a, b) => {
if (a > b) {
return -1;
} else if (b > a) {
return 1; }});
console.log(sortedNumbers); // [9, 8, 7, 6, 6, 5, 4, 4, 3, 2, 1]
//* Very Important Array Methods
//? Map(), Filter(), Reduce(),
// map() creates a new array from calling a function for every array element.
// map() does not execute the function for empty elements.
// map() does not change the original array.
// Original array of numbers
const numbers = [1, 2, 3, 4, 5];
//! Using map to square each number and create a new array
const numbers = [1, 2, 3, 4, 5];
let result = numbers.map((curElem) => curElem * curElem);
console.log(result); // [1, 4, 9, 16, 25]
//! 1: Using the map method, write a function that takes an array of strings and returns a
new array where each string is capitalized.
// Original array of strings
const words = ["APPLE", "banana", "cherry", "date"];
const result = words.map((curElem) => {
return curElem.toLowerCase();
});
console.log(result); // ["apple", "banana", "cherry", "date"]
//! 2: Using the map method, write a function that takes an array of numbers and returns
a new array where each number is squared, but only if it's an even number.
// Original array of numbers
const numbers = [1, 2, 3, 4, 5];
const result = numbers
.map((curElem) => {
if (curElem % 2 === 0) {
return curElem * curElem;}})
.filter((curElem) => curElem !== undefined);
console.log(result); // [4, 16]
const evenSquare = numbers
.map((curNum) => (curNum % 2 === 0 ? curNum * curNum : undefined))
.filter((curElem) => curElem !== undefined);
console.log(evenSquare); // [4, 16]
//! 3: Using the map method, write a function that takes an array of names and returns a
new array where each name is prefixed with "Mr. ".
const names = ["ram", "vinod", "laxman"];
const prefixName = names.map((curName) => `Mr. ${curName}`);
console.log(prefixName); // ["Mr. ram", "Mr. vinod", "Mr. laxman"]
//? Reduce method
// The reduce method in JavaScript is used to accumulate or reduce an array to a single
value. It iterates over the elements of an array and applies a callback function to each
element, updating an accumulator value with the result. The reduce method takes a
callback function as its first argument and an optional initial value for the accumulator as
the second argument.
// syntax
// array.reduce(function callback(accumulator, currentValue, index, array) {
// // Your logic here
// // Return the updated accumulator value
// }, initialValue);
// callback: A function that is called once for each element in the array.
// accumulator: The accumulated result of the previous iterations.
// currentValue: The current element being processed in the array.
// index (optional): The index of the current element being processed.
// array (optional): The array reduce was called upon.
// initialValue (optional): An initial value for the accumulator. If not provided, the first
element of the array is used as the initial accumulator value.
const productPrice = [100, 200, 300, 400, 500];
const totalPrice = productPrice.reduce((accum, curElem) => {
return accum + curElem;
}, 0);
console.log(totalPrice); // 1500
//* String in JavaScript
//? Strings in JavaScript are a fundamental data type that represents a sequence of
characters.
// Note:
//? Strings created with single or double quotes works the same.
// There is no difference between the two.
//* String Properties:
//? length: Property that returns the length of the string (number of characters).
const str = "Hello, World!";
console.log(str.length); // Output: 17
// including space n all
//* Escape Character
//? Escape Character: In JavaScript, the backslash \ is used as an escape character. It allows
you to include special characters in a string.
// Code Result Description
// \' ' Single quote
// \" " Double quote
// \\ \ Backslash
let text = "My name is ' Thapa Technical ' & \\ I am a \"Full Stack \" Developer. ";
console.log(text);
// Output: My name is ' Thapa Technical ' & \ I am a "Full Stack " Developer.
//* String Search Methods
//? 2: String Search Methods
//? a: indexOf(): The indexOf() method returns the index (position) of the first occurrence
of a string in a string, or it returns -1 if the string is not found:
// syntax
// indexOf(searchString)
// indexOf(searchString, position)
let text = "Vinod Thapa";
console.log(text.indexOf("thapa")); // -1
// The indexOf() method is case sensitive.
console.log(text.indexOf("Thapa")); // 6
let text = "Vinod Thapa";
let strArr = Array.from(text);
// Converts string to array of characters
// Output: ['V', 'i', 'n', 'o', 'd', ' ', 'T', 'h', 'a', 'p', 'a']
let strMap = strArr.map((curElem, index) => `${curElem} - ${index}`);
// Maps each character to a string showing character and its index
// Output: ['V - 0', 'i - 1', 'n - 2', 'o - 3', 'd - 4', ' - 5', 'T - 6', 'h - 7', 'a - 8', 'p - 9', 'a - 10']
console.log(strMap);
// Final output:
// [
// 'V - 0',
// 'i - 1',
// 'n - 2',
// 'o - 3',
// 'd - 4',
// ' - 5',
// 'T - 6',
// 'h - 7',
// 'a - 8',
// 'p - 9',
// 'a - 10'
// ]
//? b: lastIndexOf() : The lastIndexOf() method returns the index of the last occurrence of a
specified text in a string:
// syntax
// lastIndexOf(searchString)
// lastIndexOf(searchString, position)
let text = "Hello JavaScript, welcome to our world best JavaScript course"
// 1️⃣ indexOf(): Finds the first occurrence of "JavaScript"
let index = text.indexOf("JavaScript");
// Output: 6 → "JavaScript" first appears at index 6
// 2️⃣ lastIndexOf(): Finds the last occurrence of "JavaScript"
index = text.lastIndexOf("JavaScript");
// Output: 44 → The last "JavaScript" appears at index 44
// 3️⃣ lastIndexOf with position: Search backward from index 40
index = text.lastIndexOf("JavaScript", 40);
// Output: 6 → Only the first "JavaScript" is found before index 40
console.log(index); // Final value of index is: 6
//? c: search(): The search() method searches a string for a string (or a regular expression)
and returns the position of the match.
//* Returns the index number where the first match is found. Returns -1 if no match is
found.
let text = "Hello JavaScript, welcome to our world best JavaScript course";
let result = text.search(/Javascript/i);
console.log(result); //6
//*👉 Important Tips
// The search() method cannot take a second start position argument.
// The indexOf() method cannot take powerful search values (regular expressions).
// They accept the same arguments (parameters), and return the same value
//? match() : Returns an array of the matched values or null if no match is found.
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// Case-sensitive string match (no regex)
let result = text.match("Javascript");
// ❌ Output: null → because "Javascript" ≠ "JavaScript" (case matters
// Case-sensitive match, exact string
result = text.match("JavaScript");
// ✅ Output: ['JavaScript'] → only the first match, no 'g' fla
// Implicit regex match, same as: text.match(/JavaScript/);
result = text.match(/JavaScript/);
// ✅ Output: ['JavaScript'] → first match only, no 'g' flag
// Case-insensitive + global match using regex
result = text.match(/Javascript/gi);
// ✅ Output: ['JavaScript', 'JavaScript'] → finds all matches, ignoring case
console.log(result); //null
//? matchAll() : Returns an iterator of all matches, providing detailed information about
each match. Returns an empty iterator if no match is found.
// let text = "Hello JavaScript, welcome to our world best JavaScript course";
// let matchResult = text.matchAll("javascript");
// let matchResult = text.matchAll("JavaScript");
//todo here the js converts the normal text into regular expression
text.match(/JavaScript/g); also adds the g flag at the end
// console.log(...matchResult);
// for (let item of matchResult) {
// console.log(item[0]);
// }
// for (let index of matchResult) {
// console.log(index.index);
// }
// for (let { index } of matchResult) {
// console.log(index);
// }
//? includes(): Returns true if the string contains the specified value, and false otherwise.
// let text = "Hello JavaScript, welcome to our world best JavaScript course";
// let includeResult = text.includes(/java/i);
// let includeResult = text.includes("J");
// console.log(includeResult);
// Note: includes() is case sensitive. includes() is an ES6 feature.
//? startsWith(): The startsWith() method returns true if a string begins with a specified
value.Otherwise it returns false:
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ❌ This will return false — "Helcome" ≠ "Hello"
let result = text.startsWith("Helcome");
console.log(result); // Output: false
// ✅ This will return true — text *does* start with "Hello"
let result = text.startsWith("Hello");
console.log(result); // Output: true
//* start position for the search can be specified
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ✅ Checks if the substring starting at index 18 begins with "welcome"
let result = text.startsWith("welcome", 18);
console.log(result); // Output: true
// ❌ Starts checking at index 17 — which is the space **before** "welcome"
let result = text.startsWith("welcome", 17);
console.log(result); // Output: false
//? endsWith(): The endsWith() method returns true if a string ends with a specified value.
Otherwise it returns false:
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ❌ Check if the string ends with "welcome" — it does NOT
let result = text.endsWith("welcome");
console.log(result); // Output: false
// ✅ Check if the string ends with "course" — it DOES
let result = text.endsWith("course");
console.log(result); // Output: true//* Extracting String Parts:
//? String.prototype.substr() it is deprecated ❌
//? a: slice() extracts a part of a string and returns the extracted part in a new string.
// syntax
// slice(start, end);
// Todo JavaScript counts positions from zero.
//? First position is 0. Second position is 1.
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ✅ slice from index 6 to end
let result = text.slice(6);
console.log(result);
// Output: "JavaScript, welcome to our world best JavaScript course"
// ✅ slice from index 6 to index 15 (not inclusive)
let result = text.slice(6, 15);
console.log(result);
// Output: "JavaScrip"
// subString() substring()
//? a: substring: Extracts a portion of the string based on starting and ending indices.
//* camelCase is used to separate words, substring is not to be intended as Sub String but as
Substring
// syntax
// substring(indexStart) // index starts with 0
// substring(indexStart, indexEnd)
//* substring() is similar to slice(). The difference is that start and end values less than 0 are
treated as 0 in substring().
//! Homework
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ✅ substring from index 0 (entire string)
let result = text.substring(0);
console.log(result);
// Output: "Hello JavaScript, welcome to our world best JavaScript course"
// ✅ substring from index 1 (skips 'H')
let result = text.substring(1);
console.log(result);
// Output: "ello JavaScript, welcome to our world best JavaScript course"
// ❌ Negative index is treated as 0
let result = text.substring(-5);
console.log(result);
// Output: "Hello JavaScript, welcome to our world best JavaScript course"
//! similarities
//todo In both the slice() and substring() methods, the end parameter indicates the ending
index up to which the extraction occurs, but the character at the end index is excluded from
the extracted substring.
//* Interview Question
//! What is the output for the following code?
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ✅ Remove first character using slice()
let result1 = text.slice(1);
console.log("slice(1):", result1);
// Output: "ello JavaScript, welcome to our world best JavaScript course"
// ✅ Remove first 'H' using replace()
let result2 = text.replace("H", "");
console.log('replace("H", ""):', result2);
// Output: "ello JavaScript, welcome to our world best JavaScript course"
// ✅ Same as slice(1), using substring()
let result3 = text.substring(1);
console.log("substring(1):", result3);
// Output: "ello JavaScript, welcome to our world best JavaScript course"
// ✅ Replace only first "JavaScript" with "Vinod"
let result4 = text.replace("JavaScript", "Vinod");
console.log('replace("JavaScript", "Vinod"):', result4);
// Output: "Hello Vinod, welcome to our world best JavaScript course"
// ✅ Replace all "JavaScript" with "Vinod"
let result5 = text.replaceAll("JavaScript", "Vinod");
console.log('replaceAll("JavaScript", "Vinod"):', result5);
// Output: "Hello Vinod, welcome to our world best Vinod course"
//* Extracting String Characters
//! Extracting String Characters
// There are 3 methods for extracting string characters:
//? The charAt(position) Method
//? The charCodeAt(position) Method
//? The at(position) Method
//? charAT() : The charAt() method returns the character at a specified index (position) in a
string
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ✅ Get character at index 6
let result = text.charAt(6);
console.log(result);
// Output: "J"
// ❌ Negative index — charAt() does NOT support negative values
let result = text.charAt(-6);
console.log(result);
// Output: "" (empty string)
//? charCodeAt() : The charCodeAt() method returns the code of the character at a
specified index in a string. The method returns a UTF-16 code (an integer between 0 and
65535).
let text = "Hello JavaScript, welcome to our world best JavaScript course";
let result = text.charCodeAt(6);
console.log(result); // Output: 74 (character at index 6 is "J")
//todo ES2022 introduced the string method at():
//? The at() method returns the character at a specified index (position) in a string. The at()
method returns the same as carAt().
let text = "Hello JavaScript, welcome to our world best JavaScript course";
// ✅ Get the character at the 6th position from the end using .at()
let result = text.at(-6);
console.log(result); // Output: "c"
//todo Note
// The at() method is a new addition to JavaScript.
// It allows the use of negative indexes while charAt() do not.
// Now you can use myString.at(-2) instead of charAt(myString.length-2).
//! Replacing String Content:
//? replace() : The replace method is used to replace a specified value with another value.
const str = "Hello, World!";
const newStr = str.replace("World", "JavaScript");
console.log(newStr); // Output: Hello, JavaScript!
//? Case-Insensitive Replacement: To perform a case-insensitive replacement, you can use
the i flag in the regular expression.
let originalString = "Hello, World! How are you, World?";
let replacedString = originalString.replace(/world/gi, "vinod");
console.log(replacedString); // Output: Hello, vinod! How are you, vinod?
//! Other Useful Methods:
//? toUpperCase and toLowerCase: Converts the string to uppercase or lowercase.
const str = "JavaScript";
console.log(str.toUpperCase()); // Outputs: JAVASCRIPT
console.log(str.toLowerCase()); // Outputs: javascript
//? trim: Removes whitespace from both ends of the string.
const str = " Hello, World! ";
console.log(str.length); // Output: 20 (includes spaces at start and end)
let trimStr = str.trim(); // Removes leading and trailing spaces
console.log(trimStr); // Output: "Hello, World!"
console.log(trimStr.length); // Output: 13 (spaces removed)
//? split: Splits the string into an array of substrings based on a specified delimiter.
const str = "apple,orange,banana";
let strArr = str.split(",").reverse().join(); // "banana,orange,apple"
console.log(strArr); // Output: banana,orange,apple
//* //! Interview Questions
//! 1: Write a JavaScript function that prints the letters 'a' through 'z' in the console. You
should use a loop to iterate through the letters and print each one on a new line.
// console.log("a".charCodeAt(0));
// console.log("z".charCodeAt(0));
// for (let char = 97; char <= 122; char++) {
// console.log(String.fromCharCode(char));
// }
//! 2: Write a function to count the number of vowels in a string?
// const countVowels = (str) => {
// const vowels = "aeiou";
// let count = 0;
// for (let char of str) {
// console.log(char);
// // console.log(str.includes(char));
// if (vowels.includes(char)) {
// count++;
// }
// }
// return count;
// };
// console.log(checkAllVowelPresentOrNot("my name u is vinod @ thapa"));
// console.log(countVowels("Hello a i o u world"));
//! 3: Write a function to check if all the vowels presents in a string or not?
// const checkAllVowelPresentOrNot = (str) => {
// const vowels = "aeiou";
// for (let char of vowels) {
// // console.log(char);
// // console.log(str.includes(char));
// if (!str.includes(char)) {
// return false;
// }
// }
// return true;
// };
// console.log(checkAllVowelPresentOrNot("my name u is vinod @ thapa"));
//! 4: Write a JavaScript function to check if the given sting is Pangram or not?
const pangramChecker = (str) => {
let inputArr = str.toLowerCase().split("");
// console.log(inputArr);
// // console.log("z".charCodeAt());
const values = inputArr.filter(
(curElem) =>
curElem.charCodeAt() >= "a".charCodeAt() &&
curElem.charCodeAt() <= "z".charCodeAt()
);
// console.log(values);
return new Set(values).size === 26;
// return [...new Set(values)].length === 26;
};
console.log(pangramChecker("The quick @ brown fox jumps ove the lazy dog"));