0% found this document useful (0 votes)
13 views529 pages

Sprint 3-JS-102

The document outlines the goals and agenda for two JavaScript sessions, focusing on understanding JavaScript's necessity, executing simple programs, and working with data types and variables. It includes activities for practical coding experience on Repl.it, explanations of primitive data types, variable declaration, and naming conventions. The second session aims to cover expressions, operators, and functions, with a recap of previous concepts and interactive activities for learners.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views529 pages

Sprint 3-JS-102

The document outlines the goals and agenda for two JavaScript sessions, focusing on understanding JavaScript's necessity, executing simple programs, and working with data types and variables. It includes activities for practical coding experience on Repl.it, explanations of primitive data types, variable declaration, and naming conventions. The second session aims to cover expressions, operators, and functions, with a recap of previous concepts and interactive activities for learners.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 529

Goals for Session 1

● 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 -

1. Get your laptops ready


● Login to your replit
2. We will be learning and coding throughout the session!
Crio Foundation Series: JS
Session 1
Agenda

● Why do we need JavaScript?


● Compilation and Execution
● Your First program
● Data Types
● Variables
Why do we need JavaScript?

● Used for creating web pages.

● Adding behaviour and special effects to the webpage.

● Implementing complex features on web pages.


Introduction to Replit

● Replit allows us to write code on a browser.

Link: https://replit.com/~
Why is the template called NodeJS in replit?

Programming language JS Runtime Environment

Enables to write a set Provides an environment


of instructions. to execute those
instructions.
Demo - Running code on replit

● Fork the repl: https://replit.com/@crio-tools/Crio-JS101-ip#index.js


● Rename the repl in the format: JS101-<your-name>
● If you want to run a file, named index.js present in the sess1 folder, then, in
the Shell, type: node index.js and then hit Enter.
Consider a scenario..

Why isn’t the light turning on? Why isn’t our code working as intended?

Just like troubleshooting a light, console.log helps us investigate different


parts of our code to find and fix issues.
Code Demo - Printing “Hello World”

● Printing Hello World using JS

Meet your friend - console.log()

● console.log(“Hello World”)
Activity - Write your first program on replit

Write console.log(“Your Name”)


Consider a real-world scenario

In order to deal with different types of data in our program, we need Data-Types.
What are primitives?

Values which cannot be changed.


● Primitive Values are numbers and strings, among other things.

console.log(2);
console.log("hello");
Primitives Data Types

● Numbers (2, -100, 3.14, and others), used for math calculations.

● Strings ("hello", "abracadabra", and others), used for text.

● Booleans (true and false), used for logical operations.


5 mins break!
Consider a scenario..

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.

● We first declare the variable and then we assign the value


Recap - Variable Declaration

● The variable needs to be declared.


○ The variable declaration tells the operating system to reserve a piece of
memory with that variable name.
● Syntax for declaration:

Think of it as

Age

Labelling and reserving the box


before storing something
Code Demo - Declaration

● 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

● Variable reassignment is simple. Let’s understand with an example -


● For a variable age that was previously initialized with the value 20, you can reassign the
value 40 simply by -

var age = 20; Initialization


age = 40; Reassignment
Code Demo - Re-assignment

● Re-assignment

JS allows you to store a number (10) in a variable which had


a string (“Crio”) → Dynamically Typed
Activity - Declaring Variables

● Declare a variable greeter using var


● Initialize it with "hey hi"
● Print the variable greeter in your program. What do you get?
● Next, try re-assigning the variable to say "Hey"
● Print the variable greeter again.
Let’s understand one use case

● What if we have a variable whose value should not change during the execution of the
program.

e.g. var daysInWeek = 7;

● But if we will use var to declare this variable it can modified easily.

Does JS has a way of imposing this?


Recap - Assigning a value to a variable

● 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

Adding the contents into an


already existing and labelled
box
Const : Keyword and Syntax

● 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?

● Let’s suppose we have written a program containing 200 lines of code.


1.
● In line no. 7, we declared a variable using var temp. 2.
.....
.....
7. var temp = 10;
● In line no. 150, we again declared the same variable by oversight .....
using a var .....
.....
.....
.....
What do you think will happen? .....
150.var temp = “hello”;
.....
.....
This will work, without throwing any error. This is called 200.
as re-declaration of variable.
Let

● 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

Keyword Allows re-declaration Allows re-assignment?

var ✅ ✅

let ❌ ✅

const ❌ ❌
Activity - Playing with let
● Now re-declare a new variable using let

let greeting = "say Hi";


console.log(greeting)
let greeting = "say Hello";
console.log(greeting)
Activity - Playing with const
● Declare a variable greeting using const, and re-assign it to "say Hello"
const greeting = "say Hi";
greeting = "say Hello";

● Now, re-declare it to "say Hey"


const greeting = "say Hey";
Activity - Guess the output
Variables and values in memory
10
var a = 10;
console.log(a);

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

● Can the variable be given any name using any character?


E.g. Can we name a variable as 12_number i.e var 12_number?
Naming a variable

● Can we name a variable as 12_number i.e var 12_number ? No, we can’t.

Valid variable names should:

● Start with a letter, underscore, or dollar sign.

● After the first letter, you can use numbers, letters, underscores,
dollar signs.
What about naming a variable?

● Can we name a variable as const i.e var const;


Demo - What about naming a variable?

● Can we name a variable as const i.e var const; No, we can’t.

Valid variable names can’t be:

● Reserved keywords of JavaScript.


e.g. this, new, switch
Summary

● JavaScript is used for creating web pages.


● Primitive data types are string, boolean, number.

● Variables are named container used to store, change, and access information

● Valid variable names should:


○ Start with a letter, underscore, or dollar sign.
○ After the first letter, you can use numbers, letters, underscores, dollar signs.
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/datatypes-and-variables-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Interview Questions

● What are the different data types 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 2

● Users should be able to understand and evaluate expressions.


● Users should be able to use mathematical operators, along with precedence.
● Users should be able to use relational / logical operators.
● Users should be able to write simple If-Else statements
● Users should be able to write a simple function including how to pass parameters, calling a function
and how to return values from a function.
● Users should be familiar with Crio Platform.
● Users should be answer interview questions on Operators, Conditionals, and Functions.
While folks are joining -

1. Get your laptops ready


● Login to your Replit
2. We will be learning and coding throughout the session!
Crio Foundation Series: JS
Session 2
Recap from previous session

● Why do we need JavaScript?


● Compilation and Execution
● Your First program
● Data Types
● Variables
Agenda

● 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?

const total = mathMarks + scienceMarks;

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

We can perform basic arithmetic operations in JS programs by using 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

What if you want to obtain the value of a power of a particular number?

Example: What is 2 raised to 3? - How can you compute this programmatically is


JS?

Feel free to google it out.

2 ** 3
How do we compute the following?

Predict the output:

const x = 1 + 2 * 3;
console.log(x);

7 or 9? Confused?

In order to prevent such confusions, programming languages have a well


defined precedence for operators i.e. rules indicating a sequence.
Arithmetic Operators & Precedence

● Brackets ( … ) B
● Exponentiation (**) E
● Division ( / ) D
● Multiplication (*) M
● Modulus (Remainder) (%) R
● Addition (+) A
● Subtraction (-) S

Precedence (Order of evaluation)

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

console.log(3 + 4 * 5); 3 + (4 * 5) -> 3 + 20 -> 23

console.log(1 + 2 ** 3 * 4 / 5); 1 + (2 ** 3) * 4 / 5 -> 1 + 8 * 4 / 5 ->

1 + (8 * 4) / 5 -> 1 + 32 / 5 -> 1 + (32 / 5) ->

1 + 6.4 -> 7.4


Recap: Relational Operators

“==” not to be mistaken with “=”

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 );

What is the output ?


Activity - === v/s ==

In the previous slide, you saw both === and == returned false while comparing
equality of a and b. So, what’s the difference between them?

Feel free to google it out.

== ===

Loose equality i.e. checks only Strong equality i.e. checks on


on the basis of values, not the basis of values as well as
types. types.
Activity - === v/s ==

Predict the output:

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

Symbol How to read Evaluation

DOUBLE AND True if BOTH (left side


&& condition and right side
condition) are true

DOUBLE OR True if AT LEAST ONE (left side


|| condition or right side condition)
is true
Activity - Checking relationships II

let a = 10;
let b = 20;

console.log( a !== b && a > b );


console.log( a !== b || a > b );

What is the output ?


Recap - if else

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

● Check if a number is positive or negative.


● Print corresponding message based on the condition result
● Using If Else construct
6 step strategy to solve any problem

1. Understand the problem


2. Design test data/test cases (i.e. input and expected output)
3. Derive the solution (write pseudo code for the solution)
4. Test the solution (do a dry run of the pseudo code for the test data and confirm it works)
5. Write the program/code (using Javascript here)
6. Test the code (debug any errors)
Activity - If Else

● Given an age variable : const age = 16;

● Print “Can drive” if the age is greater than 18


● Print “Cannot drive” otherwise
● Use the If Else construct
5 mins break!
Consider a scenario

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.

One way is…

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

Hence, we need a piece of code that can:

1. Compute based on a parameter (e.g. compute square based on number


provided by user).
2. Be executed multiple times which might not necessarily be immediately one
after another.
3. Be modified by making changes at one single place.

Such a reusable piece of code is called as a function.


Syntax - Function

● Define a function :

function functionName(parameter) {

// the piece of code you want to have within the function

● 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

Define a function named getSum that takes in 2 numbers as parameters num1


and num2, and console log their sum.
Print the sum of 2 and 3 using getSum()
Print your name
Print the sum of 100 and 250
Consider a scenario

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.

We can do it by using the return keyword in JavaScript.

Note: In previous examples wherein we did not have any return statement, we were
returning undefined automatically.

Return statement is considered as the end


Code Demo - return

Define a function getSquare that takes in a number as a parameter and returns


the square of that number.

Get the square of 2 stored in mySqr1 using getSquare()


Get the square of 5 stored in mySqr2 using getSquare()
Print their sum: console.log(mySqr1 + mySqr2);
Activity - return

Define a function getDouble that takes in a number as a parameter and returns


the double of that number.

Get the square of 2 stored in myDouble1 using getDouble()


Get the square of 5 stored in myDouble2 using getDouble()
Print their sum: console.log(myDouble1 + myDouble2);
Consider a Scenario

For our calculator we want to display some greeting message to the user when
he/she starts the calculator.

Can you write a function for this?

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.

This is possible due to non-parametric function i.e. a function with no


parameters.
Activity - Non parametric 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

● Check if 2 numbers are equal


● Let’s look at how to solve this problem on Crio platform
● Writing code
○ Goal is to write code from scratch based on
■ The problem description
■ Function Signature(function name, parameters, what is to be returned)
■ The input data
■ The expected output
○ This function is then executed and return value is checked. Check last Hint to check code correctness.
○ Run Code
○ Submit
● Assessment tab (check results, understand what’s failing and fix it)
Code (from Scratch) Demo on Crio Platform

1. Understand the problem


Code (from Scratch) Demo on Crio Platform

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

89, 11 false

3, 3 true
Code (from Scratch) Demo on Crio Platform

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

89, 11 false

3, 3 true
Code (from Scratch) Demo on Crio Platform

5. Write the program/code (using JavaScript here)


Code (from Scratch) Demo on Crio Platform

6. Test the code (debug any syntax errors and logical errors)
Code Demo on Crio Platform

● Sum of Two Numbers


● Let’s look at how to solve this problem on Crio platform
● Writing code
○ Empty function provided
○ Goal is to complete this function based on
■ The problem description
■ The input data
■ The expected output
○ This function is then executed and return value is checked
○ Run Code
○ Submit
● Assessment tab (check results, understand what’s failing and fix it)
Code Demo on Crio Platform

1. Understand the problem


Code Demo on Crio Platform

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

89, 11 100

1, 2 3
Code Demo on Crio Platform

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

89, 11 100

1, 2 3
Code Demo on Crio Platform

5. Write the program/code (using JavaScript here)


Code Demo on Crio Platform

6. Test the code (debug any syntax errors and logical errors)
Demo - Introduction to Crio Platform

● Crio Javascript Platform


○ Screen with all problems -
https://www.crio.do/learn/PSDS/ME_ES6_OPERATORS_CONDITIONALS/

○ Select individual problem


○ Problem Description
○ Input and Expected output with examples
Summary

● Expressions are small units of code (literals, variables, operators, etc) that result in a value

● Mathematical operators & precedence order : () , / , * , % , + , -, **

● Relational / Logical operators : > , < , <= , <= , === , !== , && , ||

● if( condition ) {
//if condition is true, then do this
} else {
//if condition is false, then do this
}
Summary

● Function - to reuse code

● Non-Parametric:
function greet() {
console.log( “Hi” );
}

● Parametric:
function add( x, y ) { -> x & y are parameters
return x + y; -> To return the result value
}

● Parametric functions are called with arguments, ex.: add( 5, 2 ) ;


End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/conditionals-and-functions-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Interview Questions

● What is the difference between == and === in JS?


Thank you
Goals for Session 3

● 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 -

1. Get your laptops ready


● Login to your replit
2. We will be learning and coding throughout the session!
Crio Foundation Series: JS
Session 3
Recap from previous session

● 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

● If else chain, Nested if else - Part II


● Strings:
○ Accessing string characters & length
○ Immutability
● Template Strings
● String Methods
● Reading Documentation
Recap: if else chain
Use the else if statement to specify a new condition if the first condition is false.

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

Find the largest of 3 numbers -


● using If Else chain
● && operators
● and print the largest number
Activity - 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.

From the forked Repl, open sess3/smallest-user-ip.js.

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. Understand the problem


Code (from Scratch) Demo on Crio Platform

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

1, 9, 78 1

2, 3, 4 2
Code (from Scratch) Demo on Crio Platform

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

1, 9, 78 1

2, 3, 4 2
Code (from Scratch) Demo on Crio Platform

5. Write the program/code (using JavaScript here)


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

1. Understand the problem


Code (from Scratch) Demo on Crio Platform

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

25, 55 Eligible

15, 51 UnderAge

24, 48 NotEligible
Code (from Scratch) Demo on Crio Platform

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

25, 55 Eligible

15, 51 UnderAge

24, 48 NotEligible
Code (from Scratch) Demo on Crio Platform

5. Write the program/code (using JavaScript here)


Code (from Scratch) Demo on Crio Platform

6. Test the code (debug any syntax errors and logical errors)
Strings - Textual Data

Scenarios in web development where dealing with text is crucial.

● Wikipedia - textual info from website to users


● FB sign up - textual info from users to website
● WhatsApp web - textual info exchange among users via web
Strings

● A string is a sequence of zero or more characters


● Enclosed in single (‘) or double quotes (“)
● Starts and ends with same type of quotes

let favFood = ""; // or let favFood = ‘’;

let name = "Crio"; // or let name = ‘Crio’;


Code Demo - Strings

● String Length : Useful for data validation e.g. password length must be > 6 characters.

console.log(“Crio.do”.length) //prints 7

● We can use one type of quote inside another -

let favPhrase = 'My favorite phrase is "Good day"! Yours?';

● We can concatenate strings

let message = “Welcome, ” + “John!";


Consider a scenario..

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

● Bracket notation is a way to get a character at a specific index within a string.


● Indexing starts at Zero (0) instead of 1

const str = "Crio.do";

console.log(str[0]); //C

● We can also use charAt(index)

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.:

let str = “Hello!”;

console.log(str.charAt(6)); // empty string

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

1. Understand the problem


Code (from Scratch) Demo on Crio Platform

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

Anu, Rao AR

Ravi, Faizan RF
Code (from Scratch) Demo on Crio Platform

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

Anu, Rao AR

Ravi, Faizan RF
Code (from Scratch) Demo on Crio Platform

5. Write the program/code (using JavaScript here)


Code (from Scratch) Demo on Crio Platform

6. Test the code (debug any syntax errors and logical errors)
Code Demo - String Immutability

Let’s try out the following: Assign a new string:

let myStr = "Bob"; let myStr = "Bob";

myStr[0] = "J"; myStr = "Job";

console.log(myStr); console.log(myStr);

Individual characters of a String literal cannot be changed.

String values are immutable - they cannot be altered once created.


Consider a scenario…

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”

● Defines that JavaScript code should be executed in "strict mode".

● Strict mode changes previously accepted "bad syntax" into real errors.

● For example, with strict mode, you cannot use undeclared variables.
Activity - Strict Mode

Run the below code: Run the below code:

let myStr = "Bob"; "use strict"

myStr[0] = "J"; let myStr = "Bob";

console.log(myStr); myStr[0] = "J";

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.

E.g. Happy birthday Mohak!


You are 23 years old now.

How will you create such strings if we have the name and current age stored in
variables?

let name = “Mohak”;

let age = 22;


Template Strings / Template Literals

● A special type of string that makes creating complex strings easier


● Enclosed in backticks

● Allows multiline string formatting.

var str = `This is :

a template literal !` ;

● Variable or JS expression can also be within it, like below:

`${ variable or js expression }`


Code Demo - Template Strings

let firstName = "Mohak";

let age = 23;

const greeting = `Happy birthday, ${firstName}!,

Your are ${age + 1} years old now.`

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

1. Understand the problem


Code (from Scratch) Demo on Crio Platform

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

2 A circle of radius 2 has a diameter 4

3 A circle of radius 3 has a diameter 6


Code (from Scratch) Demo on Crio Platform

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

2 A circle of radius 2 has a diameter 4

3 A circle of radius 3 has a diameter 6


Code (from Scratch) Demo on Crio Platform

5. Write the program/code (using JavaScript here)


Code (from Scratch) Demo on Crio Platform

6. Test the code (debug any syntax errors and logical errors)
5 mins break!
String Methods

● String methods help us work with strings

● If updates are required on a string, since strings are immutable, these methods return a new
string with the modified value
Demo - Reading Documentation

● Here is the link:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/St
ring/lastIndexOf#using_indexof_and_lastindexof

● Go through Syntax, Description, Examples and the Try it out.


Code Demo - Positional String Methods

var str2 = "She sells seashells by the sea-shore";

console.log( str2.indexOf("sea") );

console.log( str2.lastIndexOf("sea") );

console.log( str2.indexOf("time") );
Activity - Positional String Methods

What will be the output?

var str = "Hey how are you doing";

console.log( str.indexOf("the") );

console.log( str.lastIndexOf("do") );

console.log( str.indexOf(" ") );


Consider a scenario…

Suppose we have usernames which are in the format:


“firstName-lastName-birthYear”.

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

● substring(startPos, endPos) extracts a part of a string and returns it in a new string.

● Starting position is from startPos (inclusive)

● Stopping position is just 1 before endPos (not inclusive)

● If endPos is not given, then from startPos till the end of the string is returned
Code Demo - Substring

let str = "Sun, Moon, Sky, Stars, Galaxy";

console.log( str.substring(5, 9) );

1. Guess the output


2. Using substring, print only Sun
3. Using substring, print everything starting from & including Sky
4. Print the length of the string
Concat

● str1.concat(str2) joins two or more strings

● can be used instead of the + operator (although + is preferred)

● can send multiple values : str1.concat(str2, str3, str4)


Code Demo - concat

var str = "Hello ";

var name = "Steve";

var res = str.concat(name, "! ", "How are you?");

console.log(res);

console.log( "".concat("My name is ", name) );


Summary

● If else chains are used to test for multiple mutually exclusive outcomes.

● Nested if else is used to test a combination of conditions within another condition.

● Strings are a collection of characters. Let str be a string


○ str.length returns length of the string
○ str[i] or str.charAt(i) returns character at (i)th index in the string
○ Strings are immutable
○ Template strings can be used to add JS expressions within a string
○ String methods can be used for processing strings
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/strings-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


End-of-week quizzes

Please make sure you complete both of the quizzes mentioned in the Post-session task of
this session:

1. Learning Outcome Quiz - 1


2. Interview Quiz - 1.

NOTE: The Interview Quiz is a mix of:


- Normal MCQs
- Video-recording based questions (You must record a video in which you give answer to
the mentioned interview question, just like you would answer it in an actual interview for a
job. You must upload your video to YouTube by following these instructions. The answer
explanation that appears after you submit your video link contains a well-crafted answer
that you can learn to ace your interviews.)
Interview Questions

● Can you explain the concept of String Immutability in JS?

● What are template literals in JavaScript, and how do they differ from
traditional string concatenation?

● What are some common methods to manipulate strings in JavaScript?


Thank you
Goals for Session 4

● Users should be able to understand loops in Javascript.


● Users should be able to create and use for loop.
● Users should be able to create arrays in Javascript and iterate over them.
● Users should be able to use different array methods like push, pop, shift, unshift, sort,
and reverse.
While folks are joining -

1. Get your laptops ready


● Login to your replit
2. We will be learning and coding throughout the session!
Crio Foundation Series: JS
Session 4
Recap from previous session

● If else chain, Nested if else - Part II


● Strings:
○ Accessing string characters & length
○ Immutability
● Template Strings
● String Methods
● Reading Documentation
Agenda

● Introduction to loops in JavaScript


● For Loop
● Introduction to Arrays
● Array Methods
○ push() and pop()
○ shift() and unshift()
○ sort()
○ reverse()
Recap - For Loop false

Notice the
1 2 semicolons?

for (initialization ; condition ; updation)


4
{ true

Block of code

} Exit
Code Demo - For Loop

Repeating your favorite song thrice with the appropriate message :

for (let i=1; i<=3; i++) {


console.log(`Favorite Song Repeat # ${i}`);
}
Activity - For Loop

LINK -
https://www.crio.do/learn/PSDS/ME_ES6_LOOPS_ARRAYS_1_NOSTUBS/ME_ES6_LOOPS_ARRAYS_1_N
OSTUBS_MODULE_SUMFIRSTNNUMBERSNOSTUBSES6/

Add the numbers from 1 to n using a For Loop on Crio Platform


Activity - For Loop

1. Understand the problem


Activity - For Loop

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

3 6

5 15
Activity - For Loop

3. Derive the solution (write pseudo code for the solution)


Activity - For Loop

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

3 6

5 15
Activity - For Loop

5. Write the program/code (using JavaScript here)


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

let simpleArray = ['one', 2, 'three', true, false, undefined];

console.log(simpleArray[0]); //"one"

simpleArray[1] = "two"; //mutation in place

● Array elements can be accessed and modified using bracket notation.

● Unlike strings, array entries are mutable & can be changed freely.
Array Indices & Values

Value 1 Value 2 Value 3

let simpleArray = [ 'one', 'two', 'three', true, false, undefined, 4 ];

Index 0 Index 1 Index 2


Activity - Create an array with different 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"

● Print only the second value of this array.


● Change the value of the 3rd index of the array, and set it to your name.
● Print the new array.
5 mins break!
Consider a scenario…
Array length

● .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

const simpleArray = [1,2,3,4];


for (let i=0; i < simpleArray.length; i++) {
console.log( simpleArray[i] );
}
Code demo - Array References

let x = [1, 2, 3]
let y = x
x[0] = 1000

console.log(x)
console.log(y)
Arrays Memory Representation

let x = [1, 2, 3]; [1000, 2, 3]


[1000, 2, 3]
let y = x;
x[0] = 1000;
console.log(x);
Console
console.log(y);

y
1000
1 2 3

x 0x12 0x20 0x28


0 1 2
Activity - Array References & Equality

Guess the output:

let a = [1, 2, 3]
let b = [1, 2, 3]
let c = a

console.log(a === b) console.log(a == b)


console.log(a === c) console.log(a == c)

== & === check the reference here


Activity Debrief false
true
let a = [1, 2, 3]; false
let b = [1, 2, 3]; true
let c = a;
console.log(a === b);
console.log(a === c); Console
console.log(a == b);
console.log(a == c);
c
1 2 3

a 0x74 0x82 0x90


0 1 2

1 2 3

b 0x12 0x20 0x28


0 1 2
Consider a scenario…

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”

“Omkar” “Mohak” “Ram”

0 1 2

“Omkar” “Mohak” “Ram” “Sanket”

0 1 2 3
Code demo - push()

.push() appends data to the end of an array & returns the new array length.

In CodeSandBox, create an array:

const ticketLine = [“Omkar”, “Mohak”, “Ram”];

Use push() to add a new element “Sanket”, as the last element of the ticketLine array.
Consider a scenario…

Suppose “Omkar” gets a ticket!

“Omkar” “Mohak” “Ram” “Sanket”

0 1 2 3

“Mohak” “Ram” “Sanket”

0 1 2
Code demo - shift()

.shift() removes the first element from an array and returns the removed element.

In replit, create an array:

const ticketLine = [“Omkar”, “Mohak”, “Ram”, “Sanket”];

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”

“Mohak” “Ram” “Sanket”

0 1 2

“Ruchir” “Mohak” “Ram” “Sanket”

0 1 2 3
Code demo - unshift()

.unshift() works like .push(), but adds the element at the beginning of the array.

In replit, create an array:

const ticketLine = [“Mohak”, “Ram”, “Sanket”];

Use unshift() to add “Ruchir” as the 0th element in the ticketLine array.
Consider a scenario…

“circle” “triangle” “rectangle”

0 1 2

Drawing Board in DrawApp “circle” “triangle”

0 1
Code demo - pop()

.pop() works like .shift(), but it removes the last element of the array.

In replit, create an array:

const shapes = [“circle”, “triangle”, “rectangle”];

Use pop() to remove the last element “rectangle” from the shapes array.
.

Array Methods at a glance


Array Methods

● .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

let arr = ['a','b','c'];

console.log( arr.push('d') ); console.log( arr.pop() );

console.log(arr); console.log(arr);

console.log( arr.unshift('e') ); console.log( arr.shift() );

console.log(arr); console.log(arr);
Activity - Todo List

1. Create a new empty array named todoDB

2. Write a function addTodo(item, priority) that:

a. Adds a new todo item to the list depending on the priority.

b. If the priority is 'high', then the item is added at the start, else at the end of the list
Consider a scenario…

const myPlaylist = [“Cheap Thrills”, “Check Kar”, “Vikram”];

const song = “Drag Me Down”;

Create a function findSong() that takes in myPlaylist


array and song string as arguments and returns the
index of the song if the song is present.

If the song is not present in the playlist, then we


must return nothing. But how do we indicate this
nothing programmatically in JS?

Answer: null
Code Demo - null

● In simple words, the null value is a value representing no value or nothing,


indicating intentional absence of a value.

● It is one of JavaScript's primitive values.

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.

const arr = [1, "Kevin", null, 0, true];


for(var itr = 0; itr < arr.length; itr++ ){
if(arr[itr] !== null && arr [itr] !== 0)
console.log(arr[itr]);
}

Does this cover all the cases ?

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 of these will evaluate to false, if it is used as a condition.

● 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

1. Understand the problem


Activity - Falsy Values

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

7, ate, "", false, 9 7, ate, 9

a, b, c a, b, c
Activity - Falsy Values

3. Derive the solution (write pseudo code for the solution)


Activity - Falsy Values

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

7, ate, "", false, 9 7, ate, 9

a, b, c a, b, c
Activity - Falsy Values

5. Write the program/code (using JavaScript here)


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

let arr = ['a','b','c','a','d','e','c','f','c'];

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

● Share the below link with the learners

Link: https://www.crio.do/magic/js101-strings-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Interview Questions

● What are some of the array methods in JavaScript?

● 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 -

1. Get your laptops ready


● Login to your replit
2. We will be learning and coding throughout the session!
Crio Foundation Series: JS
Session 5
Recap from previous session

● Introduction to loops in JavaScript


● For Loop
● Introduction to Arrays
● Array Methods
○ push() and pop()
○ shift() and unshift()
○ sort()
○ reverse()
Agenda

● 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…

Suppose you have your songs playlist stored as follows:


const myPlaylist = [“Cheap Thrills”, “Check Kar”, “Vaathi Coming”];

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) -

Checks if array contains given element (starting from an index - optional).

In case fromIndex is not mentioned, it is considered as 0.

Returns boolean value:


- true: if the element is present in the array within the index range fromIndex to last index.
- false: if the element is NOT present in the array within the index range fromIndex to last
index.
Code Demo - Searching in Arrays

let myPlaylist = ['On Top','Attention','Vikram','Sunflower','Vaathi Coming','Check


Kar','Circles'];

console.log( arr.includes('Vaathi Coming') );

console.log( arr.includes('Vaathi Coming', 5) );


Activity: Guess the Output

Can you guess the o/p for the following code without trying to run the code?

let myPlaylist = ['On Top','Attention','Vikram','Sunflower','Vaathi Coming','Check


Kar','Circles'];

console.log( arr.includes('Vikram', 5) );

console.log( arr.includes('Vikram') );
Consider a scenario…

Sign Up Form

Name John Wick fullName = “John Wick”;


// firstName = ??
// lastName = ??
Email [email protected]
String to Array - split()

● Splits a string into an array of substrings

● Syntax with optional parameter:

string.split(separator)

● If separator string is omitted, then an array with the original string is returned
Code Demo - split

const filePath = "users/john/documents/report.txt";

const pathSegments = filePath.split("/");

console.log(pathSegments);

const pathSegments2 =
"users/john/documents/report.txt".split();

console.log(pathSegments2);
Consider a scenario…

Sign Up Form

First Name John


name = [“John”, “Wick”];
// fullName = ??
Last Name Wick
Array to String - join()

● Joins an array to form a string

● Syntax with optional parameter:

array.join(separator)

● If separator string is missing, then default is a comma.


Code Demo - join

var pathSegments = ["Users", "John", "Documents", "report.txt"];

const filePath = pathSegments.join("/");

console.log(filePath);

const filePath2 = pathSegments.join();

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/

Write a function reverseString(str) which takes in a string parameter,

And returns a string which is the reverse of the original string, on Crio Platform.

Example: “hello” becomes “olleh”.


Activity - Reverse a string

1. Understand the problem


Activity - Reverse a string

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

welcome emoclew

first tsrif
Activity - Reverse a string

3. Derive the solution (write pseudo code for the solution)


Activity - Reverse a string

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

welcome emoclew

first tsrif
Activity - Reverse a string

5. Write the program/code (using JavaScript here)


Activity - Reverse a string

6. Test the code (debug any syntax errors and logical errors)
Summary: String ↔ Array

var str = "And so the adventure begins";

split(“ ”) join(“ ”)

var arr = [ 'And', 'so', 'the', 'adventure', 'begins' ];


Consider a scenario…

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

[[24, 71, 50],


[52, 50, 86],
[3, 0, 102]]

Break-down of this data storage:

one row data -> one array.


And, one column within that row -> one element with that array.

For multiple rows, create multiple such arrays.


Hence, we need an outer array to store all of these related arrays together.
This type of storage wherein we have array within an array is called as a
multidimensional array (2D array in our case).
Accessing Elements of Multi-Dimensional Arrays

1D Array: 2D Array:

let x = [a,b,c,d]; let y = [[a,b],[c,d]];


0 1 2 3 0 1

x[0] = a y[0] = [a,b] y[0][0] = a


x[1] = b 0 1 y[0][1] = b
x[2] = c y[1][0] = c
x[3] = d y[1] = [c,d] y[1][1] = d
0 1
Code Demo - 2D Array
let arr = [
[1,2,3],
[4,5,6],
[7,8,9],
];

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[1] ); // [ [ 10, 11, 12 ], 13, 14 ]


console.log( arr[1][0] ); // [ 10, 11, 12 ]
console.log( arr[1][0][1] ); // 11
console.log( arr[0][1] ); // 2
console.log( arr[1][2] ); // 14
Activity - Array Methods

let arr = [ [1,2],3,4 ];

● Push an empty array at the end. arr.push([]);

● Add an element to that new subarray.


console.log(arr);
● Remove the new subarray.
arr[3].push(5);

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

We will be use nested loops, i.e loop within a loop.

for( ; ; ){ // for iterating through rows


for( ; ; ){ // for iterating through columns
// do something
}
}
Recap: Traversing a 1D array

‘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

How nested for loops works?

for( let i=0; i < 3; i++ ) {

for( let j=0; j < 3; j++ ) {

console.log( ` i , j = ${i} , ${j} ` );

}
Code Demo - Print a 2D Array with indexes

Write a function printArray(arr) that:

● Runs through the given 2D array using nested loops


● And prints the element values with indexes

Ip : arr = [[0, 1], [2, 3], [4, 5]];

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

1. Understand the problem


Activity - Generate a 2D array

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

2 [[0, 1], [0, 1]]

3 [[0, 1, 2], [0, 1, 2], [0, 1, 2]]


Activity - Generate a 2D array

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

2 [[0, 1], [0, 1]]

3 [[0, 1, 2], [0, 1, 2], [0, 1, 2]]


Activity - Generate a 2D array

5. Write the program/code (using JavaScript here)


Activity - Generate a 2D array

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.

● Only way we can think of is an array i. e, we will create 2 arrays:


○ One to store the keys name, age and designation
○ Second to store the values “Kevin” , 24, and “Developer”

Let’s see how to create these arrays and access some value.
Consider a scenario…

var key = ["name", "age", "designation"];

var value = ["Kevin", 24, "Developer"];

let keyName = "age"; // This is the key


let indexNeeded = key.indexOf(keyName); // This is the index of the key
let valueNeeded = value[indexNeeded]; // Value associated with the required index.

console.log(keyName + " : " + valueNeeded);

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

● Objects are another way to store a collection of values. {


email: “[email protected]”,
● Objects are made up of key-value pairs know as properties. name: “Beaver”
}

Note - These objects are different from Class objects which we’ll deal with later in the sprint.
Creating Objects

There are 3 ways to create an object:

1. Using object literal

2. Empty object and then add properties

3. Using new keyword

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

● Every property is separated by comma, and


● Property values can be of any datatype

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

age: 17, console.log(typeof(shinobi.village)); // 4

'village': "Leaf Village", console.log(typeof(shinobi.isNinja)); // 5

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

1. Understand the problem


Activity - Creating an object

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

"Alex", "P", "John" { fullName: 'Alice P John' }

"Code", "Crio", "Do" { fullName: 'Code Crio Do' }


Activity - Creating an object

3. Derive the solution (write pseudo code for the solution)


Activity - Creating an object

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

"Alex", "P", "John" { fullName: 'Alice P John' }

"Code", "Crio", "Do" { fullName: 'Code Crio Do' }


Activity - Creating an object

5. Write the program/code (using JavaScript here)


Activity - Creating an object

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.

● Now we want to add properties, how can we do that.

For example:

let ob = {
name: "Crio"
}
Code Demo - Adding Properties

● Creating an empty object and then adding properties.

● Now that we have an object we need to add one more property.


How can we access properties?

● When the property name is known ahead of time you can access the values of these properties

using:

○ Dot Notation (object.property)


Code Demo - Accessing Objects

let ob = {name: "Crio", location: "Bengaluru"};


console.log(ob.name); // Crio
Things to know about Keys

● Object keys can only be strings.

● JavaScript object keys cannot be number, boolean, null, or undefined type values.
Code Demo - Then what will be happen here?

var ob = { 1: "One" };

● Will this give any error? //1

● If it works then how? //2


Code Demo - How can we access this property

● You can access the values of these properties using:

○ Bracket Notation (test["name"])

let ob = {1: "One"};


//console.log(ob.1 ); error
console.log(ob[1]);
Code Demo - Accessing Objects

What will be the output:

let name = "Crio"

let ob = {name: "Criodo"}

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 = {

firstName: "John ",

lastName: "Doe"

details.fullName = details.firstName + details.lastName;

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.

Added property “isEngineer”

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

● delete operator is used to remove properties.


Activity - CRUD our objects

● 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)

● Change the isVerified status to true. (Update operation)

● Remove the property name and add two new properties firstName and lastName (Delete
operation)
● Print the final object person.
Summary

● includes() checks if array contains given element


● split() splits a string into an array of substrings
● join() joins an array to form a string
● Objects are another way to store a collection of values.
● Objects are made up of key-value pairs know as properties.
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/js101-arraymethods-and-objects

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Interview Questions

● Can you explain the difference between dot notation and square bracket
notation when accessing object properties? When would you use one over
the other?

● Explain the difference between null and undefined.

(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 -

1. Get your laptops ready


● Login to your replit
2. We will be learning and coding throughout the session!
Crio Foundation Series: JS
Session 6
Recap from previous session

● 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.

const personalDetails = { const address = {


name: "Jhon Doe”, locality: "1600 rose lane colony",
designation: "Developer", city: "Mumbai",
age: 24 state: "Maharashtra",
} country: "India"
}
Object - 1
Object - 2

This is where nested objects comes into picture.


Nested Objects

● Object properties can have objects as their values also.

● The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
Code Demo - Updating Nested Objects

What will be the output? //1

console.log(ourStorage.cabinet);
const ourStorage = { console.log(ourStorage.cabinet["top drawer"]);
"cabinet": {
"top drawer": { Updating properties // 2

"folder1": "a file", ourStorage.cabinet["top drawer"].folder1 = "few files";


ourStorage.cabinet["top drawer"].folder2 = "secret files";
"folder2": "secrets"
},
} What will be the output? // 3
}; console.log(ourStorage.cabinet["top drawer"].folder1);
console.log(ourStorage.cabinet["top drawer"].folder2);
Activity- Accessing Nested Objects

const personalDetails = { What will be output?


name: "John Doe",
designation: "Data Analyst",
age: 24, console.log (personalDetails.address); //1
address: {
locality: "1600 roselane colony",
city: "Mumbai", console.log (personalDetails.address.city); //2
state: "Maharashtra",
or
country: "India" console.log(personalDetails['address']['city']);//2
}
}
Activity - Nested Objects

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

● The destructuring assignment syntax in JavaScript expression makes it possible to unpack


values from arrays, or properties from objects, into distinct variables.

● Object destructuring can extract multiple properties in one statement.

const obj = { name: “Ravi”, age: 20 };

var name = obj.name;


// unpacking object without destructuring
var age = obj.age;

const { name, age } = obj; //unpacking object properties using destructuring


Consider a scenario…

Suppose a function showEmployeeDetails() takes in an object as an argument,


that has the following structure:

and console logs all the properties’ values.


Possible solution

One way is…

But, can we do better?


Object Destructuring

A better solution:

Object destructuring assigns the properties of an object to variables with the


same names by default.
Activity - Object Destructuring Debugging
There is an error in the code, let’s fix that.
Link:https://www.crio.do/learn/PSDS/ME_ES6_OBJECTS/ME_ES6_OBJECTS_MODULE_DEBUGOBJECTDESTRUCTURINGES6/
typeof

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.

Note: typeof arr; // “object”


Code Demo - Object vs Array

const obj = {"name":"crio.do"};

const arr = [4,7,8,0,6];

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

● Destructuring works for Arrays as well.

const [a, b] = [10, 20]; //a = 10, b = 20


Activity - 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

1. Understand the problem


Activity - Array Destructuring

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

["code", “for”, “good”, “vibes”, “only”] code for good

["code", “for”, “good”, “intent”] code for good


Activity - Array Destructuring

3. Derive the solution (write pseudo code for the solution)


Activity - Array Destructuring

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

["code", “for”, “good”, “vibes”, “only”] code for good

["code", “for”, “good”, “intent”] code for good


Activity - Array Destructuring

5. Write the program/code (using JavaScript here)


Activity - Array Destructuring

6. Test the code (debug any syntax errors and logical errors)
5 mins break!
Let’s understand one use case

var student1 = { var student2 = { var student3 = {


name: "Kevin", name: "Martin", name: "Robert",
rollNumber: 10, rollNumber: 20, rollNumber: 30,
stream: "PCM" stream: "PCM" stream: "PCB"
} } }

Object #1 Object #2 Object #3

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

● Create an object of car which has three properties:


○ color
○ type
○ capacity
● Create an vehicle array having 3 such type of objects.
Recap - accessing array elements and object properties

Let’s go back to how we accessed arrays and objects.

var arr = [ 1, 2, 3];


var obj = {
arr[1] = 10;
name: "Kevin",
age: 24
}
obj.name = "Brain" // or obj['name'] = "Brain"

Array elements are accessed and


modified using bracket notation.
Properties of an object can be accessed using
dot or bracket notation.
Code Demo - Access array of objects

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

● Given an array of objects as an argument, we have to return the name of


student with maximum marks? ( Length of the array always greater than 0)

—-----------------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

Is there any mistake in the second statement?


Floating Point Numbers

● JavaScript treats decimals as floating point numbers.

● Operations like addition, multiplication, etc are subject to rounding error.


Let’s understand one use case

We have been given two numbers `a` and `b`, we are dividing these numbers now how to take care of
the situation

when a is equal to a non zero number and b is equal to zero

Can you think of something or does JavaScript take care of that.


Demo - Special Numbers

let scale = 0;

let a = 1 / scale; Infinity


console.log(a);
Demo - More Special Numbers

let scale = 0; NaN

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

● Object properties can have objects as their values also.

● The sub-properties of objects can be accessed by chaining together the dot or bracket notation.

● The destructuring assignment syntax in JavaScript expression makes it possible to unpack


values from arrays, or properties from objects, into distinct variables.

● JavaScript treats decimals as floating point numbers.


End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/js101-nestedobjects-specialnumbers

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


End-of-week quizzes

Please make sure you complete both of the quizzes mentioned in the Post-session task of
this session:

1. Learning Outcome Quiz - 2


2. Interview Quiz - 2

NOTE: The Interview Quiz is a mix of:


- Normal MCQs
- Video-recording based questions (You must record a video in which you give answer to
the mentioned interview question, just like you would answer it in an actual interview for a
job. You must upload your video to YouTube by following these instructions. The answer
explanation that appears after you submit your video link contains a well-crafted answer
that you can learn to ace your interviews.)
Interview Questions

● How are arrays different from objects in JavaScript?

● Explain array destructuring and object destructuring in JavaScript.

● 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

● Users should be able to use math function and constants.


● Users should be able to differentiate between normal functions and arrow functions.
● Users should be able to understand how pass by value works.
● Users should be able to understand how pass by reference works.
While folks are joining -

1. Get you laptops ready


● Login to your replit

2. We will be learning and coding throughout the session!


Crio Foundation Series: JS
Session 7
Recap from previous session

● Nested Objects
● Objects vs Arrays
● Destructuring
● Array of Objects
● Floating Point Numbers
● Special Numbers in JS
What’s for this session?

● Math Functions & Constants


● Arrow Functions
● Pass by value
● Pass by reference
Consider a scenario…

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.

Is there a way to do this in JS?


Code Demo - Math Functions

● The JavaScript Math object allows you to perform mathematical tasks on numbers.

● Solving the earlier problem, we use truncate method.

Math.trunc(x) returns the integer part of x.

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.

Is there a way to do this in JS?


Code Demo - Math.round

With Math Function


Without Math Function

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.

Can this be done in JS?


Demo - Math.floor

With Math Function


Without Math Function

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…

Suppose we want to write a program that calculates the circumference of a


circle when radius value is given.

let circumference = 2 * ℼ * r;

But, how can we get ℼ value in JS?


Mathematical constant property

● 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

● From the forked repl, open sess7/circle-user-ip.js

● 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.

● Circumference of Circle = 2 * ℼ * radius;


Activity - Difference between max. and min.

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.

1. Understand the problem


Activity - Difference between max. and min.

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

7, 3, 8, 4 3

9, 1, 3, 4 8
Activity - Difference between max. and min.

3. Derive the solution (write pseudo code for the solution)


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)

Input Expected Output

7, 3, 8, 4 3

9, 1, 3, 4 8
Activity - Difference between max. and min.

5. Write the program/code (using JavaScript here)


Activity - Difference between max. and min.

6. Test the code (debug any syntax errors and logical errors)
Doc Reading - Math.abs()

● Read the following doc to understand Math.abs()

Math.abs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs
Activity - Math.abs() predict output

What will be output?

console.log(Math.abs(-89.09)); // 89.09

console.log(Math.abs(-0)); // 0
Doc Reading - Math.sqrt()

● Read the following doc to understand Math.sqrt()

Math. sqrt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt
Activity - Math.sqrt() predict output

What will be output?

console.log(Math.sqrt(25)); // 5

console.log(Math.abs(-100)); // 100
Consider a scenario…

● We have a scenario where we want to create a function with no name meaning


we want to create anonymous functions.

How can we do that?


Function Expressions

Function Expression

Function Declaration function (){


console.log('Hello)
}
function display() {

console.log('Hello');

} You might be thinking how are we going to call this function?

display(); // Hello
We assign it to a variable

var call = function (){


console.log('Hello') // Hello
}
call();
Alternative syntax for function expressions
var call = () {
console.log('Hello');
Function Expression Removed ‘function’ }
call();

var call = function (){ Added ‘arrow’


console.log('Hello')
}
call();

var call = () => {


console.log('Hello');
}
call();
Arrow Functions

● 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.

var call = (a) => console.log(a);


call(8); // 8

var call = a => console.log(a);


call(8); // 8
Code Demo - Arrow function

● Arrow functions don't need an explicit return keyword to return a value unless a block {} is
specified.

- Without block & return

var call = a => a * 10;


call(8); // 80

- With block & return

var call = a => {


a = a * 10;
return a
}
call(8); // 80
Activity - Arrow Function

● Create an arrow function which takes in two arguments return true if the both the
numbers are “even” else return false.
Code Demo

● From the forked repl, open sess7/funcConv.js


● Below the first comment define ‘squareExpr()’ as function expression
version of the given square() function declaration.
● Below the second comment define ‘squareArrow()’ as arrow function
version of the given square() function declaration.
● You must be able to see output after correct implementation:
5 min break!
Let’s understand one use case

● Your friend gave you notes. You duplicated it and made some changes.

● Now the question is will those changes reflect in your friends notes.

If you thinking - NO ( you are right)

The next question is how can we do it in the programming world?


Pass by Value

● All the primitive data types are passed by value.

● 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.

● Now the question is will those scratches reflect in your car.

If you thinking - YES ( you are right)

The next question is how can we do it in the programming world?


Pass by Reference

● All the non primitive data types are passed by reference.

● Arrays, objects and functions all are passed by reference.

● 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"
}

var copy_obj = obj; Jhon


console.log(obj.name); // What will be the output?

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

1. Understand the problem


Activity - Pass by Reference

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

[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

3. Derive the solution (write pseudo code for the solution)


Activity - Pass by Reference

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

[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

5. Write the program/code (using JavaScript here)


Activity - Pass by Reference

6. Test the code (debug any syntax errors and logical errors)
Consider a case…

Updating a user profile with new information.


Spread Syntax(...)

● 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

Updating a user profile with new information.


Activity - Predict the output
Summary

● 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

● Share the below link with the learners

Link: https://www.crio.do/magic/js101-math-and-arrowfunctions

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Interview Questions

● What are the differences between arrow functions and function expressions
in JS?

● What are the differences between pass-by-value and pass-by-reference in


JS?

● Differentiate between the rest and spread operators 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 8

● Users should be able to understand both global and local scope.


● Users should be able to differentiate between block and function scope.
● Users should be able to understand how hoisting works.
● Users should be able to understand callbacks.
● Users should be able to understand what is closure and how it works.
While folks are joining -

1. Get you laptops ready


● login to your replit

2. We will be learning and coding throughout the session!


Crio Foundation Series: JS
Session 8
Recap from previous session

● Math Functions & Constants


● Arrow Functions
● Pass by value
● Pass by Reference
What’s for this session?

● 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.

● Scope basically partitions the visibility of variables throughout the program.


Consider a scenario…

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

var a = 10; // variable 'a' global scope

function func(){
console.log("a is accessible within the function:", a);
}
func();

console.log("a is accessible outside the function:", a);

Note: Global variable in one file, can be accessed in other file.


Local Scope

If we want a variable to be accessible locally in the program we define it:

1. Within a function (Function scope - var )

2. Within a block (Block scope - let & const)


Recap: Consider a scenario…
Code Demo - Function Scope
Activity - What will be the output & why?

var firstName = "Kevin";

function display(){
var lastName = "Obrain";
console.log("FullName: " + firstName + " " + lastName );
}

display();

console.log("FullName: " + firstName + " " + lastName );


Consider a scenario…

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 {}

Let’s see how?


Code Demo - let and const

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 {}.

Let’s see how?


Code Demo - var
Activity - Scope of var

var a =10; // global variable

func ();

function func() { ‘x’ can be accessed within the block scope


if(a==10)
{
var x =10;
console.log(x);
}
console.log(x); ‘x’ can be accessed outside the block scope
}
console.log(x);

‘x’ can’t be accessed outside the function scope


Consider a scenario…

● 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’

if(1){ var a = 10;


var a = 10;
var a = 10;
var a = 20;
var a = 20; func();
} function func() {
console.log(a);
console.log(a); var a = 20;
}
console.log(a);

Output: 20
Output: 20
Output: 10
Curious Cats - What will be the output?
Re-declaring variable using ‘const’

if(1){ const a = 10;


const a = 10;
const a = 10;
const a = 20;
const a = 20; func();
} function func() {
console.log(a);
console.log(a); const a = 20;
}
console.log(a);

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’

if(1){ let a = 10;


let a = 10;
let a = 10;
let a = 20;
let a = 20; func();
} function func() {
console.log(a);
console.log(a); let a = 20;
}
console.log(a);

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.

Is there a way to do it or is this even possible?


Lexical Scope

● Lexical scope is ability for a inner scope to access variables from the outer scope.

● That means inner scope is lexically bound to the outer scope.


Code Demo - Lexical Scope

function parent() {
const message = "I am from parent";

function child() {
console.log(message + " Called from child function ");
}
child();
}

parent();
Activity - Lexical Scope

var x = 10; // global scope

var outerFunc = function (){ // outermost function


var y = 20;
console.log(x + " " + y);

var innerFunc= function (){ // innermost function


var z = 30;
console.log(x + " " + y + " " + z);
}
innerFunc();
}
outerFunc();
5 min break!
Activity - Predict the o/p

What we see?

console.log(a);
var a = 10;

We think output should be an error.


Hoisting

● Hoisting is a JavaScript mechanism where variables and function declarations are


moved to the top of their scope before code execution.
Code Demo - Hoisting Variable Declaration

What we saw? What actually happens?

var a;
console.log(a);
console.log(a);
var a = 10;
a = 10;

Now, can you guess?

We think output should be an error.


undefined

Variables declared with const and let are not hoisted.


Code Demo - Hoisting Function Declaration

What we see? What actually happens?

function func() {
console.log("hello");
func ();
}
function func() {
console.log("hello");
func ();
}
Now, can you guess?

We think output should be an error. hello

Remember “Function Declarations” are hoisted entirely.


Code Demo - Hoisting Function Expression

What we see? What actually happens?

var func;
func ();
func();
var func = function() {
func = function() {
console.log("hello");
console.log("hello");
}
}

Now, can you guess?

We think it will be hello. Error: func is not a function

Remember “Function Expressions” are hoisted partially.


Code Demo - Hoisting Function Expression

What we see? What actually happens?


(As let/const are not hoisted)

func();
func ();
let func = function() {
let func = function() {
console.log("hello");
console.log("hello");
}
}

Now, can you guess?

We think it will be hello. Error: Cannot access 'func' before initialization

Remember “let and const” are not hoisted.


Consider a scenario…

● 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.

How can we do it in the programming world.


Callback

● In JavaScript, a callback is a function passed into another function as an argument to be


executed later.

● 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

function bikeRepair(){ function bikeRepair(funcToExecuteLater){


console.log("Working on bike"); console.log("Working on bike");
} //once the work is done
Now let’s pass one function funcToExecuteLater();
}
as an argument to other
function callOwner(){
console.log("Take back bike");
function callOwner(){ }
console.log("Take back bike");
} bikeRepair(callOwner);
Activity - Callback
What will be the output:

function sum(n1, n2) {


console.log(n1 + n2);
}

function multiply(n1, n2) {


console.log(n1 * n2)
}

function calculator(num1, num2, operation) {


console.log(`Calculating on ${num1} and ${num2}`)
operation(num1, num2);
}

calculator(5, 5, sum);
calculator(5, 5, multiply); // different callback, different answer
Closures

● Closure = Function + Lexical Environment

● 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
}

const ans = parentFunction();


ans();
Activity - What will be the output?

function multiply(storedNum) {
return function(num) {
return storedNum * num;
}
}

const multiplyTwo = multiply(2);


const multiplyThree = multiply(3);
const multiplyFour = multiply(4);

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

● Share the below link with the learners

Link: https://www.crio.do/magic/js101-scope-hoisting-callback

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Interview Questions

● What are the differences between var, let and const?

● Explain Hoisting in JS.

● What is a callback function in JavaScript?

● What are Closures in JS?


Thank you
Goals for Session 9

● Users should be able to understand advanced callback methods like for…each


and find.
● Users should be able to use sort method and how it sort lexicographically.
● Users should be able to understand map, filter and reduce and differentiate
between them.
● Users should be able to understand advanced array methods like splice and slice.
While folks are joining -

1. Get you laptops ready


● login to your replit

2. We will be learning and coding throughout the session!


Crio Foundation Series: JS
Session 9
Recap from previous session

● Global Scope
● Local Scope
● Lexical Scope
● Hoisting
● Callback
● Closure
What’s for this session?

● Advanced array callback functions


● Sorting
● Map, Filter and Reduce
● Advanced array functions
○ Splice
○ Slice
Consider a scenario…

● If we wanted to iterate through the elements we used a for or while loop.

● What if we want to iterate without incrementing the iterator or even checking the
condition explicitly and move to the next item.

Is there a way to do it? How can we do it in the JS programming world.


For...Each

● forEach is invoked on an array, it iterates or loops through the array.

● Runs a Callback function on each value in the array.

● When the loop ends forEach returns undefined.


Code Demo - For...Each

Without arrow syntax With arrow syntax

const nums = [1, 2, 3, 4]; const nums = [1, 2, 3, 4];


nums.forEach( function iterate(value) { nums.forEach((value) => console.log(value));
console.log(value);
});
For...Each - Commonly used variations

● foreach(value) - value is the element in the array

● foreach(value, index) - index is the index of the element in the array


Code Demo - For...Each

const nums = [1, 2, 3, 4];


nums.forEach((value, index) => {
console.log("Element " + value + " is at index " + index);
});
Activity - For...Each

Question Link:
https://www.crio.do/learn/PSDS/ME_ES6_CALLBACKS_SORTING/ME_ES6_CALLBACKS_SORTI
NG_MODULE_DIVIDEANDRETURNES6/
Activity - For...Each

1. Understand the problem


Activity - For...Each

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

[2, 3, 4] [2, 1.5, 1.3333333333333333]

[1, 6, 7] [ 1, 3, 2.3333333333333335 ]
Activity - For...Each

3. Derive the solution (write pseudo code for the solution)


Activity - For...Each

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

[2, 3, 4] [2, 1.5, 1.3333333333333333]

[1, 6, 7] [ 1, 3, 2.3333333333333335 ]
Activity - For...Each

5. Write the program/code (using JavaScript here)


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" },
];

for (var itr = 0; itr < data.length; itr++){


if(data[itr]._id === "4"){
console.log(data[itr]);
break;
}
}

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. Understand the problem


Activity - Find

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

[1, 2, 3, 4] 2

[1, 42, 3, 2, 3, 2] 42
Activity - Find

3. Derive the solution (write pseudo code for the solution)


Activity - Find

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

[1, 2, 3, 4] 2

[1, 42, 3, 2, 3, 2] 42
Activity - Find

5. Write the program/code (using JavaScript here)


Activity - Find

6. Test the code (debug any syntax errors and logical errors)
Consider a scenario…

● Suppose we have a situation where we want to arrange a bunch of students according to


their names in alphabetical order.

How can we do it ?
Introduction to Sorting

● sort() sorts elements of an array in-place and returns the sorted array.

● The default sort order is ascending.


Code Demo - Sorting

var arr = ["Xavi", "Zaltan", "Messi", "Aguero"];


arr.sort();
console.log(arr);

[ 'Aguero', 'Messi', 'Xavi', 'Zaltan' ]


Code Demo - Sorting

const nums = [4, 20, 12, 1, 100];


console.log(nums.sort()); // Q. What would this print?

[1, 100, 12, 20, 4]

Let’s understand why in the next slide.


Sorting Number 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

We can customise how sort is done with a comparator function.

● The comparator functions takes in two arguments to compare (say a and b)


a. If the function returns -ve number then that means to sort a before b
b. If the function returns a +ve number that means to sort b before a
c. If the function returns 0 then it means to keep the original ordering of a and b

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];

nums.sort (function (a, b) { nums.sort (function (a, b) {


if (a < b) return a - b
return -1; Same thing can be written as });
});
console.log(nums);
console.log(nums)

Arrow Syntax

const nums = [4, 20, 12, 11, 100, 0, 4];


nums.sort ((a, b) => a - b);
console.log(nums);
Activity - Sort an array in Descending order

● Sort an array in descending order using arrow syntax.


● From the forked repl, open sess9/sortActivity.js. Write the required code below the
mentioned comment

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…

● Suppose we have an array of numbers arr.

let arr = [ 10, 30, 50 ];

● Now we are doubling every number in the array and storing in a new array.

let newArr = []; // storing doubles


for (let i = 0; i < arr.length; i++) {
newArr[i] = arr[i]* 2;
}
console.log(newArr); // [ 20, 60, 100 ]
Can we do better?

● Yes, we can turn it into a function so that we can reuse it.

const arr = [10, 30, 50];


let arr = [ 10, 30, 50 ];
function multiplyByTwo(arr) {
const newArr = [];
let newArr = []; // storing doubles
for (let i = 0; i < arr.length; i++) {
for(let i = 0; i < arr.length; i++) {
newArr[i] = arr[i] * 2;
newArr[i] = arr[i] * 2;
}
}
return newArr;
console.log(newArr); // [ 20, 60, 100 ]
}

const arrDoubled = multiplyByTwo(arr);


console.log(arrDoubled); // [ 20, 60, 100 ]
Can we do better?

● 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 = []; }

for(let i = 0; i < arr.length; i++) { const arr = [10, 30, 50];


newArr[i] = double(arr[i]);
} function mutiplyFn(item){
return newArr; return item * 2;
} }

const arrDoubled = multiplyByTwo(arr); const arrDoubled = multiplyElements(arr, mutiplyFn);


console.log(arrDoubled); // [ 20, 60, 100 ] console.log(arrDoubled); // [ 20, 60, 100 ]
Can we simplify it even further ?

● Yes, we can. This is where map comes to rescue

● 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.
.

Let’s us see how?


Code Demo - Map

function multiplyElements(arr,mutiplyFn) { function multiplyElements(arr, mutiplyFn) {


const newArr = []; const newArr = [];

for(let i = 0; i < arr.length; i++) { for(let i = 0; i < arr.length; i++) {


newArr[i] = mutiplyFn(arr[i]); newArr[i] = mutiplyFn(arr[i]);
} }
return newArr; return newArr;
} }

const arr = [10, 30, 50]; const arr = [10, 30, 50];

function mutiplyFn(item){ function mutiplyFn(item){


return item * 2; return item * 2;
} }

const arrDoubled = multiplyElements(arr,mutiplyFn); const arrDoubled = arr.map(mutiplyFn);


console.log(arrDoubled); // [ 20, 60, 100 ] console.log(arrDoubled); // [ 20, 60, 100 ]
console.log(arr); // original array is unchanged
Code Demo - Map

const arr = [10, 30, 50];


const arr = [10, 30, 50]; Anonymous function
const arrDoubled = arr.map(function (item){
function mutiplyFn(item){ return item * 2;
return item * 2; });
} console.log(arrDoubled);

const arrDoubled = arr.map(mutiplyFn);


console.log(arrDoubled); // [ 20, 60, 100 ]

Arrow Syntax

const arr = [10, 30, 50];


const arrDoubled = arr.map((item) => item * 2);
console.log(arrDoubled);
Activity - Map

● 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...
];

let filteredProducts = [];


for (let i = 0; i < products.length; i++) {
if (products[i].category === 'Electronics') {
filteredProducts.push(products[i]);
}
}

console.log(filteredProducts);

● More code to write.


● Higher chance of errors.
● Less readable and maintainable.

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...
];

let filteredProducts = [];


for (let i = 0; i < products.length; i++) { ● Conciseness and readability.
if (products[i].category === 'Electronics') {
filteredProducts.push(products[i]); ● Less room for error.
} ● Easier to understand and maintain.
}

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;
}

console.log("Total price:", total);

● More verbose and complex for


simple aggregations.
● Higher chance of making errors.
● Less efficient for operations on
large arrays.

Can we do better?
Reduce

● The reduce() method reduces an array of values down to just one value!

● The reduce() method does not change the original array.


Reduce

const newArray = array.reduce(accumulatorFn,initialValue);

(accumulator, currentValue, index, currentArray) => {


//Reducer logic
}
Reduce
1. accumulator: The accumulator accumulates callback's return values. It means it stores all the values
returned by callback. It can be a number, an array or an object(Required Parameter)
2. currentValue: Current value is similar to array[i] when we iterate over array using for loops
(Required)
3. index: Current index of the item (Optional Parameter)
4. currentArray: We are iterating over, in this case it is "array"(Optional)
5. initialValue: A value to use as the first argument to the first call of the callback (Optional)

If initialValue is specified
- currentValue to be initialized to the first value in the array.

If initialValue is not specified


- accumulator is initialized to the first value in the array, and currentValue is initialized to the second
value in the array.
Code Demo - reduce()

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;
}

console.log("Total price:", total);


Activity - Reduce

Question Link:

https://www.crio.do/learn/PSDS/ME_ES6_CALLBACKS_SORTING_NOSTUBS/ME_ES6_CALLBA
CKS_SORTING_NOSTUBS_MODULE_FINDSUMUSINGREDUCENOSTUBSES6/
Activity - Reduce

1. Understand the problem


Activity - Reduce

2. Design test data/test cases (i.e. input and expected output)

Input Expected Output

1, 2, 3, 4 10

32, 33, 16, 40 121


Activity - Reduce

3. Derive the solution (write pseudo code for the solution)


Activity - Reduce

4. Test the solution (do a dry run of the pseudo code for the test data and
confirm it works)

Input Expected Output

1, 2, 3, 4 10

32, 33, 16, 40 121


Activity - Reduce

5. Write the program/code (using JavaScript here)


Activity - Reduce

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() allows us to add and/or remove array elements inplace

● 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;

console.log("Updated Playlist:", playlist);


console.log("Removed Song:", removedSong);
Splice Variations

● splice(start) - Takes in the start index of the array.

● splice(start, deleteCount) - Deletes the deleteCount number of elements from the


start index.

● splice(start, deleteCount, newItem1) - Adds new element newItem1 right after


the delete operation.
Code Demo - splice

● We are given an index from which we want to delete all the elements in the array

function deleteElements(months,start){
months.splice(start);
}

const months = ['Jan', 'March', 'April', 'June'];


deleteElements(months, 1);
console.log(months); // [‘Jan’]
Code Demo - splice

● 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);
}

const months = ['Jan', 'March', 'April', 'June'];


deleteElements(months, 1, 2);
console.log(months); // [‘Jan’, ‘June’]

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...
];

let topArticles = [];


for (let i = 0; i < 6; i++) {
topArticles.push(allArticles[i]);
}

console.log("Top 6 Articles:",topArticles);

● It requires more code for a simple task.


● It's less efficient and more prone to errors,
especially with larger arrays or complex
conditions.
● The intent of the code is not immediately
clear.

Can we do better?
slice

● slice(start, end) copies or extracts a given number of elements to a new array, leaving the

array it is called upon untouched.

● 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()

let allArticles = [ let allArticles = [


// array of 20 news articles... // array of 20 news articles...
]; ];

let topArticles = []; let topArticles = allArticles.slice(0, 5);


for (let i = 0; i < 6; i++) {
topArticles.push(allArticles[i]); console.log("Top 5 Articles:", topArticles);
}

console.log("Top 6 Articles:",topArticles);
Summary

● forEach() method calls a function for each element in an array.


● find() method returns the value of the first element in the provided array that
satisfies the provided testing function.
● sort() method sorts elements of an array in-place lexicographically and returns the
sorted array.
● 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.
● filter() method takes each element in an array and it applies a conditional statement
against it.
● reduce() method reduces an array of values down to just one value.
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/js101-sorting-hof-advarray-methods

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


End-of-week quizzes

Please make sure you complete both of the quizzes mentioned in the Post-session task of
this session:

1. Learning Outcome Quiz - 3


2. Interview Quiz - 3

NOTE: The Interview Quiz is a mix of:


- Normal MCQs
- Video-recording based questions (You must record a video in which you give answer to
the mentioned interview question, just like you would answer it in an actual interview for a
job. You must upload your video to YouTube by following these instructions. The answer
explanation that appears after you submit your video link contains a well-crafted answer
that you can learn to ace your interviews.)
Interview Questions

● Differentiate between map(), filter() and reduce()

● Describe the features described in ES6.


(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 sprints)
Thank you
While folks are joining

● Please wait for other folks to join :)


Crio Sprint: JS-101
Today’s Session Agenda

● 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

Input: 1237 Output: Miraculous

Input: 567 Output: Non Miraculous


Implementation Requirements and Hints
It’s time to code!

https://www.crio.do/magic/js-final-project

Make sure you follow the 6-step methodology mentioned in the link description.

You have 40 minutes.


JS-101 Final Project Debrief
Sprint Summary

● Please find the summary of JS-1 sprint below:

https://help.crio.do/a/solutions/articles/82000901903?portalId=82000068258
Takehomes

Do not forget to complete your take-home exercise:

https://www.crio.do/learn/PSDS/ME_ES6_INTERVIEW_CHALLENGE_NOSTUBS/
Thank you

You might also like