Sprint 3-JS-102
Sprint 3-JS-102
● Users should be able to understand why we need JavaScript and where to use it.
● Users should be able to execute simple JavaScript programs using console statements
on Repl.it
● Users should be able to differentiate between different types of primitive data types.
● Users should be able to declare variables using var, let and const and difference
between these identifiers based on declaration and assignment.
● Users should be able to distinguish between valid and invalid variable names.
● Users should be able to write variable names using best coding practices.
● User should be able to answer interview questions on data types and variables.
While folks are joining -
Link: https://replit.com/~
Why is the template called NodeJS in replit?
Why isn’t the light turning on? Why isn’t our code working as intended?
● console.log(“Hello World”)
Activity - Write your first program on replit
In order to deal with different types of data in our program, we need Data-Types.
What are primitives?
console.log(2);
console.log("hello");
Primitives Data Types
● Numbers (2, -100, 3.14, and others), used for math calculations.
Without variable: For total, need to add price of each item from start
With variable: For total, need to add price of just current item, as we
have stored the sum until now in a variable.
Variables
● Variables are named container used to store, change, and access information.
Think of it as
Age
● Declaration:
○ We use the keyword var along with the name of the variable.
Code Demo - Assignment
● Assignment:
○ We simply assign some value to the variable.
Recap: Reassignment
● Re-assignment
● What if we have a variable whose value should not change during the execution of the
program.
● But if we will use var to declare this variable it can modified easily.
● After you declare a variable, you would want to store a value in the memory reserved by
it. Assigning a value after the variable is declared, at some point in your program, is called
an assignment.
● Syntax for Assignment:
20
Think of it as -
Age
● Declaring a variable using const keyword instead of var creates a variable whose value can’t be
changed.
const means constant i.e. whose value can not be changed.
const variableName;
Activity - Will we get an error?
● But how can we stop this as this can easily lead to undesirable outputs.
● Declaring variables using let will stop this confusion as it’s more strict than var.
Demo - var, let, and const
var ✅ ✅
let ❌ ✅
const ❌ ❌
Activity - Playing with let
● Now re-declare a new variable using let
var a = 10;
console.log(a); Console
a 0x11 10
Memory
Variables and values in memory
10
var b = a; 10
console.log(a); 10
console.log(b);
var b = a;
console.log(a); Console
console.log(b);
b 10
0x37
a 0x11 10
Memory
Variables and values in memory
10
a = 20; 10
console.log(a); 10
console.log(b); 20
10
a = 20;
console.log(a); Console
console.log(b);
20
0x15
b 10
0x37
a 0x11 10
Memory
Variables and values in memory
Summary:
● Values are stored in the memory, and variables are the labels pointing to
the memory address where the value is stored.
● When we assign a value to a variable either directly (e.g. b = 20;) or from one
variable to another
(e.g. b = a;), a new copy of that value is created and stored in the memory
and the variable points to it.
Activity - Naming a variable
● After the first letter, you can use numbers, letters, underscores,
dollar signs.
What about naming a variable?
● Variables are named container used to store, change, and access information
Link: https://www.crio.do/magic/datatypes-and-variables-quiz
● Expressions
● Mathematical Operators (+, -, *, /, %) and Precedence
● Relational / Logical Operators (>, <, ===, !==, &&, ||)
● If-Else statements - Part I
● Introduction to Functions - Part I
○ Parametric & Non-Parametric
○ Calling a function
○ Returning values
● JS program from scratch on Replit
○ Take user i/p
● Introduction to Crio Platform
Let’s understand one use case
Suppose we have the data of marks in Math and Science, but we want to
compute total marks in our program. How can we do this?
In this case, we are taking the sum of values stored in variables and
assigning that sum to a new variable called total.
Recap: Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Code Demo - Arithmetic Operators
Let’s evaluate some expressions that use arithmetic operators
● console.log(2 + 2)
● console.log(29 - 19)
● console.log(19 - 29)
● console.log(5 * 15)
● console.log(10 / 2)
● console.log(1 / 2)
● console.log(10 % 2)
Activity - Arithmetic Operators
2 ** 3
How do we compute the following?
const x = 1 + 2 * 3;
console.log(x);
7 or 9? Confused?
● Brackets ( … ) B
● Exponentiation (**) E
● Division ( / ) D
● Multiplication (*) M
● Modulus (Remainder) (%) R
● Addition (+) A
● Subtraction (-) S
B
E
DMR
AS
Note: In case they belong to same category, follow order from left to right in the
given expression.
Activity: Predict the output
Variable
Equal to
assignment
Code Demo - Checking relationships
let a = 10;
let b = 20;
console.log ( a == b );
console.log ( a === b );
console.log ( a >= b );
console.log ( a <= b );
console.log ( a !== b );
console.log ( a != b );
In the previous slide, you saw both === and == returned false while comparing
equality of a and b. So, what’s the difference between them?
== ===
1. console.log(0 == false);
console.log(0 === false);
2. console.log(37 == ‘37’);
console.log(37 === ‘37’);
1. Output:
true (converts false boolean->0 number, for comparison)
false (no such conversion, strict comparison)
2. Output:
true (converts ‘37’ string->37 number, for comparison)
false (no such conversion, strict comparison)
Recap - Logical Operators
let a = 10;
let b = 20;
Use the if statement to specify a block of code to be executed if the condition is true, and use else to
specify a block of code to be executed if the condition is false.
Syntax: Example:
if (hour < 18) {
if (condition) { greeting = "Good day";
// block of code to be executed if the condition is true } else {
} else { greeting = "Good evening";
// block of code to be executed if the condition is false }
}
Code Demo - If Else
There exists a calculator app, and you have to build the square (number raised to
power 2) feature for it. Suppose, user wants to calculate square of numbers 3, 7,
24.
console.log(3 ** 2);
console.log(7 ** 2);
console.log(24 ** 2);
Pitfalls
1. The user might not always want squares of 3, 7, 24. They may ask for
squares of other numbers as well, which will vary based on user’s need.
2. The user might not always want to perform square operations one after
another, but might also perform some other operations in between, e.g.
find square of 2, then add 23 to it, then subtract 2 from it, and then find
square of it again.
3. After a few months, you may be asked to update the feature e.g. calculate
square root, or cube of given number. So, you will need to change the code
at multiple lines.
Function
● Define a function :
function functionName(parameter) {
● Call a function i.e. executing the piece of code defined in the function :
functionName(argument);
● Argument is the actual value we wish to pass to the function and parameter is the variable within
the function that will store the passed value.
● You may have multiple parameters and arguments separated by comas.
Code demo - Function
Write a code consisting of a function getSquare that will compute and console
log the square based on a number value passed to it.
Print the square of 3 using getSquare
Print “hello”
Print the square of 2 using getSquare
Print “Crio”
Print “Learn by doing”
Print the square of 24 using getSquare
Activity - Function
What if you don’t want to console log the value computed by the function, but simply
return it out from the function in order to store it and process it further.
E.g. Instead of doing console log of the square calculated by getSquare(), we want to just
store it in a variable called mySqr so that we can use it later.
Note: In previous examples wherein we did not have any return statement, we were
returning undefined automatically.
For our calculator we want to display some greeting message to the user when
he/she starts the calculator.
Note: We just need to do a console log inside the function, saying “Hello!”, so we
don’t need to pass any parameter to the function.
Define a user named greet, that will do console log “Hello!”. Make sure no
parameters are used.
Code (with user i/p) Demo on Replit
● Write a program to take 2 numbers as input from user via terminal, and console.log true if both
the numbers are equal, else console.log false.
● From the forked Repl, open sess2/equalityCheck-user-ip.js
● As mentioned in the comments, define a function and call it for the purpose of checking whether
the given terminals are equal or not.
Code (from Scratch) Demo on Crio Platform
89, 11 false
3, 3 true
Code (from Scratch) Demo on Crio Platform
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
89, 11 false
3, 3 true
Code (from Scratch) Demo on Crio Platform
6. Test the code (debug any syntax errors and logical errors)
Code Demo on Crio Platform
89, 11 100
1, 2 3
Code Demo on Crio Platform
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
89, 11 100
1, 2 3
Code Demo on Crio Platform
6. Test the code (debug any syntax errors and logical errors)
Demo - Introduction to Crio Platform
● Expressions are small units of code (literals, variables, operators, etc) that result in a value
● Relational / Logical operators : > , < , <= , <= , === , !== , && , ||
● if( condition ) {
//if condition is true, then do this
} else {
//if condition is false, then do this
}
Summary
● Non-Parametric:
function greet() {
console.log( “Hi” );
}
● Parametric:
function add( x, y ) { -> x & y are parameters
return x + y; -> To return the result value
}
Link: https://www.crio.do/magic/conditionals-and-functions-quiz
● Users should be able to write & use if-else chains & nested if-else statements.
● Users should be able to access string characters and check length of the string.
● Users should be able to understand string immutability.
● Users should be able to use string methods and also go through the documentation in
order to implement new methods
While folks are joining -
● Expressions
● Mathematical Operators (+, -, *, /, %) and Precedence
● Relational / Logical Operators (>, <, ===, !==, &&, ||)
● If-Else statements - Part I
● Introduction to Functions - Part I
○ Parametric & Non-Parametric
○ Calling a function
○ Returning values
● Introduction to Crio Platform
Agenda
Syntax:
Example:
if (condition1) {
if (time < 10) {
// Block 1: block of code to be executed if condition1 is true
greeting = "Good morning";
}
}
else if (condition2) {
else if (time < 20) {
// Block 2: block of code to be executed if the condition1 is
greeting = "Good day";
false and condition2 is true
}
}
else {
else {
greeting = "Good evening";
// Block 3: block of code to be executed if the condition1 is
}
false and condition2 is false
}
Code Demo - If else Chain
Write a program on replit to take in 3 numbers as user input via the terminal and
log the smallest among them on the console.
You must define a function and call it wherever the comments are mentioned.
Activity - If else Chain
LINK -
https://www.crio.do/learn/PSDS/ME_ES6_OPERATORS_CONDITIONALS/ME_ES6_OPERATORS_CONDIT
IONALS_MODULE_SMALLESTOFTHREENUMBERSES6/
Code (from Scratch) Demo on Crio Platform
1, 9, 78 1
2, 3, 4 2
Code (from Scratch) Demo on Crio Platform
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
1, 9, 78 1
2, 3, 4 2
Code (from Scratch) Demo on Crio Platform
6. Test the code (debug any syntax errors and logical errors)
Recap: Nested if else
Syntax:
Example:
if (condition1) {
if (time = 10) {
// Block 1: block of code to be executed if condition1 is true
console.log(“Good morning");
if (condition2) {
if (awake!= true) {
// Block 2: block of code to be executed if the
console.log(“WAKE UP!");
condition1 is true and condition2 is true
}
}
else {
else {
console.log(“Drink coffee");
// Block 3: block of code to be executed if the
}
condition1 is true and condition2 is false
else {
}
console.log(“Continue sleeping :)");
}
}
else {
// Block 4: block of code to be executed if the
condition1 is false
}
Activity - Nested If Else
Question:
https://www.crio.do/learn/PSDS/ME_ES6_OPERATORS_CONDITIONALS_NOSTUBS/ME_ES6_OPERATO
RS_CONDITIONALS_NOSTUBS_MODULE_BLOODDONATIONNOSTUBSES6/
Code (from Scratch) Demo on Crio Platform
25, 55 Eligible
15, 51 UnderAge
24, 48 NotEligible
Code (from Scratch) Demo on Crio Platform
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
25, 55 Eligible
15, 51 UnderAge
24, 48 NotEligible
Code (from Scratch) Demo on Crio Platform
6. Test the code (debug any syntax errors and logical errors)
Strings - Textual Data
● String Length : Useful for data validation e.g. password length must be > 6 characters.
console.log(“Crio.do”.length) //prints 7
In order to validate that the password string contains at least one number and at
least one special character, we should be able to access each individual
character of the string. How can we do that?
Accessing string characters
console.log(str[0]); //C
console.log(str.charAt(4)); //.
Curious Cats - .charAt() vs []
What’s the use of having .charAt() when we already have [] to access character at
a particular index of the string?
charAt() returns an empty string if index is out of range, while bracket notation
returns undefined.
E.g.:
console.log(str.charAt[6]); // undefined
Activity - Playing with Strings and Indexes
Question
https://www.crio.do/learn/PSDS/ME_ES6_STRINGS/ME_ES6_STRINGS_MODULE_CONCATFIRSTCHARES
6/
Code (from Scratch) Demo on Crio Platform
Anu, Rao AR
Ravi, Faizan RF
Code (from Scratch) Demo on Crio Platform
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
Anu, Rao AR
Ravi, Faizan RF
Code (from Scratch) Demo on Crio Platform
6. Test the code (debug any syntax errors and logical errors)
Code Demo - String Immutability
console.log(myStr); console.log(myStr);
It might happen that a developer might forget that strings are immutable in JS, and might have a line of
code as seen in previous slide:
myStr[0] = "J";
And then he will get unexpected output.
Since strings are immutable in JS, is there a way by which JS should give us an error message the
moment we mutate a string? i.e. can we make JS more strict?
Strict Mode
“use strict”
● Strict mode changes previously accepted "bad syntax" into real errors.
● For example, with strict mode, you cannot use undeclared variables.
Activity - Strict Mode
console.log(myStr);
Consider a scenario…
A social media platform has the birthdate and current age of all of its users. We
need to greet happy birthday to users who have their birthday in a personalized
manner i.e. mentioning their name and updated age.
How will you create such strings if we have the name and current age stored in
variables?
a template literal !` ;
console.log(greeting);
Activity - Template Strings
Question
https://www.crio.do/learn/PSDS/ME_ES6_STRINGS_NOSTUBS/ME_ES6_STRINGS_NOSTUBS_MODULE_F
INDDIAMETERNOSTUBSES6/
Code (from Scratch) Demo on Crio Platform
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
6. Test the code (debug any syntax errors and logical errors)
5 mins break!
String Methods
● If updates are required on a string, since strings are immutable, these methods return a new
string with the modified value
Demo - Reading Documentation
console.log( str2.indexOf("sea") );
console.log( str2.lastIndexOf("sea") );
console.log( str2.indexOf("time") );
Activity - Positional String Methods
console.log( str.indexOf("the") );
console.log( str.lastIndexOf("do") );
E.g.: “john-doe-1982”
How can we extract a the first name, last name and birth year?
i.e. How can we extract the substrings “john”, “doe” and “1982” from the string
“john-doe-1982”?
Substring
● If endPos is not given, then from startPos till the end of the string is returned
Code Demo - Substring
console.log( str.substring(5, 9) );
console.log(res);
● If else chains are used to test for multiple mutually exclusive outcomes.
Link: https://www.crio.do/magic/strings-quiz
Please make sure you complete both of the quizzes mentioned in the Post-session task of
this session:
● What are template literals in JavaScript, and how do they differ from
traditional string concatenation?
Notice the
1 2 semicolons?
Block of code
} Exit
Code Demo - For Loop
LINK -
https://www.crio.do/learn/PSDS/ME_ES6_LOOPS_ARRAYS_1_NOSTUBS/ME_ES6_LOOPS_ARRAYS_1_N
OSTUBS_MODULE_SUMFIRSTNNUMBERSNOSTUBSES6/
3 6
5 15
Activity - For Loop
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
3 6
5 15
Activity - For Loop
6. Test the code (debug any syntax errors and logical errors)
For Loop - Debrief
● The initialization statement is executed one time only before loop starts, to define and setup
loop variable.
● The condition statement is evaluated at the beginning of every loop iteration and will continue
as long as it evaluates to true.
● The final expression is executed at the end of each loop iteration, prior to the next condition
check to increment or decrement your loop counter.
Consider a scenario…
Arrays in JavaScript
● With JavaScript array variables, we can store several types of data in one place.
● Arrays can store anything as their value - primitives, another array, objects, or even functions*
Code Demo - Arrays
console.log(simpleArray[0]); //"one"
● Unlike strings, array entries are mutable & can be changed freely.
Array Indices & Values
● Create a new empty array and set the following elements in the array at the given indexes
[0] - 1
[1] - "Hello"
[2] - true
[3] - "Piotr"
● .length returns the next available index in the array, that is the length of the array.
if(password.length < 6) {
console.log(“Password must have at least 6 characters”);
}
Code Demo - Array length
let x = [1, 2, 3]
let y = x
x[0] = 1000
console.log(x)
console.log(y)
Arrays Memory Representation
y
1000
1 2 3
let a = [1, 2, 3]
let b = [1, 2, 3]
let c = a
1 2 3
BookMyShow is an app where people can book tickets of various events. India
v/s Pakistan Cricket match is going on and the users must be able to book tickets
on a first-come-first-serve basis.
Suppose a new user “Sanket” wants to join the waiting list.
“Sanket”
0 1 2
0 1 2 3
Code demo - push()
.push() appends data to the end of an array & returns the new array length.
Use push() to add a new element “Sanket”, as the last element of the ticketLine array.
Consider a scenario…
0 1 2 3
0 1 2
Code demo - shift()
.shift() removes the first element from an array and returns the removed element.
Use shift() to remove the 0th element “Omkar”, from the ticketLine array.
Consider a scenario…
Super Premium user “Ruchir” gets to use the feature of VIP booking that puts
him directly at the front of the waiting list!
“Ruchir”
0 1 2
0 1 2 3
Code demo - unshift()
.unshift() works like .push(), but adds the element at the beginning of the array.
Use unshift() to add “Ruchir” as the 0th element in the ticketLine array.
Consider a scenario…
0 1 2
0 1
Code demo - pop()
.pop() works like .shift(), but it removes the last element of the array.
Use pop() to remove the last element “rectangle” from the shapes array.
.
● .push() appends data to the end of an array & returns the new array length.
● .pop() removes the last element from an array and returns the removed element.
● .shift() works like .pop(), but it removes the first element of the array.
● .unshift() works like .push(), but adds the element at the beginning of the array.
Code Demo - Array Methods
console.log(arr); console.log(arr);
console.log(arr); console.log(arr);
Activity - Todo List
b. If the priority is 'high', then the item is added at the start, else at the end of the list
Consider a scenario…
Answer: null
Code Demo - null
Let’s implement the Find Song program, discussed on the previous slide.
From the forked repl, open sess4/songs-user-ip.js, and code up the solution
after the demo.
Consider a scenario…
We want to print the values from the given array, which are not false.
Wouldn’t it be great if we knew the list of all the false values, rather than checking it.
Falsy or Truthy Values
● false, null, 0, "", undefined, and NaN are Falsy values in JavaScript.
● All values other than these are Truthy, it will evaluate to true.
Activity - Falsy Values
LINK -
https://www.crio.do/learn/PSDS/ME_ES6_LOOPS_ARRAYS_1_NOSTUBS/ME_ES6_LOOPS_ARRAYS_1_N
OSTUBS_MODULE_OPTIMISTLADNOSTUBSES6/
Create a new array without the falsy values from the given array, on Crio Platform
Activity - Falsy Values
a, b, c a, b, c
Activity - Falsy Values
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
a, b, c a, b, c
Activity - Falsy Values
6. Test the code (debug any syntax errors and logical errors)
.
Sort
.
Reverse
reverse() - Reverses the order of the elements in the given array, in-place.
In-place: The array is reversed in-place. It’s not the case that a new array is created with the reversed
positionings.
Code Demo - Reverse
console.log(arr.reverse());
console.log(arr);
Summary
● The initialization statement is executed one time only before loop starts, to define
and setup loop variable.
● The condition statement is evaluated at the beginning of every loop iteration and
will continue as long as it evaluates to true.
● The final expression is executed at the end of each loop iteration, prior to the next
condition check to increment or decrement your loop counter.
● With JavaScript array variables, we can store several pieces of data in one place.
● Array elements can be accessed and modified using bracket notation.
● Unlike strings, array entries are mutable & can be changed freely.
● .length returns the next available index in the array, that is the length of the array.
End of session quiz
Link: https://www.crio.do/magic/js101-strings-quiz
● What are truthy and falsy values in JavaScript? Can you provide examples of
each?
(If any term in the above answer looks new to you, please just read it in the answer provided to get a high-level understanding.
You will learn more about it in the later sessions)
Thank you
Goals for Session 5
● Users should be able to understand how to search arrays using includes method.
● Users should be able to convert string to array using split()
● Users should be able to convert array to string using join()
● Users should be able to use nested loops
● Users should be able to understand multi-dimensional arrays
● User should be able to to create objects, add properties, change properties and delete
properties.
While folks are joining -
● Searching in Array
■ Array.includes(value)
● String to Array - split()
● Array to String - join()
● Nested loops
● Multidimensional Arrays
● Introduction to JS Objects
● Creating, accessing & updating objects
Consider a scenario…
And you need to create a function isSongPresent() that takes in the myPlaylist array and a song
string as arguments and returns true if the song is present in the playlist, else returns false.
First thing that pops up in your mind is to iterate through all the elements in the array and look for
the song string we are searching for.
But can we do better or is there any existing method that could help us?
Searching in Arrays
● Array.includes(element, fromIndex) -
Can you guess the o/p for the following code without trying to run the code?
console.log( arr.includes('Vikram', 5) );
console.log( arr.includes('Vikram') );
Consider a scenario…
Sign Up Form
string.split(separator)
● If separator string is omitted, then an array with the original string is returned
Code Demo - split
console.log(pathSegments);
const pathSegments2 =
"users/john/documents/report.txt".split();
console.log(pathSegments2);
Consider a scenario…
Sign Up Form
array.join(separator)
console.log(filePath);
console.log(filePath2);
Activity - Reverse a string
LINK -
https://www.crio.do/learn/PSDS/ME_ES6_LOOPS_ARRAYS_2_NOSTUBS/ME_ES6_LOOPS_ARRAYS_2_N
OSTUBS_MODULE_REVERSESTRINGNOSTUBSES6/
And returns a string which is the reverse of the original string, on Crio Platform.
welcome emoclew
first tsrif
Activity - Reverse a string
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
welcome emoclew
first tsrif
Activity - Reverse a string
6. Test the code (debug any syntax errors and logical errors)
Summary: String ↔ Array
split(“ ”) join(“ ”)
Is there a way to store data in our JS program in a way similar to how we store it in
the rows and columns format in Excel?
Multi-dimensional array
1D Array: 2D Array:
console.log(arr[0][0]);
console.log(arr[0][1]);
console.log(arr[0][2]);
console.log(arr[1][0]);
console.log(arr[1][1]);
console.log(arr[1][2]);
console.log(arr[2][0]);
console.log(arr[2][1]);
console.log(arr[2][2]);
Multi-Dimensional Arrays
To access these nested array elements,
● First set of brackets refers to the entries in the outermost (the first level) array,
● Each additional pair of brackets refers to the next level of entries inside.
let arr = [
[1,2,3],
[[10,11,12], 13, 14]
];
console.log(arr);
arr.pop();
console.log(arr);
But how to iterate?
Now you might be wondering how can we traverse or iterate through this 2D arrays
‘a’ ‘b’ ‘c’ ‘d’ ‘e’ ‘f’ for(let i = 0;i < arr.length;i++) {
console.log(arr[i]);
0 1 2 3 4 5 }
Output:
‘a’
‘b’
‘c’
‘d’
‘e’
‘f’
How to traverse a 2D array?
0 1
Output:
0 ‘a’ ‘b’ ‘a’
‘b’
1 ‘c’ ‘d’
‘c’
2 ‘e’ ‘f’ ‘d’
‘e’
‘f’
Approach for traversing a 2D array
0 1
Output: How to access?
0 ‘a’ ‘b’ ‘a’ -> arr[0][0] -> row 0 col 0
‘b’ -> arr[0][1] -> row 0 col 1
1 ‘c’ ‘d’ ‘c’ -> arr[1][0] -> row 1 col 0
‘d’ -> arr[1][1] -> row 1 col 1
2 ‘e’ ‘f’ ‘e’ -> arr[2][0] -> row 2 col 0
‘f’ -> arr[2][1] -> row 2 col 1
Noticed a pattern?
-> To traverse a row -> Traverse all columns left to right in a row i.e. all for(let row = 0;row < arr.length;row++ ) {
elements of 1D array within the 2D array const arr1d = arr[row];
for(let col = 0;col < 1D array’s length;col++) // just like 1D array traversal. for(let col = 0;col < arr1d.length;col++) {
-> This is done for all the rows top to button i.e. all 1D arrays within the 2D console.log(arr[row][col]);
array. So, put the above loop within a loop for no. of rows. }
for(int row = 0;row < 2D array’s length;row++) // 2D array’s length = no. of }
//1D arrays in it
{
for(let col = 0;col < current 1D array’s length;col++)
}
Code demo - Nested For loops
}
Code Demo - Print a 2D Array with indexes
Op :
[0,0] = 0
[0,1] = 1
[1,0] = 2
[1,1] = 3
[2,0] = 4
[2,1] = 5
Activity - Generate a 2D array
LINK -
https://www.crio.do/learn/PSDS/ME_ES6_LOOPS_ARRAYS_2_NOSTUBS/ME_ES6_LOOPS_ARRAYS_2_N
OSTUBS_MODULE_CREATEMATRIXNOSTUBSES6/
Ip : Size = 3
Op : [ [ 0, 1, 2 ], [ 0, 1, 2 ], [ 0, 1, 2 ] ]
Activity - Generate a 2D array
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
6. Test the code (debug any syntax errors and logical errors)
5 mins break!
Consider a scenario…
● Suppose you want to store personal information like name, age and designation.
Let’s see how to create these arrays and access some value.
Consider a scenario…
This could be a cumbersome task if we have very big array then we need to iterate through the
array, now the question is can we do better?
Introduction to JavaScript Objects
Note - These objects are different from Class objects which we’ll deal with later in the sprint.
Creating Objects
Note: Creating object using new will be covered in a later sprint, when we discuss Classes.
Object Literal
Object is created with curly brackets {} and made up of key-value pairs, also referred to as properties.
const person = {
name: 'Dr Jack'
};
● We’ve created an object with one property inside it, one key-value pair.
● The key is named 'name' and the value is the string 'Dr Jack'.
Code Demo
Let’s try to create an object “shinobi” with all his details wherein
let shinobi = {
name: "Naruto Uzumaki",
age: 17,
village: "Leaf Village",
isNinja: true
}
Code Demo - Guess the output
let shinobi = {
console.log(typeof(shinobi.name)); // 1
name: "Naruto Uzumaki",
console.log(typeof(shinobi.family)); // 2
"family": "green",
console.log(typeof(shinobi.age)); // 3
isNinja: true
}
Activity - Creating an object
Give firstName, middleName and lastName as arguments, create an object with property:
● fullName as Key
● firstName, middleName and lastName concatenated as Value
Function should return the property?
Link:
https://www.crio.do/learn/PSDS/ME_ES6_LOOPS_ARRAYS_2/ME_ES6_LOOPS_ARRAYS_2_M
ODULE_GETFULLNAMEES6/
Activity - Creating an object
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
6. Test the code (debug any syntax errors and logical errors)
Consider a scenario…
● Let’s suppose that we are not aware of the properties that are required in the object at the time of
creation of object.
For example:
let ob = {
name: "Crio"
}
Code Demo - Adding Properties
● When the property name is known ahead of time you can access the values of these properties
using:
● JavaScript object keys cannot be number, boolean, null, or undefined type values.
Code Demo - Then what will be happen here?
var ob = { 1: "One" };
console.log(ob.name) // 1
console.log(ob[name]) // 2
Consider a scenario…
● You can add new properties the way you access them.
● Given that you have two properties firstName and lastName, we need to extract full name i.e
firstName + lastName how can we do that.
Code Demo - Adding new property
const details = {
lastName: "Doe"
console.log(details.fullName);
Consider a scenario…
● Suppose we have added a new property in the object now we want to check if the property exists not.
const personalDetails = {
const personalDetails = {
name: "John Doe",
name: "John Doe",
designation: "Data Analyst",
designation: "Data Analyst",
isEngineer: true
isEngineer: false
}
}
if(personalDetails.isEngineer)
if(personalDetails.isEngineer)
console.log("Property exists");
console.log("Property exists");
else
else
console.log("Property doesn't exists");
console.log("Property doesn't exists");
In left hand side when the value is true output is “Property exists” but when the value is false
output is “Property doesn’t exists” how can we solve this ambiguity.
Code Demo - Checking Properties
const personalDetails = {
name: "John Doe",
designation: "Data Analyst"
}
personalDetails.isEngineer = false;
console.log(personalDetails.hasOwnProperty('isEngineer')); // true
console.log(personalDetails.hasOwnProperty('Engineer')); // false
Code Demo - Removing properties
● Create a new object called person and give it properties like name, jobTitle, email,
isVerified (boolean, value = false) (Create operation)
● Print only the name and the verified status of the person. (Read operation)
● Remove the property name and add two new properties firstName and lastName (Delete
operation)
● Print the final object person.
Summary
Link: https://www.crio.do/magic/js101-arraymethods-and-objects
● Can you explain the difference between dot notation and square bracket
notation when accessing object properties? When would you use one over
the other?
(If any term in the above answer looks new to you, please just read it in the answer provided to get a high-level understanding.
You will learn more about it in the later sessions)
Thank you
Goals for Session 6
● Users should be able to create nested objects and access the properties.
● Users should be able to use destructing on objects as well as arrays.
● Users should be able to differentiate between arrays and objects.
● Users should be able to create and access array of objects.
● Users should be able understand special numbers in JavaScript.
While folks are joining -
● Searching in Array
■ Array.includes(value)
● String to Array - split()
● Array to String - join()
● Nested loops
● Multidimensional Arrays
● Introduction to JS Objects
● Creating, accessing & updating objects
Agenda
● Nested Objects
● Objects vs Arrays
● Destructuring
● Array of Objects
● Floating Point Numbers
● Special Numbers in JS
Consider a scenario…
● Suppose we want to store personal information of a person which is his name, designation, age,
and his address.
● But address contains locality, city, state and country, creating another doesn’t make any sense
as they are part of one object.
● The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
Code Demo - Updating Nested Objects
console.log(ourStorage.cabinet);
const ourStorage = { console.log(ourStorage.cabinet["top drawer"]);
"cabinet": {
"top drawer": { Updating properties // 2
const userDetails = {
name: {
first: "Kapil", ● Use the object given here .
last: "Raghuwanshi",
},
jobTitle: "JS Instructor @ Crio.do", ● Update the first and last properties with your details.
email: {
work: "[email protected]", ● Add new property isProMember to the status and
personal: "",
},
set it to false.
status: {
isOnline: true,
isVerified: false,
}
}
Code Demo - Object Destructuring
A better solution:
typeof in JavaScript is an operator used for type checking and returns a string
indicating the data type of the expression written in front of it.
Arrays are like objects in JS
Arrays in JS do not have a data type but are instead treated as objects with their indices as properties of
the object, and elements of the array as values.
If typeof for both arr and obj returns object how can we differentiate between the two?
Array.isArray(obj); //false
Array.isArray(arr); //true
Code Demo - Array Destructuring
Implement a function named mergedString that takes in an array of strings str. Implement
mergedString in such a way that it returns the merged string formed by only the first three
elements of the array. We have to use the destructuring syntax to extract the first three array
values.
Please note: The length of the array will always be greater than or equal to three.
Link:
https://www.crio.do/learn/PSDS/ME_ES6_OBJECTS_NOSTUBS/ME_ES6_OBJECTS_NOSTUBS_
MODULE_MERGEDSTRINGNOSTUBSES6/
Activity - Array Destructuring
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
6. Test the code (debug any syntax errors and logical errors)
5 mins break!
Let’s understand one use case
Let’s say we have 30 such objects of same type and if we want to perform operations
like insertion or deletion it will be cumbersome task.
Can we think of something wherein we can club these different students together?
Array of Objects
{
name: "Kevin",
rollNumber: 10,
stream: "PCM"
}
student [ Object #1
{
name: "Martin",
Object #1, rollNumber: 20,
stream: "PCM"
}
Object #2,
Object #2
Object #3
{
name: "Robert",
] rollNumber: 30,
stream: "PCB"
}
Object #3
Code Demo - Array of Objects
var student = [
{
name: "Kevin",
rollNumber: 10,
stream: "PCM"
},
{
name: "Martin",
rollNumber: 20,
stream: "PCM"
},
{
name: "Robert",
rollNumber: 30,
stream: "PCB"
}
]
Activity - Creating an array of object
var student = [
//How to name of 2nd student
{
console.log(student[1].name) //Austin
name: "Kevin",
std_id: 10
},
{
name: "Austin",
std_id: 20
}, //How to id of 3rd student
{ console.log(student[2]['std_id']) //30
name: "Robin",
std_id: 30
}
]
Activity - Access array of objects
—-----------------Input—-----------------
var student = [
{
name: "Kevin",
std_id: 10, —---------------Output—------------------
marks: 25
}, Austin
{
name: "Austin",
std_id: 20,
marks: 30
},
{
name: "Robin",
std_id: 30,
marks: 20
}
]
Can you guess the output?
console.log(202.2*2); 404.4
console.log(303.3*3); 909.9000000000001
We have been given two numbers `a` and `b`, we are dividing these numbers now how to take care of
the situation
let scale = 0;
let a = 0 / scale;
console.log(a);
let scale = 0;
let a = -1 / scale;
-Infinity
console.log(a);
let scale = 1;
-0
let a = -0 / scale;
console.log(a);
Summary
● The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
Link: https://www.crio.do/magic/js101-nestedobjects-specialnumbers
Please make sure you complete both of the quizzes mentioned in the Post-session task of
this session:
● Can you explain the difference between a shallow copy and a deep copy of
an object in JavaScript?
(If any term in the above answer looks new to you, please just read it in the answer provided to get a high-level understanding.
You will learn more about it in the later sessions)
Thank you
Goals for Session 7
● Nested Objects
● Objects vs Arrays
● Destructuring
● Array of Objects
● Floating Point Numbers
● Special Numbers in JS
What’s for this session?
Imagine you're developing an online budgeting tool where users enter their
daily expenses.
Some users enter exact amounts like $23.456, but we need a consistent way to
handle these decimals for calculations and display. We would like to consider just
the integer part i.e. given 23.456 we must consider 23.
● The JavaScript Math object allows you to perform mathematical tasks on numbers.
console.log(Math.trunc(23.456)); //23
Consider a case…
Now, suppose in the online budgeting tool you decide to make a change i.e.
instead of simply removing the decimal part, you decide to round it off based on
the decimal part.
So, if some user enters exact amounts like $23.456, it should be rounded off to
23, and if it is suppose $23.61 it should be rounded off to the next integer 24.
var a = 4;
var a = 4;
var b = 9;
var b = 9;
console.log(Math.round(a/b)); // 0
console.log(a/b); // 0.4444444444444444
var a = 4;
var a = 4;
var b = 8;
var b = 8;
console.log(Math.round(a/b)); // 1
console.log(a/b); // 0.5
Consider a case…
Now, suppose you have added a feature in your online budgeting tool that
predicts the budget you must have for next month based on this month’s
expense.
But, you need to show the lower integer part of the predicted value. E.g. if the
prediction is $23.456 the value logged on console must be 23, and even if it is
$23.61 it must show 23.
var a = 25;
var a = 25;
var b = 17;
var b = 17;
console.log(Math.floor(a/b)); // 1
console.log(a/b); // 1.4705882352941178
Consider a scenario…
let circumference = 2 * ℼ * r;
● We can get the value of mathematical constant using the PI property of the Math
built-in object, for example: Math. PI
● Math.PI represents the ratio of the circumference of a circle to its diameter, approximately
3.14159
𝙼𝚊𝚝𝚑.𝙿𝙸 = π ≈
3.14159
Code Demo - Calculate circumference of a circle
● Below the comment asking to define a function, you should define a function that takes in a
number value (radius) as a parameter and returns the circumference of the circle based on
that radius value.
● Below the comment asking to call a function, you must call the function that you have
defined and console log the value returned by it.
Question link:
https://www.crio.do/learn/PSDS/ME_ES6_MATH_FUNCTIONS_NOSTUBS/ME_ES6_MATH_F
UNCTIONS_NOSTUBS_MODULE_DIFFBETWEENMAXANDMINNOSTUBSES6/
Activity - Difference between max. and min.
7, 3, 8, 4 3
9, 1, 3, 4 8
Activity - Difference between max. and min.
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
7, 3, 8, 4 3
9, 1, 3, 4 8
Activity - Difference between max. and min.
6. Test the code (debug any syntax errors and logical errors)
Doc Reading - Math.abs()
Math.abs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs
Activity - Math.abs() predict output
console.log(Math.abs(-89.09)); // 89.09
console.log(Math.abs(-0)); // 0
Doc Reading - Math.sqrt()
Math. sqrt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt
Activity - Math.sqrt() predict output
console.log(Math.sqrt(25)); // 5
console.log(Math.abs(-100)); // 100
Consider a scenario…
Function Expression
console.log('Hello');
display(); // Hello
We assign it to a variable
● There’s another very simple and concise syntax for creating functions, that’s often better
than Function Expressions.
● It is written with a () => {} format, where => is called the fat-arrow or just arrow.
Code Demo - Arrow function
var call = () => console.log('Hello');
● If no argument then simply parenthesis. call(); // Hello
● If we have only one argument, then parentheses around parameters can be omitted.
● Arrow functions don't need an explicit return keyword to return a value unless a block {} is
specified.
● Create an arrow function which takes in two arguments return true if the both the
numbers are “even” else return false.
Code Demo
● Your friend gave you notes. You duplicated it and made some changes.
● Now the question is will those changes reflect in your friends notes.
● Boolean, number, string, null and undefined all are passed by value.
● Any changes that we make in the passed item with not reflect in the original item.
Activity - Pass by value
function add(num){
num = num + 10;
console.log(num); // What will be the output?
}
var num = 5;
add(num);
console.log(num); // What will be the output?
Let’s understand one use case
● Now you gave your friend a car to drive, but accidentally he scratched it.
● Any changes that we make in the passed item will reflect in the original item.
Code Demo - Pass by Reference
const obj = {
name: "Jhon"
}
function changeName(obj){
Jhon
obj.name = "Doe";
}
console.log("Object before function call");
console.log(obj.name);
changeName(obj);
console.log("Object after function call");
console.log(obj.name); Doe
Code Demo - Storing Reference
● If we initialize one object with another object, and we are making some changes,
those changes will also reflect in the original object as well.
const obj = {
name: "Jhon"
}
copy_obj.name = "Khaby"
console.log(copy_obj.name); // What will be the output?
Khaby
console.log(obj.name); // What will be the output?
Activity - Pass by Reference
Question Link:
https://www.crio.do/learn/PSDS/ME_ES6_MATH_FUNCTIONS/ME_ES6_MATH_FUNCTIO
NS_MODULE_WAYSOFPASSINGARGSIIES6/
Activity - Pass by Reference
[7, 3, 8, 4], 2, 7 7, 3, 7, 4
[2, 4, 6, 8], 5, 10 2, 4, 6, 8, 10
Activity - Pass by Reference
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
[7, 3, 8, 4], 2, 7 7, 3, 7, 4
[2, 4, 6, 8], 5, 10 2, 4, 6, 8, 10
Activity - Pass by Reference
6. Test the code (debug any syntax errors and logical errors)
Consider a case…
● Spread syntax can be used when all elements from an object or array need to be included in a
new array or object.
● If any changes are made in the new object or array those will not reflect in the original
object or array.
Code Demo - Spread Syntax
● The JavaScript Math object allows you to perform mathematical tasks on numbers.
● Arrow functions is another very simple and concise syntax for creating functions, that’s often
better than Function Expressions and is written: a () => {}, where => is called the fat-arrow or just
arrow.
● All the primitive data types are passed by value.
● All the non primitive data types are passed by reference.
● Spread syntax can be used when all elements from an object or array need to be included in a new
array or object.
End of session quiz
Link: https://www.crio.do/magic/js101-math-and-arrowfunctions
● What are the differences between arrow functions and function expressions
in JS?
(If any term in the above answer looks new to you, please just read it in the answer provided to get a high-level understanding.
You will learn more about it in the later sessions)
Thank you
Goals for Session 8
● Global Scope
● Local Scope
● Lexical Scope
● Hoisting
● Callback
● Closure
Consider a scenario…
Is there a way to make todoItem accessible only in the function addTodo() and not
outside it, in order to prevent unintentional addition of todos to the todoList.
Scope
● The scope is the extent to which a variable is accessible while executing the code.
How can we access todoList inside as well as outside of all the functions,
basically, everywhere in our program?
Global Scope
● If we want a variable to be accessible anywhere in the program we define it globally.
● Global scope is the outermost scope in the JavaScript.
Code Demo - Global Scope
function func(){
console.log("a is accessible within the function:", a);
}
func();
function display(){
var lastName = "Obrain";
console.log("FullName: " + firstName + " " + lastName );
}
display();
Updating the 'message' variable outside of the if-else block will override any values assigned
within these blocks.
Is there a way to restrict the scope of message to block level instead of function level?
Block Scope
● Block scope is a local scope bounded between two curly brackets {}.
● The block scope lets you limit the accessibility of all variables declared inside it.
Block Scope - ( let and const)
● Variables declared using let or const, can’t be accessed outside the curly brackets {}
Similarly, we will get the same error if we use const to declare message in
the if and else blocks.
Block Scope - ( var)
● Variables declared using var, can be accessed outside the curly brackets {}.
func ();
● What if we have a situation wherein we want to re-declare a variable using var, let or
const within a block/function with same name.
Can we do it?
Curious Cats - What will be the output?
Re-declaring variable using ‘var’
Output: 20
Output: 20
Output: 10
Curious Cats - What will be the output?
Re-declaring variable using ‘const’
Error: Identifier
'a' has already Error: Identifier
'a' has already Output: 10
been declared
been declared
Curious Cats - What will be the output?
Re-declaring variable using ‘let’
Error: Identifier
'a' has already Error: Identifier
'a' has already Output: 10
been declared
been declared
Activity - What will be the output?
var a = 10;
console.log(a);
if(a==10)
{
const a = 20;
console.log(a);
}
var a = 30;
console.log(a);
Consider a scenario…
● What if we have a situation wherein we want to inner scope has to access the variable of
the outer scope.
● Lexical scope is ability for a inner scope to access variables from the outer scope.
function parent() {
const message = "I am from parent";
function child() {
console.log(message + " Called from child function ");
}
child();
}
parent();
Activity - Lexical Scope
What we see?
console.log(a);
var a = 10;
var a;
console.log(a);
console.log(a);
var a = 10;
a = 10;
function func() {
console.log("hello");
func ();
}
function func() {
console.log("hello");
func ();
}
Now, can you guess?
var func;
func ();
func();
var func = function() {
func = function() {
console.log("hello");
console.log("hello");
}
}
func();
func ();
let func = function() {
let func = function() {
console.log("hello");
console.log("hello");
}
}
● You went to a repair shop to repair your bike, you told the guy who is repairing your bike
to call you once the work is done.
● Callbacks make sure that a function is not going to run before a task is completed but will
run right after the task has been completed.
Code Demo - Callback
calculator(5, 5, sum);
calculator(5, 5, multiply); // different callback, different answer
Closures
● If a function is created inside another function, it retains access to the scope of that
outer function even after that outer function returns, because the outer function is in
the lexical scope of the function.
Code Demo - Closures
function parentFunction() {
//Lexical Scope of childFunction() START
const message = "Hi! I'm a message from parent";
function childFunction() {
console.log(message);
}
return childFunction;
//Lexical Scope of childFunction() END
}
function multiply(storedNum) {
return function(num) {
return storedNum * num;
}
}
console.log(multiplyTwo(5));
console.log(multiplyThree(6));
console.log(multiplyFour(7));
Summary
● The scope is the extent to which a variable is accessible while executing the code.
● Global scope is the outermost scope in the JavaScript.
● Block scope is a local scope bounded between two curly brackets {}.
● Lexical scope is ability for a inner scope to access variables from the outer scope.
● Hoisting is a JavaScript mechanism where variables and function declarations are moved to
the top of their scope before code execution.
● A callback is a function passed into another function as an argument to be executed later.
● A closure refers to the lexical scope a function was declared in and the variables it has
access to.
End of session quiz
Link: https://www.crio.do/magic/js101-scope-hoisting-callback
● Global Scope
● Local Scope
● Lexical Scope
● Hoisting
● Callback
● Closure
What’s for this session?
● What if we want to iterate without incrementing the iterator or even checking the
condition explicitly and move to the next item.
Question Link:
https://www.crio.do/learn/PSDS/ME_ES6_CALLBACKS_SORTING/ME_ES6_CALLBACKS_SORTI
NG_MODULE_DIVIDEANDRETURNES6/
Activity - For...Each
[1, 6, 7] [ 1, 3, 2.3333333333333335 ]
Activity - For...Each
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
[1, 6, 7] [ 1, 3, 2.3333333333333335 ]
Activity - For...Each
6. Test the code (debug any syntax errors and logical errors)
Consider a scenario…
● If we want to search an element in the array, and get its first occurrence, how can we do
that?
const data = [
{ _id: "1", name: "Vivek" },
{ _id: "2", name: "Neha" },
{ _id: "3", name: "Satya" },
{ _id: "4", name: "Amit" },
];
Can we do better, is there an existing method that can help. Let’s find out.
Find
● find() method returns the value of the first element in the provided array that satisfies the
condition mentioned in the callback function.
find(callbackFn)
Code Demo - Find
const data = [
{ _id: "1", name: "Vivek" },
{ _id: "2", name: "Neha" },
{ _id: "3", name: "Satya" },
{ _id: "4", name: "Amit" },
];
const res = data.find((item) => item._id === "1");
console.log(res); //{ _id: '1', name: 'Vivek' }
Activity - Find
Question Link:
https://www.crio.do/learn/PSDS/ME_ES6_CALLBACKS_SORTING_NOSTUBS/ME_ES6_CALLBACKS_
SORTING_NOSTUBS_MODULE_FIRSTEVENNOSTUBSES6/
Activity - Find
[1, 2, 3, 4] 2
[1, 42, 3, 2, 3, 2] 42
Activity - Find
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
[1, 2, 3, 4] 2
[1, 42, 3, 2, 3, 2] 42
Activity - Find
6. Test the code (debug any syntax errors and logical errors)
Consider a scenario…
How can we do it ?
Introduction to Sorting
● sort() sorts elements of an array in-place and returns the sorted array.
● sort() tries to convert the array elements to strings first and sorts lexicographically
(dictionary order).
Let’s understand how to sort our number array by customising our sort method
in the next slide.
Code Demo - Sort Method with Comparator Function
nums.sort(function (a, b) {
if (a < b) return -1; // or any negative value
else if (a > b) return 1; // or any positive value
else return 0;
})
Code Demo - Sort an array in ascending order
const nums = [4, 20, 12, 11, 100, 0, 4]; const nums = [4, 20, 12, 11, 100, 0, 4];
Arrow Syntax
Expected Output:
5 min break!
Activity - Sort an array of objects
const array = [
Given an array of objects with different keys sort it {
using sort() method. name: "Kevi",
age: 25,
Print the names of the people in ascending order of
},
their age. {
name: "Arnold",
age: 6,
},
{
name: "Sheila",
age: 56,
},
];
Consider a scenario…
● Now we are doubling every number in the array and storing in a new array.
● Yes, we can make it even more modular, making it easy for us to go from doubling to tripling the
elements.
const arr = [10, 30, 50]; function multiplyElements(arr, mutiplyFn) {
const newArr = [];
function double(item){
return item * 2; for(let i = 0; i < arr.length; i++) {
} newArr[i] = mutiplyFn(arr[i]);
}
function multiplyByTwo(arr) { return newArr;
const newArr = []; }
● map() method that allows you to transforms the array elements in a cleaner way.
● map() method is used for creating a new array from an existing one, applying a function to
each one of the elements of the original array.
.
const arr = [10, 30, 50]; const arr = [10, 30, 50];
Arrow Syntax
● Given an array of numbers where each element represents the radius of a circle.
● We need to calculate the area of each circle and push the result into a new array.
● From the forked repl, open sess9/mapActivity.js. Write the required code after the
mentioned comment.
Input: [10, 30, 50]
Expected Output:
Consider a scenario…
let products = [
{ name: 'Laptop', category: 'Electronics', price:
1200 },
{ name: 'Shirt', category: 'Apparel', price: 50 },
// more products...
];
console.log(filteredProducts);
Can we do better?
Filter
● filter() method takes in a callback that applies a condition against each element of the array on
which the filter() is called.
● If this conditional returns true, the element gets pushed to the output array otherwise it will
not be pushed.
Code demo - filter()
let products = [
{ name: 'Laptop', category: 'Electronics', let filteredProducts = products.filter(product =>
price: 1200 }, product.category === 'Electronics');
{ name: 'Shirt', category: 'Apparel', price: 50 console.log(filteredProducts);
},
// more products...
];
console.log(filteredProducts);
Consider a scenario…
let cart = [
{ item: 'Book', price: 12.99 },
{ item: 'T-shirt', price: 19.99 },
// more items...
];
let total = 0;
for (let i = 0; i < cart.length; i++) {
total += cart[i].price;
}
Can we do better?
Reduce
● The reduce() method reduces an array of values down to just one value!
If initialValue is specified
- currentValue to be initialized to the first value in the array.
let cart = [
{ item: 'Book', price: 12.99 }, let total = cart.reduce((accumulator, currentItem) =>
{ item: 'T-shirt', price: 19.99 }, accumulator + currentItem.price, 0);
// more items...
]; console.log("Total price:", total);
let total = 0;
for (let i = 0; i < cart.length; i++) {
total += cart[i].price;
}
Question Link:
https://www.crio.do/learn/PSDS/ME_ES6_CALLBACKS_SORTING_NOSTUBS/ME_ES6_CALLBA
CKS_SORTING_NOSTUBS_MODULE_FINDSUMUSINGREDUCENOSTUBSES6/
Activity - Reduce
1, 2, 3, 4 10
4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)
1, 2, 3, 4 10
6. Test the code (debug any syntax errors and logical errors)
Consider a scenario…
let playlist = ['Song 1', 'Song 2', 'Song
3', 'Song 4']; ● Complexity: The code becomes
more complex, especially for
// Task: Remove 'Song 2' and add 'New simple operations.
Song' in its place
let newPlaylist = []; ● Error-Prone: Manual index
let removedSong = ''; management increases the risk of
for (let i = 0; i < playlist.length; i++) errors.
{
if (playlist[i] === 'Song 2') {
● Readability: Such code is harder to
removedSong = playlist[i]; read and maintain.
newPlaylist.push('New Song');
} else { Can we do better?
newPlaylist.push(playlist[i]);
}
}
playlist = newPlaylist;
console.log("Updated Playlist:",
playlist);
console.log("Removed Song:",
removedSong);
splice
● splice() not only modifies the array it's being called on, but it also returns a new array
containing the value of the removed elements.
Code demo - splice()
let playlist = ['Song 1', 'Song 2', 'Song let index = playlist.indexOf('Song 2');
3', 'Song 4']; if (index !== -1) {
removedSong = playlist.splice(index, 1,
// Task: Remove 'Song 2' and add 'New Song' 'New Song')[0];
in its place }
let newPlaylist = [];
let removedSong = ''; console.log("Updated Playlist:", playlist);
for (let i = 0; i < playlist.length; i++) { console.log("Removed Song:", removedSong);
if (playlist[i] === 'Song 2') {
removedSong = playlist[i];
newPlaylist.push('New Song');
} else {
newPlaylist.push(playlist[i]);
}
}
playlist = newPlaylist;
● We are given an index from which we want to delete all the elements in the array
function deleteElements(months,start){
months.splice(start);
}
● We are given an index from which we want to delete all the elements and also how many
elements to delete in the array ?
function deleteElements(months,start,deleteCount){
months.splice(start, deleteCount);
}
What if after deleting we want to add some item? Let’s find out how to do it.
Consider a scenario…
let allArticles = [
// array of 20 news articles...
];
console.log("Top 6 Articles:",topArticles);
Can we do better?
slice
● slice(start, end) copies or extracts a given number of elements to a new array, leaving the
● The slice() method selects from a given start, up to a (not inclusive) given end.
● The slice() method returns a new array containing the extracted elements.
Code demo - slice()
console.log("Top 6 Articles:",topArticles);
Summary
Link: https://www.crio.do/magic/js101-sorting-hof-advarray-methods
Please make sure you complete both of the quizzes mentioned in the Post-session task of
this session:
● JS Final Project
JS-101 Final Project
Utilize the JS knowledge you’ve gained in this sprint so far, to code up the below
mentioned program.
https://www.crio.do/magic/js-final-project
Problem Description
https://www.crio.do/magic/js-final-project
Make sure you follow the 6-step methodology mentioned in the link description.
https://help.crio.do/a/solutions/articles/82000901903?portalId=82000068258
Takehomes
https://www.crio.do/learn/PSDS/ME_ES6_INTERVIEW_CHALLENGE_NOSTUBS/
Thank you