for any suggestions or queries mail to email : codingtitans2@gmail.com
javascript is a programming language, commonly known as language of web. it is used to make web pages interactive by manipulating dom(document object model). it is a client side programming language.
language which runs on clients side is known as clients side language. javascript runs on users browsers thats why it is client side language. like : html,css, js
Server side programming language stands for language which runs at server side , server side refers to the server (web server) other than user physical machine.
like java is server side programming language because it is used to interact with database generate dynamic data at run time. it cannot execute at users machine.
like : java, dot net, ruby, node js
before jumping to conclusion lets understand what is single threaded and multi threaded.
eg. we have our computer system which comprises of cpu, which is central processing unit, and it is divided into cores. if we examine we could see our processor is eg : intel core i5 7 generation it has 4 core means it has 4 different areas and at same time it can handle 4 different task.
in our mobile phones also we octa core processor means processor can handle 8 different task .
so in our system how a task is executed ?
a task is known as process, a octa core processor can handle 8 different process at a time. computer system dedicates each task to different thread , consider thread a person (octa core means 8 processor or 8 thread or 8 person).
when one thread completed execution it releases and gets freed and system gives another task to exxecute.
so now js is single threaded or multi threaded ?
it is single threaded --> javascript can perform single task at a time.
There are 2 ways a. internal using script tag in head tag or body tag <script></script>
b. external js file. (linking external js file in the head tag) <script src="path to external js file">
we can include javascript in our code in head or body section
we know browser reads the file from top to bottom
when we place our script tag in head section then browser reads the script and then reads the body section, means scripy is loaded first before html
when we place our script in body section at the last , it parses the html first then loads the script, wich is good practice, because loading script can cause time delay.
when we have developed the page structure using html and css, if we need to make the page dynamic like when user clicks then on some action the content should changed or page should behave like this,this can be controlled using javascript.
a) js can change HTML content
b) it can change html attribute values
c) hide/show elements and much more
variables are the containers for storing data , we can declare js variables in 3 different ways.
1. let ( introduced in es6)
2. const ( introduced in es6 )
3. var (since starting of js)
eg : var a = 10;
where var is a data type
a is variable name
10 is value
lets understand what is declaration and definition.
variable declaration : variable declaration refers to the specifiying data type and name of variable woitjout assigning a value.
eg : var a;
variable definition : Variable definition is the process of both declaring a variable and assigning it an initial value.
var a = 10;
variable name is known as identifier. basically how can a variable can be identified.
var age = 25;
here age is a variable name or identifer.
Rule for identifers :
a) name should begin with letter
b)reserved words should not be used for identifiers like let, break, for , while
variables declared using var can be re-declared means
var a = 10;
var a= 20;
here we first declared a =10 then re declare a =20;
while let and const does not allow re-declaration
let a=10;
let a=20;
error : syntax error
const : const is for storuing constant values which do not change during run time.values declared in const cannot be re defined
const a=10;
a=20; // it will give error
eg: const PI= 3.14
we know value of pi will never change so we can use const variable for this.
Always declare a variable with const when you know that the value should not be changed.
Use const when you declare:
A new Array
A new Object
A new Function
A new RegExp
undefined -> variables which are not defined holds the value undefined
null -> when user inteyonally adds value null , data type is object.
number
boolean
string
object
There are various types of operators in js such as.
a)Arithmetic operator
b) Assignment operator
c) Comparision Operator
d)logical Operator
e)bitwise operator
f)ternary operator
The various Arithmetic operator are.
let a=5,b=10
a) Addition (+)
used for addition of 2 values
let result = a+b.
result = 15
b) Subtraction (-)
let result = b-a;
result = 5;
c) Multiplication (*)
let result = a*b;
result = 150;
d) division (/)
let result = b/a;
result = 2
e) Modulo (%) -- it gives remainder
let result = b%a;
result =0;
f) Exponetiation Operator(introduced in ecma 2016) (**)
let a=5;
exponentiation is similar to power
a**2 means 5^2 or 5 power 2 which is 25
a**2 gives = 25
g) Increment operator (++)
increment operator can be used as suffix and prefix
let a=10,b=20;
++a --> pre increment
a++ -> post increment
Difference between the 2 is in pre increment number is incremented first and in post increment it is later.
eg ++a + b. -> it will output 31
because ++a will increment 10 to 11 then add 20
a++ + b--> will give 30
because it will first add numbers then increment value of a
h) Decrement operator (--)
same is for decrement operator.
--a , a--
The various assignment operators are :
a) = -> it is used to assign valye to variable.
eg: let a= 10
eg: let a=10;
a = a+20;
here a =30 because 10+20 will result into (30) the result will be assigned back to variable a using assignment operator.
there is also shorthand to this which is
a+=20 which means a=a+20
similary a=a*20 can be written as
a*=20
the comparison operators are :
a) == --> it is used to compare 2 values, it return true or false based on comparison.
b) === -> it is known as triple equal operator , the difference between == and === operator is that == operator looks to compare 2 values while === operator compares value and type.
eg : let a= 5 , b=5
a==b -> returns true becayse a is 5 and b is also 5
a===b --> it return true because value matches both are 5 and type , type of a is number and type of b is also number
eg :2 let a=5, b="5";
a==b --> it return true because both are 5
a===b --> false
value comparison : 5 ==='5' --> true
type comparison : number === 'syring' --> false
c)!= and !==
d) greater than(>) and less than (<)
let a=5,b=10;
a>b --> false;
b>a --> true
e) greater than equal and less than equal (>= and <=)
Logical operators in programming are used to perform logical operations on one or more boolean values or expressions. These operators allow you to combine, compare, and manipulate boolean values to make decisions and control the flow of your program. In most programming languages, logical operators include:
-
AND Operator (
&&):- The AND operator returns
trueif both of its operands aretrue. - It returns
falseif at least one of its operands isfalse. - Example:
true && trueevaluates totrue, whiletrue && falseevaluates tofalse.
- The AND operator returns
-
OR Operator (
||):- The OR operator returns
trueif at least one of its operands istrue. - It returns
falseonly if both of its operands arefalse. - Example:
true || falseevaluates totrue, whilefalse || falseevaluates tofalse.
- The OR operator returns
-
NOT Operator (
!):- The NOT operator is a unary operator that negates (flips) the boolean value of its operand.
- It returns
trueif its operand isfalse, andfalseif its operand istrue. - Example:
!trueevaluates tofalse, and!falseevaluates totrue.
Logical operators are commonly used in conditional statements (such as if, else if, and while) to control program flow based on conditions. They are also used to combine multiple conditions to create more complex logic.
Additionally, logical operators follow short-circuiting behavior in many programming languages, which means they may not evaluate all of their operands. For example, in an && expression, if the first operand is false, the second operand is not evaluated because the overall result will be false regardless of the second operand. This behavior can be leveraged for efficiency and to avoid potential errors in certain situations.
The ternary operator, often referred to as the conditional operator, is a concise way to write conditional statements in many programming languages, including JavaScript. It allows you to evaluate a condition and return one of two values based on whether the condition is true or false.
The syntax of the ternary operator is as follows:
condition ? expression_if_true : expression_if_false
Here's how it works:
- The
conditionis evaluated first. If it istrue, theexpression_if_trueis executed, and its value becomes the result of the entire expression. If theconditionisfalse, theexpression_if_falseis executed, and its value becomes the result.
Here's an example in JavaScript:
let isRaining = true;
let weather = isRaining ? "Bring an umbrella" : "Leave your umbrella at home";
console.log(weather); // Outputs: "Bring an umbrella"In this example:
isRainingis the condition."Bring an umbrella"is the value returned if the condition is true."Leave your umbrella at home"is the value returned if the condition is false.
The ternary operator is often used for simple conditional assignments or to make code more concise when the condition and the two possible outcomes are short expressions. However, for complex conditions or when the expressions involve multiple statements, using a regular if...else statement is usually more readable.
While the primary purpose of the unary plus (+) operator in JavaScript is to convert values to numbers (when possible), it can be used in a few other ways or in combination with other operations:
-
Mathematical Operations: You can use the unary plus operator to perform mathematical operations. For example:
let x = 5; let y = 10; let sum = +x + +y; // Equivalent to 5 + 10, results in 15
-
Parsing Numbers from Strings: It's commonly used to parse numeric values from user input, such as form fields or text boxes, where the input is received as a string. This is a common technique to ensure that user input is treated as a number.
let userInput = "42"; let numberValue = +userInput; // Converts the string "42" to the number 42
-
Converting Number-Like Values: The unary plus operator can handle values that are "number-like" but not strictly numeric, such as numbers with trailing spaces.
let numberAsString = "42 "; let numberValue = +numberAsString; // Converts "42 " to 42
-
Converting Dates to Timestamps: You can use
+to convert aDateobject to a Unix timestamp (number of milliseconds since January 1, 1970).let now = new Date(); let timestamp = +now; // Converts the Date object to a timestamp
-
Using in Comparison: The unary plus operator can be used in comparisons to convert values to numbers before performing comparisons.
let str1 = "5"; let str2 = "10"; if (+str1 < +str2) { console.log("str1 is less than str2"); }
In general, while the primary purpose of the unary plus operator is for type conversion to numbers, it can also be employed in various other contexts where type conversion or mathematical operations are needed. However, you should use it judiciously, as it may make the code less readable when used for purposes other than type conversion.
The ?? operator and the || operator are both used in JavaScript for handling default values or providing fallback values, but they have some key differences:
-
Nullish Coalescing Operator (
??):- The nullish coalescing operator, denoted as
??, is used to provide a default value when a variable isnullorundefined, but it does not provide a default value for other falsy values such as0,"",false,NaN, or empty objects. - It specifically checks for
nullorundefinedand short-circuits (returns the right-hand operand) if the left-hand operand is one of these values. - It is designed to handle cases where you want to distinguish between null/undefined and other falsy values.
Example:
let x = null; let y = x ?? "Default Value"; console.log(y); // Outputs: "Default Value"
- The nullish coalescing operator, denoted as
-
Logical OR Operator (
||):- The logical OR operator, denoted as
||, is used to provide a default value when a variable is falsy, which includesnull,undefined,0,"",false,NaN, and empty objects. - It short-circuits (returns the right-hand operand) if the left-hand operand is falsy.
Example:
let x = null; let y = x || "Default Value"; console.log(y); // Outputs: "Default Value"
- The logical OR operator, denoted as
In summary, the key difference between ?? and || is their behavior when the left-hand operand is a falsy value other than null or undefined. The ?? operator only checks for null or undefined, whereas the || operator checks for any falsy value. Choose the operator that best fits your specific use case and the behavior you want for handling defaults.
!! is the double NOT operator, which coerces the operand to a boolean value. It’ll convert truthy values to true and falsy values to false .
console.log(!!0); == false
console.log(!!''); == false
console.log(!!false); == false
console.log(!!NaN); == false
console.log(!!undefined); == false
console.log(!!null); == false
truthy values : truthy or true values (values which are not undefined or are not null)
a) non zero number
b) non empty strings
c) arrays
d) objects
e) functions
f) NaN
Falsy Values
a) 0
b) -0
c) false
d) null
e) undefined
f) empty string
A function is a block of code designed to perform particular task.
function needs to be invoked to perform a task.
syntax
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
parameter are basically the inputs to the functions.
eg . function add (a,b){
console.log(a+b)
}
consider we created a function to add 2 numbers.
function add (a,b){
console.log(a+b)
}
this above function will not be called or return us the sum of 2 numbers , we have to call the function.
clling function is known as function invocation.
syntax:
function_name()
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different results.
a block is denoted using curly braces {}.
anything enclosed inside this will be called inside a block.
eg . { // block starts
let a=10; // defining variable a inside a block
} // block ends
block start: when curly braces or scope of block starts
block ends: when curly brarces or scope of block ends.
function declaration and function expression are 2 ways to define functions in js.
function declaration : Function declaration defines a function using function keyword followed by function name.
function add(a, b) {
return a + b;
}
function expression : function expression defines a anonymous function, (a function without name is called anonymous function.) or a function assigned to a variable.
eg: var add = function(a,b){
}
default parameter are a way to provide default values to function paramaters.
eg : function add(a,b){
console.log(a+b)
}
it can clearly seen the function requires 2 arguments but during function call we passed just 1 , it will result in NaN because 5+undefined will result in NaN.
if we want,if user doesnot assign a value or pass a value to parameter then default value should be assigned to the variable, then we can use the default arguments.
When a function is called and an argument for a parameter is not provided, the default value is used instead. Default arguments are a convenient way to make functions more flexible and handle cases where not all arguments are provided by the caller.
function greet(name, greeting = 'Hello') {
console.log(`${greeting}, ${name}!`);
}
greet('Alice'); // Output: "Hello, Alice!"
greet('Bob', 'Hi'); // Output: "Hi, Bob!"
Conditional statements in JavaScript are used to make decisions in your code. They allow you to execute different blocks of code based on whether a specified condition evaluates to true or false. JavaScript provides several conditional statements, including:
The if statement is the most basic conditional statement. It executes a block of code if a specified condition is true.
The if...else statement allows you to execute one block of code if a condition is true and another block if the condition is false.
The switch statement is used to test a variable against multiple values and execute different code blocks for each value.
The if statement in JavaScript is a statement that allows you to execute a block of code if a specified condition evaluates to true.
if (condition) {
// Code to execute if the condition is true
}
condition: This is a boolean expression or any expression that can be evaluated to true or false. If the condition is true, the code block enclosed within the curly braces {} is executed. If the condition is false, the code block is skipped.
const age = 25;
if (age >= 18) {
console.log("You are an adult.");
}
in if statement we can execute block of code if condition execute to be true , but what if the condition is false.
In this case we can use if...else statement
if(condition){
// code to be executed if condition is true
}else{
// code to be executed if condition is false.
}
The if...else if...else statement in JavaScript is an extension of the if...else statement that allows you to handle multiple conditions in a sequence. It provides a way to test a series of conditions, executing different blocks of code based on the first condition that evaluates to true. Here's the syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the conditions are true
}condition1,condition2, etc.: These are boolean expressions or expressions that can be evaluated totrueorfalse. The conditions are evaluated in the order in which they are written. Ifcondition1istrue, it executes the code block associated with it. Ifcondition1isfalse, it moves on tocondition2, and so on.
Here's an example of how the if...else if...else statement works:
const temperature = 25;
if (temperature > 30) {
console.log("It's hot outside.");
} else if (temperature >= 20) {
console.log("The weather is pleasant.");
} else {
console.log("It's cold outside.");
}In this example, it first checks if temperature is greater than 30. If that condition is true, it logs "It's hot outside." If the temperature is not greater than 30, it moves on to the next condition, which checks if the temperature is greater than or equal to 20. If that condition is true, it logs "The weather is pleasant." If neither condition is true, it executes the code in the else block, which logs "It's cold outside."
The if...else if...else construct is useful when you have multiple conditions to check in a specific order and want to handle different scenarios based on the first condition that is satisfied.
The switch statement in JavaScript is a conditional statement that is used to test a variable against multiple values or expressions and execute different code blocks based on the value that matches. It provides an alternative way to handle multiple conditions compared to a series of if...else if...else statements.
The basic syntax of the switch statement looks like this:
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
// more cases can follow
default:
// Code to execute if expression doesn't match any case
}Here's how the switch statement works:
-
The
switchstatement is provided with anexpression, which is typically a variable or an expression that you want to compare against thecasevalues. -
Inside the
switchstatement, there are multiplecaselabels that represent different values or expressions to be compared to theexpression. -
If the
expressionmatches one of thecasevalues, the corresponding block of code associated with thatcaselabel is executed. -
The
breakstatement is used to exit theswitchstatement once a match is found. Withoutbreak, the code execution would continue into the nextcaseblock even if a match has already been found. -
If none of the
casevalues match theexpression, thedefaultblock is executed.
Here's an example of a switch statement:
const day = "Monday";
switch (day) {
case "Monday":
console.log("It's the start of the workweek.");
break;
case "Friday":
console.log("It's almost the weekend!");
break;
default:
console.log("It's a regular day.");
}In this example, the switch statement compares the day variable to different values and executes the corresponding code block based on the value that matches. In this case, it will execute the code in the "Monday" case because day is set to "Monday."
The switch statement is particularly useful when you have a variable with multiple possible values and you want to simplify the handling of each value with different code blocks.
loops are used to iterate the statements number of times. loops help us to reduce redundancy.
without loop :
eg. if we want to print number from 1 to 5 without loops , we do like
console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
with loops we can reduce the following line of the code significantly.
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
syntax:
for (initialization; condition; update) {
// Code to be executed in each iteration
}
The "initialization" part is executed only once, at the beginning of the loop, to set up the initial conditions.
The "condition" is checked before each iteration. If it's true, the loop executes the code block inside the loop. If it's false, the loop terminates.
After each iteration of the loop, the "update" statement is executed, which typically increments or decrements the control variable.
eg :
for (let i = 1; i <= 5; i++) {
console.log(i);
}
A `while` loop in JavaScript is a control flow structure that repeatedly executes a block of code as long as a specified condition is true. It is often used when you don't know in advance how many iterations are needed and want to continue looping as long as the condition remains true.
The basic syntax of a while loop in JavaScript is as follows:
while (condition) {
// Code to be executed as long as the condition is true
}Here's how a while loop works:
-
The
conditionis evaluated before each iteration. If the condition is true, the code inside the loop is executed. -
After executing the code block, the program returns to the
condition, and if it is still true, the loop continues to the next iteration. This process repeats until the condition becomes false. -
When the condition becomes false, the loop terminates, and the program continues with the code after the loop.
Here's an example of a while loop that prints numbers from 1 to 5:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}In this example, i is initially set to 1. The while loop checks if i is less than or equal to 5. If this condition is true, it prints the value of i, increments i by 1, and then checks the condition again. This process repeats until i is no longer less than or equal to 5.
The loop will produce the following output:
1
2
3
4
5
While for loops are typically used when you know the number of iterations in advance, while loops are more suitable when the number of iterations depends on a dynamic condition or when you need to create a loop with more complex exit conditions. Be careful when using while loops to avoid infinite loops by ensuring that the condition will eventually become false.
A "do-while" loop in programming is a control flow structure that is similar to a "while" loop, but with a crucial difference: it guarantees that the code block within the loop will be executed at least once, even if the loop's condition is initially false.
The basic syntax of a do-while loop in most programming languages, including JavaScript, is as follows:
do {
// Code to be executed
} while (condition);Here's how a do-while loop works:
-
The code block inside the
dois executed first, regardless of whether the condition is true or false. -
After the code block executes, the program checks the
conditionspecified in thewhilestatement. -
If the
conditionis true, the loop will continue to execute the code block and then reevaluate the condition. This process repeats until theconditionbecomes false. -
If the
conditionis initially false, the code block still executes once before checking the condition. If the condition remains false, the loop terminates after the first iteration.
Here's an example of a do-while loop in JavaScript that prompts the user for a number and continues to prompt until the user enters a positive number:
let number;
do {
number = parseFloat(prompt("Enter a positive number:"));
} while (isNaN(number) || number <= 0);
console.log("You entered a valid positive number: " + number);In this example, the code inside the do block prompts the user for a number, and the loop will keep executing as long as the user's input is not a positive number. The loop ensures that the user is prompted at least once, even if they enter an invalid value.
The do-while loop is useful in situations where you want to perform a task that must be done at least once, and then continue repeating the task based on a condition. It's less common than the standard for or while loops but can be valuable in specific scenarios where you need to guarantee an initial execution.
parseInt and parseFloat are JavaScript functions used for converting strings into numbers. However, they have different use cases and behavior:
-
parseInt:parseIntis used to parse a string and convert it into an integer (whole number).- It starts parsing from the beginning of the string and stops when it encounters a non-numeric character or a decimal point.
- It also accepts an optional second parameter, the radix, which specifies the base of the number system (e.g., 10 for decimal, 16 for hexadecimal).
- It discards any decimal portion of the number.
- Example:
const parsedInt = parseInt("123.45"); // Returns 123
-
parseFloat:parseFloatis used to parse a string and convert it into a floating-point number (a number that can have a decimal point).- It parses the entire string until it encounters an invalid character or the end of the string.
- It retains the decimal portion of the number, allowing for floating-point values.
- Example:
const parsedFloat = parseFloat("123.45"); // Returns 123.45
Use Cases:
- Use
parseIntwhen you want to convert a string to an integer, discarding any decimal places. - Use
parseFloatwhen you want to convert a string to a floating-point number, retaining decimal places if present in the string.
Here's an example demonstrating the difference:
const intResult = parseInt("42.67"); // Result is 42 (decimal portion is truncated)
const floatResult = parseFloat("42.67"); // Result is 42.67 (decimal portion is retained)
console.log(intResult); // Outputs 42
console.log(floatResult); // Outputs 42.67In summary, parseInt is for converting strings to integers, and it truncates any decimal portion. parseFloat is for converting strings to floating-point numbers, and it retains decimal places if they exist in the string. The choice between them depends on your specific use case and the desired type of conversion.
In JavaScript, "break" and "continue" are control flow statements used within loops to modify the flow of the program's execution:
-
break:
- The "break" statement is used to exit a loop prematurely. When a "break" statement is encountered inside a loop, it terminates the loop, and program control continues with the next statement after the loop.
- It is commonly used when you want to exit a loop based on a certain condition being met.
Example in a "for" loop:
for (let i = 1; i <= 5; i++) { if (i === 3) { break; // Exit the loop when i is 3 } console.log(i); }
-
continue:
- The "continue" statement is used to skip the current iteration of a loop and move to the next iteration. When a "continue" statement is encountered, the rest of the code inside the current iteration is skipped, and the loop continues with the next iteration.
- It is often used when you want to skip specific iterations based on a condition without terminating the entire loop.
Example in a "for" loop:
for (let i = 1; i <= 5; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i); }
Both "break" and "continue" are valuable tools for controlling the flow of loops in JavaScript, allowing you to handle specific conditions or requirements within the loop's execution.
Answer: The "break" statement inside the inner loop will exit only the inner loop. It does not directly affect the outer loop. The outer loop will continue its execution unless a "break" statement is explicitly used within the outer loop as well. If you want to exit both the inner and outer loops when a condition is met, you would need to use a labeled "break" statement, which specifies the loop to break out of. Here's an example:
outerloop:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outerloop; // This breaks out of both loops
}
console.log(`i=${i}, j=${j}`);
}
}In this example, the labeled "break" statement "break outerloop;" will exit both the outer and inner loops when i is 2 and j is 2.
Array is a data structure which can store multiple element in index manner and sequential.
we can declare array like :
eg : let arr = [];
charactersticks of array
1. Arrays maintain the order of elements, and each element in the array has a unique position or index
2. In Other languages , arrays are homogeous which means they only contain same type of data, while in js which is dynamic typed language, it can store the heterogenous data.
let arr=[1,"a",true];
here array contains number, string and boolean value.
3. Arrays provide fast and direct access to elements based on their index.
Array are type of Object. let arr = [1,2,3,4]
typeof arr => 'object'
Array declaration => let arr = []
here variable arr in type of array , which does not have any value.
lets declare an array with elements
let arr =[10,20,30,40,50,60,70,80]
as we know arrays are index based which means elements are stored at index starting from zero
at index 0 => 10
at index 1 => 20
at index 2 => 30
at index 3 => 40
at index 4 => 50
at index 5 => 60
at index 6 => 70
at index 7 => 80
at index 8 => 90
to get the zero index element we have to do :
arr[0] => 10
arr[1] => 20
arr[5] => 60
we can check length of an array using length property.
let arr=[1,2,3,4,5,6,7,8,9]
arr.length => 9
const arr= ['john','alex','victor','matte','cintia'];
Array is index based data structure
just like we can access element at zero index like arr[0]
we can print element using or iterating the index
the above array has index starting from
0 -> john
1 -> alex
2 -> victor
3 -> matte
4 -> cintia
we can iterate through this index using for loop like
for(let i=0;i< arr.length;i++){
console.log(arr[i]);
}
The for...of loop is a modern iteration construct in JavaScript introduced with ECMAScript 2015 (ES6). It provides a concise and readable way to loop over the values of iterable objects, such as arrays, strings, maps, sets, and more. The for...of loop allows you to iterate directly over the values themselves, rather than their indices or keys, making it a convenient choice for many common looping tasks.
Here's the basic syntax of the for...of loop:
for (const element of iterable) {
// Code to be executed for each element in the iterable
}element: This is a variable that represents the current value of the iterable on each iteration.iterable: This is the iterable object you want to loop through.
Examples:
-
Looping through an array:
const fruits = ["apple", "banana", "cherry"]; for (const fruit of fruits) { console.log(fruit); } // Output: // "apple" // "banana" // "cherry"
-
Looping through a string (treats it as an iterable of characters):
const text = "Hello"; for (const char of text) { console.log(char); } // Output: // "H" // "e" // "l" // "l" // "o"
-
Looping through the values of a Set:
const mySet = new Set([1, 2, 3]); for (const value of mySet) { console.log(value); } // Output: // 1 // 2 // 3
The for...of loop is a more concise and often more readable alternative to traditional loops like for and forEach when you need to iterate over the values of iterable objects. It also works well with the break statement to exit the loop or the continue statement to skip to the next iteration, just like other loop constructs.
In JavaScript, the `Array` constructor is a built-in constructor function that is used to create and initialize arrays. You can use it to create new arrays, either empty or with initial values. The `Array` constructor can be called in two ways:
-
Using
newkeyword:You can create an empty array by invoking the
Arrayconstructor with thenewkeyword. You can also pass a single argument, which specifies the initial length of the array.const emptyArray = new Array(); const arrayWithLength = new Array(3); // Creates an array with a length of 3
Note that when you provide a single numeric argument, it sets the length of the array, but the actual elements are
undefined. -
Using array elements:
You can create an array by passing individual values as arguments to the
Arrayconstructor. These values become the elements of the array.const fruits = new Array('apple', 'banana', 'cherry');
This is equivalent to creating an array using array literal notation:
const fruits = ['apple', 'banana', 'cherry'];
Using array literals is the more common and preferred way to create arrays in JavaScript because it's more concise and readable. The Array constructor is rarely used in practice, except for some specific scenarios where you need to create an array with a specified length.
It's important to be aware of potential issues with using the Array constructor to create arrays, particularly when dealing with a single numeric argument. In some cases, it might be more intuitive and safer to create arrays using array literals or other array creation methods provided by JavaScript.
There are 4 different methods to add or delete elements in array .
1. Push => Adds one or more elements to the end of an array.
let fruits = ['apple', 'banana'];
fruits.push('cherry');
// fruits is now ['apple', 'banana', 'cherry']
we can push more than 1 element
fruits?.push('orange','mango')
// ['apple','banana','cherry','orange','mango'];
- Pop : Removes the last element from an array.
let arr= [1,2,3,4]
arr.pop() -> returns 4
- Unshift: Adds one or more elements to the beginning of an array.
let fruits = ['banana', 'cherry'];
fruits.unshift('apple');
// fruits is now ['apple', 'banana', 'cherry']
- Shift : Removes the first element from an array.
let fruits = ['apple', 'banana', 'cherry'];
fruits.shift();
// fruits is now ['banana', 'cherry']
The at() method of Array instances takes an integer value and returns the item at that index.
const array1 = [5, 12, 8, 130, 44];
let index = 2;
array1.at(2) => 8
array1.at(-1) => 44
** negative index count from back.
The concat() method of Array instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
output => ["a", "b", "c", "d", "e", "f"]
arr.concat(elements)
the elements can be
a) array
b) multiple values (10,20,30);
arr.concat(10,20,30,40);
The Array.isArray() static method determines whether the passed value is an Array.
Array.isArray() checks if the passed value is an Array. It does not check the value's prototype chain, nor does it rely on the Array constructor it is attached to. It returns true for any value that was created using the array literal syntax or the Array constructor.
Array.isArray(1) => false
Array.isArray([]) => true
The fill() method of Array instances changes all elements within a range of indices in an array to a static value. It returns the modified array.
syntax :
fill(number to be filled,start_index,end_index);
const array1 = [1, 2, 3, 4];
// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
filter method is used to filter elements from the array and it gives the shallow copy of the array.
eg : let evenNumbers = [1,2,3,4,5,6,7,8,9,10];
here we are having an array of 10 natural numbers, if we want to filter only the even numbers we have to do the following steps:
a) iterate each and every element of array and check whether element is even or odd.
b) take a new bucket or a new array and place even numbers in new bucket .
function filterEvenNumberWithoutFilterMethod(arr){
let evenNumbers =[];
for(let i=0;i< arr.length;i++){
if(arr[i] %2 !==0 ) continue;
evenNumbers.push(arr[i])
}
}
- let evenNumbers =[]; taking a new bucket to store all even numbers.
- iterating elements from 0 to length and checking if element at index is modulus by 2 is not equal zero (means odd number ) should be igore and loop should continue
- when number is even it should be pushed in new array.
Array slice method is used to return the shallow copy of array elements.
syntax : array.slice(start,end)
-
where start and end represent the index of items in that array. The original array will not be modified.
-
end index is optional, if end index is not provided the slice will return all the elements starting from startIndex till the last element.
-
if end index is present, end index will always be considered -1. slice(0,3) it will give the elements starting from 0 index till the 2 index.
eg : const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; - animals.slice(1) // will give elements starting from 2 till the last index output => ['camel', 'duck', 'elephant']; - animals.slice(0,2) // will give elements starting from 0 to 1 output => ['ant','bison'] -- animals.slice(-2) // negatve index will start from last -2 means starting from second last index which is duck and goes till last. output => ['duck','elephant']
The Array.from() method is a static method available in JavaScript for creating a new array from an iterable object or an array-like object. It allows you to convert other data structures, such as strings, sets, maps, and objects with iterable properties, into an array.
Here's the basic syntax of Array.from():
Array.from(iterable[, mapFn[, thisArg]])iterable: The source iterable or array-like object to convert into an array.mapFn(optional): A mapping function to apply to each element in the iterable. It is called for each element in the iterable, and the returned value becomes the corresponding element in the new array.thisArg(optional): An optional value to use asthiswhen executing the mapping function.
Examples:
-
Converting a String to an Array:
You can use
Array.from()to convert a string into an array of its characters.const str = 'Hello'; const charArray = Array.from(str); console.log(charArray); // Output: ['H', 'e', 'l', 'l', 'o']
-
Converting a Set to an Array:
You can convert a
Setinto an array.const mySet = new Set([1, 2, 3]); const setArray = Array.from(mySet); console.log(setArray); // Output: [1, 2, 3]
-
Using a Mapping Function:
You can provide a mapping function to modify the elements as you convert them.
const numbers = [1, 2, 3, 4, 5]; const squaredNumbers = Array.from(numbers, x => x * x); console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
-
Using an Array-Like Object:
Array.from()can be used to convert an array-like object (e.g., theargumentsobject) into an array.function exampleFunction() { return Array.from(arguments); } const argsArray = exampleFunction(1, 2, 3); console.log(argsArray); // Output: [1, 2, 3]
Array.from("hello",(ele)=>ele.toUpperCase());
Array.from() is a versatile method that simplifies the process of converting iterable or array-like data into arrays, which can be particularly useful when working with different types of data in JavaScript.
-
The indexOf() method of Array instances 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) const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // Expected output: 1 // Start from index 2 console.log(beasts.indexOf('bison', 2)); // Expected output: 4 console.log(beasts.indexOf('giraffe')); // Expected output: -1 ---- eg : 2 const array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0
-
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 animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; console.log(animals.lastIndexOf('Dodo')); // Expected output: 3 console.log(animals.lastIndexOf('Tiger')); // Expected output: 1
The reverse() method of Array instances reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
Arrow functions in JavaScript are a more concise way to write functions. They were introduced in ECMAScript 6 (ES6) and provide a shorter syntax for defining functions compared to conventional function expressions.
Here's a basic example of an arrow function:
const add = (a, b) => a + b;And here's how you would write the same function using a conventional function expression:
const add = function(a, b) {
return a + b;
};Here are some key differences between arrow functions and conventional functions:
-
Syntax:
- Arrow functions have a shorter syntax, especially when the function has only one expression. They don't require the
functionkeyword or the use of curly braces{}if there's only one statement.
- Arrow functions have a shorter syntax, especially when the function has only one expression. They don't require the
-
thisbinding:- Arrow functions do not have their own
thiscontext. They inherit thethisvalue from the surrounding code. This makes them particularly useful when defining functions as callbacks or within methods, where the context ofthiscan be different in a conventional function.
- Arrow functions do not have their own
-
No arguments object:
- Arrow functions do not have their own
argumentsobject. In conventional functions, you can access theargumentsobject to get all the passed arguments, but arrow functions do not have this feature.
- Arrow functions do not have their own
-
Cannot be used as constructors:
- You cannot use arrow functions with the
newkeyword to create instances of objects. Conventional functions can be used as constructors to create new objects.
- You cannot use arrow functions with the
-
Use cases:
- Arrow functions are often preferred for short, simple functions, like mapping an array or defining callbacks in functions like
Array.prototype.map(),Array.prototype.filter(), andsetTimeout(). Conventional functions are still used for more complex or larger functions.
- Arrow functions are often preferred for short, simple functions, like mapping an array or defining callbacks in functions like
-
Readability:
- Arrow functions can make the code more concise, but they may sacrifice some readability for those who are not familiar with this syntax. Some developers prefer conventional functions for clarity in certain situations.
It's essential to choose between arrow functions and conventional functions based on the specific use case and your coding style. Both have their advantages and disadvantages, and understanding their differences will help you use them effectively in your JavaScript code.
eg :
() => expression
param => expression
(param) => expression
(param1, paramN) => expression
() => {
statements
}
param => {
statements
}
(param1, paramN) => {
statements
}
lets consider normal function be of greet
function greet(){
console.log("Hello World")
}
Steps to convert this into arrow function:
1. remove the function keyword.
greet(){
console.log("Hello World")
}
2. give the arrow between the paranthesis and curly braces.
greet = ()=>{}
we have seen passing primitive types like integers and strings to function, but we can also pass function as a parameter to another function.
-
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
eg: we can pass function as a parameter function success(){ console.log("success") } function add(a,b,callback){ console.log(a+b); callback(); }
-
JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.
-
Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.
-
In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed.
The setTimeout function in JavaScript is used to schedule the execution of a function (or the evaluation of a piece of code) after a specified delay in milliseconds. It allows you to introduce a delay in your code, making it useful for various purposes, such as executing code after a certain time interval, creating animations, handling timeouts, or simulating asynchronous behavior.
Here's the basic syntax of the setTimeout function:
setTimeout(function, delay);-
function: This is the function or code snippet you want to execute after the specified delay. -
delay: This is the amount of time, in milliseconds, by which you want to delay the execution of the function.
Here's an example of how you can use setTimeout to schedule a function to run after a 2-second delay:
function sayHello() {
console.log("Hello, world!");
}
setTimeout(sayHello, 2000); // Executes sayHello after a 2-second delay (2000 milliseconds)You can also use an arrow function or an inline function directly within setTimeout, like this:
setTimeout(() => {
console.log("This is an anonymous function.");
}, 1000);It's important to note that setTimeout doesn't pause the execution of the rest of your code. It schedules the specified function to run in the future and continues executing the code that follows it. If you need to wait for the setTimeout to complete before proceeding, you should use callbacks or Promises to handle the asynchronous behavior.
Here's an example of using setTimeout to create a simple delay:
console.log("Start");
setTimeout(function() {
console.log("This message appears after a delay.");
}, 2000);
console.log("End");In this example, "Start" and "End" will be displayed immediately, while the message within setTimeout will be displayed after a 2-second delay.
setTimeout is a fundamental part of asynchronous JavaScript and is often used for handling animations, creating timed actions, and managing non-blocking code execution.
The setInterval function in JavaScript is used to repeatedly execute a given function or code snippet at a specified time interval. It is similar to setTimeout, which schedules a function to run after a specified delay, but setInterval is designed to execute a function repeatedly with a fixed time gap between each execution.
Here's the basic syntax of the setInterval function:
setInterval(function, delay);-
function: This is the function or code snippet you want to execute at regular intervals. -
delay: This is the time interval, in milliseconds, between each execution of the function.
Here's an example of how you can use setInterval to repeatedly execute a function every 2 seconds:
function logMessage() {
console.log("This message repeats every 2 seconds.");
}
setInterval(logMessage, 2000); // Executes logMessage every 2 seconds (2000 milliseconds)You can also use an arrow function or an inline function directly within setInterval, like this:
setInterval(() => {
console.log("This is an anonymous function that repeats.");
}, 1000);It's important to note that setInterval will continue to execute the specified function indefinitely at the specified time interval until you explicitly clear it using clearInterval. To stop the execution of a repeating function, you would use clearInterval and provide it with the interval ID returned by setInterval.
Here's an example of how to use clearInterval to stop a repeating function:
function logMessage() {
console.log("This message repeats every 2 seconds.");
}
const intervalId = setInterval(logMessage, 2000);
// To stop the repeating function after a certain number of executions (e.g., 5 times):
let counter = 0;
const maxExecutions = 5;
if (counter === maxExecutions) {
clearInterval(intervalId); // This stops the interval.
}setInterval is commonly used for tasks that need to be performed at regular intervals, such as updating real-time data, creating animations, or periodically checking for new data from a server. It's an essential part of handling time-based events in JavaScript.
In JavaScript, the filter method is a built-in array method that is used to create a new array containing elements from the original array that meet a specified condition. The filter method does not modify the original array; instead, it returns a new array with the elements that satisfy the provided condition.
Here is the basic syntax of the filter method:
const newArray = array.filter(callback(element, index, array));array: The original array that you want to filter.callback: A function that is called for each element in the array. This function should returntruefor elements that should be included in the filtered array andfalsefor elements that should be excluded.element: The current element being processed in the array.index(optional): The index of the current element being processed.array(optional): The array thatfilterwas called upon.
Here's an example of using the filter method to filter even numbers from an array:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const evenNumbers = numbers.filter(function (number) {
return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4, 6, 8]You can also use arrow functions for conciseness:
const evenNumbers = numbers.filter(number => number % 2 === 0);The filter method is a powerful tool for selecting elements from an array based on various criteria, and it is commonly used for tasks such as data filtering, searching, or creating a subset of data that meets specific conditions.
-
In JavaScript, the
mapmethod is a built-in function for arrays that allows you to create a new array by applying a given function to each element of an existing array. It takes an input array, processes each element, and returns a new array containing the results of the function applied to each element.
Here's the basic syntax of the map method:
const newArray = array.map(callback(currentValue, index, array));array: The original array on which you want to apply themapoperation.callback: A function that is executed for each element in the array.currentValue: The current element being processed.index(optional): The index of the current element being processed.array(optional): The array on whichmapwas called.
Here's an example of using the map method to double each element in an array:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function (number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]You can also use arrow functions for brevity:
const doubledNumbers = numbers.map(number => number * 2);The map method is particularly useful for transforming data in an array. It creates a new array with the same length as the original one, where each element is the result of applying the provided function to the corresponding element in the input array. It does not modify the original array; it returns a new one, making it non-destructive.
Common use cases for the map method include data transformation, such as formatting or extracting specific information from an array of objects, or creating a new array based on some transformation of the elements in the original array.
The every() method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// Expected output: true (as all elements are less than 40).
-
it iterates for all elements in the array untill elements return false.
In JavaScript, the some method is a built-in function for arrays that is used to determine if at least one element in the array meets a specified condition. The some method returns true if the condition is met by at least one element in the array and false if no elements satisfy the condition.
Here's the basic syntax of the some method:
const result = array.some(callback(element, index, array));array: The array you want to test.callback: A function that is used to test each element in the array.element: The current element being tested.index(optional): The index of the current element.array(optional): The array on which thesomemethod was called.
Here's an example of using the some method to check if an array contains any even numbers:
const numbers = [1, 3, 5, 2, 7, 9];
const hasEvenNumber = numbers.some(function (number) {
return number % 2 === 0;
});
console.log(hasEvenNumber); // Output: true (because 2 is an even number)You can also use arrow functions for brevity:
const hasEvenNumber = numbers.some(number => number % 2 === 0);The some method is often used to quickly check if an array contains elements that satisfy a certain condition. It's particularly useful when you want to determine whether at least one item in the array meets a specific requirement without needing to process all the elements in the array.
If you need to check whether all elements in the array satisfy a condition, you can use the every method, which returns true only if all elements meet the condition.
-
The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
const array1 = [5, 12, 8, 130, 44]; const found = array1.find((element) => element > 10); console.log(found); // Expected output: 12
The findIndex() method of Array instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// Expected output: 3
The findLast() method of Array instances iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found);
// Expected output: 130
-
The forEach() method of Array instances executes a provided function once for each array element.
forEach(callbackFn)
- There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
-
The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate
const array1 = [1, 2, 3]; console.log(array1.includes(2)); // Expected output: true const pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // Expected output: true console.log(pets.includes('at')); // Expected output: falsesyntax :
includes(searchElement) includes(searchElement, fromIndex)
Note :
the first element that matches, use find().
the index of the last matching element in the array, use findLastIndex().
the index of a value, use indexOf(). (It's similar to findIndex(), but checks each element for equality with the value instead of using a testing function.)
whether a value exists in an array, use includes(). Again, it checks each element for equality with the value instead of using a testing function.
if any element satisfies the provided testing function, use some().