0% found this document useful (0 votes)
26 views97 pages

Notes - JavaScript Zero To Hero in 5 Days

Uploaded by

josis69689
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)
26 views97 pages

Notes - JavaScript Zero To Hero in 5 Days

Uploaded by

josis69689
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/ 97

9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Notes - JavaScript Zero to Hero


in 5 Days

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 1/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Basics of JavaScript

Introduction

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 2/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

History of JavaScript
The history of JavaScript is a fascinating journey through the evolution of web
development. Here's a concise overview of its key milestones:

1. Birth of JavaScript:

• JavaScript was created by Brendan Eich in 1995 while he was working at


Netscape Communications Corporation.

• Originally named "Mocha" and later "LiveScript," it was eventually


renamed JavaScript to capitalize on the popularity of Java at the time.

2. Browser Wars:

• JavaScript became a key player in the "Browser Wars" of the late 1990s,
as Netscape and Microsoft Internet Explorer competed to dominate the
web.

• Microsoft introduced its own version of JavaScript called JScript, creating


compatibility issues.

3. Standardization:

• In 1997, JavaScript was submitted to the European Computer


Manufacturers Association (ECMA) for standardization. This led to the
creation of ECMAScript, a standardized specification for the language.

• ECMAScript 3 (ES3) became the de facto standard for JavaScript, which


all major browsers implemented.

4. Quiet Years:

• After the initial fervor, JavaScript development slowed, and it was


primarily used for simple client-side interactions like form validation and
simple animations.
5. Ajax and Web 2.0:

• In the early 2000s, JavaScript saw a resurgence with the advent of Ajax
(Asynchronous JavaScript and XML), which enabled smoother and more
interactive web applications.

• The rise of Web 2.0 brought JavaScript to the forefront, as it became a


fundamental part of creating dynamic and responsive web experiences.
6. ECMAScript 5 (ES5):

• In 2009, ECMAScript 5 introduced several new features and


improvements, making JavaScript more powerful and efficient.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 3/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

7. ECMAScript 6 (ES6) and Beyond:

• ECMAScript 6, released in 2015, brought significant enhancements to


JavaScript, including new syntax, classes, and modules.

• Subsequent ECMAScript versions (ES7, ES8, etc.) introduced further


features and improvements to the language.
8. Node.js:

• In 2009, Ryan Dahl introduced Node.js, which allowed developers to run


JavaScript on the server-side, enabling full-stack development with a
single language.
9. Modern JavaScript:

• Today, JavaScript is an integral part of web development, powering both


client-side and server-side applications.

• Popular frameworks and libraries like React, Angular, and Vue.js have
emerged, simplifying front-end development.
10. The Future:

• JavaScript continues to evolve, with new features and proposals


constantly being discussed and implemented.

• The rise of Progressive Web Apps (PWAs), WebAssembly, and the


growing importance of JavaScript in mobile app development
demonstrate its enduring relevance.
In summary, JavaScript has come a long way from its humble beginnings as a
simple scripting language to become a versatile and essential tool for building
modern web applications. Its vibrant ecosystem and ongoing development
ensure its continued prominence in the world of programming.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 4/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Program, Programming and Programmer


1. Program:

• A program is a set of instructions or code that tells a computer what


tasks to perform.

• It is typically written in a programming language and consists of a


sequence of commands and algorithms designed to achieve a specific
outcome or solve a particular problem.

• Programs can range from simple scripts that automate repetitive tasks
to complex software applications like word processors, web browsers,
and video games.
2. Programming:

• Programming is the process of creating and designing programs by


writing and organizing code.

• Programmers use programming languages to communicate with


computers, providing step-by-step instructions that the computer can
understand and execute.

• Programming involves tasks such as problem-solving, algorithm design,


debugging, and testing to ensure that a program functions correctly.

3. Programmer:

• A programmer, often referred to as a software developer or coder, is a


person who writes, maintains, and debugs computer programs.

• Programmers are skilled in various programming languages and


technologies and have a deep understanding of software development
principles.

• They work on a wide range of projects, from developing mobile apps


and websites to creating complex software systems and algorithms.

• Programmers play a crucial role in translating human ideas and


requirements into functional computer programs, making technology
more accessible and useful to people.
In summary, a program is a set of computer instructions, programming is the
process of creating these instructions, and a programmer is the individual
responsible for writing and maintaining the code that makes software and
applications function. Together, they form the foundation of the software
development process, driving technological innovation and solving real-world
problems.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 5/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

How Does JavaScript Work on the Web?


JavaScript plays a vital role in how websites and web applications function. It's a
client-side scripting language, which means it runs in the user's web browser
rather than on a remote server. Here's how JavaScript works on the web:
1. Incorporation into HTML: JavaScript is typically embedded within HTML
documents using <script> tags. These tags can be placed in the HTML
<head> or <body> section of a web page. For example:

<script> // JavaScript code goes here </script>

2. Downloading: When a user visits a web page, their browser downloads the
HTML, CSS, and JavaScript files associated with that page. JavaScript files
often have the .js extension.
3. Execution: Once downloaded, the browser executes the JavaScript code
sequentially, line by line. It can be executed either inline (within the HTML
file) or from external JavaScript files linked to the HTML file.
4. Manipulating the Document Object Model (DOM): One of the primary
functions of JavaScript on the web is to interact with the Document Object
Model (DOM), which is a representation of the webpage's structure.
JavaScript can:

• Access and modify HTML elements and their attributes.

• Add or remove elements dynamically.

• Change the content, style, and behavior of the webpage in response to


user interactions or events.
5. Handling User Events: JavaScript allows developers to define event handlers
that respond to user interactions like clicks, mouse movements, and
keyboard inputs. These event handlers can trigger specific actions or
functions when events occur.

6. Asynchronous Requests: JavaScript can make asynchronous requests to web


servers using technologies like the XMLHttpRequest (XHR) object or the
modern Fetch API. This enables dynamic content loading, allowing web
applications to update without requiring a full page reload.
7. Client-Side Validation: JavaScript is often used for client-side form
validation, ensuring that user input is correct before submitting it to the
server. This enhances the user experience by providing immediate feedback.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 6/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

8. Interactivity and Animations: JavaScript can create interactive elements,


such as image sliders, interactive maps, and games. It's also used for
animations and transitions, providing a visually appealing user experience.

9. Browser Compatibility: Developers need to consider browser compatibility


when using JavaScript, as different browsers may interpret and execute
JavaScript code differently. Libraries like jQuery and modern JavaScript
frameworks like React and Angular help manage these differences.
10. Security: Security is a crucial consideration when working with JavaScript.
Developers must prevent common security vulnerabilities like Cross-Site
Scripting (XSS) and Cross-Site Request Forgery (CSRF) by sanitizing user
input and following best practices.

In summary, JavaScript enhances the interactivity and functionality of web pages


by running client-side code in the user's browser. It can manipulate the DOM,
handle user interactions, make asynchronous requests, and create dynamic web
experiences. JavaScript is a fundamental technology in modern web
development, enabling web applications to be more responsive and user-
friendly.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 7/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Setting Up the Coding Environment


Setting up a coding environment for JavaScript with Visual Studio Code (VS
Code) is straightforward and can greatly enhance your development experience.
Here's a step-by-step guide to help you get started:

1. Install Visual Studio Code:

• If you haven't already, download and install Visual Studio Code from the
official website (https://code.visualstudio.com/).

• Follow the installation instructions for your operating system (Windows,


macOS, or Linux).

2. Open Visual Studio Code:

• Launch VS Code after the installation is complete.

3. Install Extensions:

• VS Code offers a wide range of extensions that can enhance your JavaScript
development experience. You can access extensions by clicking on the
Extensions icon in the sidebar or using the shortcut Ctrl+Shift+X
(Windows/Linux) or Cmd+Shift+X (macOS).

• Search for and install popular extensions like "ESLint" for code linting,
"Prettier" for code formatting, and "Live Server" for running web applications
locally.

• These extensions help you maintain clean and well-organized code.


4. Create a JavaScript Project:

• You can work with JavaScript files directly in VS Code, but for larger projects,
it's a good practice to create a dedicated project folder.

• Open VS Code and create a new folder for your project. You can do this via
the File > Open Folder menu.

5. Create a JavaScript File:

• Inside your project folder, create a new JavaScript file with the .js
extension. You can do this by right-clicking the folder in the Explorer panel
and selecting "New File."
6. Writing and Running JavaScript Code:

• Open your JavaScript file in VS Code by double-clicking it in the Explorer


panel.

• Write your JavaScript code in the editor.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 8/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

• To run your JavaScript code, you can use the built-in Node.js runtime if your
code is server-side. For client-side JavaScript (browser), you can use
extensions like "Live Server" to launch a local development server.

• For Node.js, open the integrated terminal in VS Code using Ctrl+``


(backtick) or by selecting "View > Terminal" from the menu. Then,
navigate to your project folder and execute your JavaScript file using
the node command, e.g., node myscript.js`.

7. Debugging:

• VS Code offers powerful debugging capabilities for JavaScript. You can set
breakpoints, inspect variables, and step through your code.

• To debug your JavaScript code, create a launch.json configuration file by


clicking the gear icon in the Run and Debug sidebar panel, then select "Add
Configuration."

• Follow the prompts to set up a debugging configuration for your project.


8. Save Your Work:

• Always remember to save your changes in VS Code by pressing Ctrl+S


(Windows/Linux) or Cmd+S (macOS).

With these steps, you'll have a fully functional JavaScript coding environment set
up in Visual Studio Code, ready to create, test, and debug your JavaScript
applications with ease. You can further customize your environment by exploring
VS Code's extensive settings and additional extensions as needed.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 9/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

How do Browsers Execute JavaScript?


Browsers execute JavaScript by following a specific process that allows them to
interpret and run JavaScript code within web pages. Here's a high-level overview
of how browsers execute JavaScript:

1. HTML Parsing and DOM Construction:

• When a user navigates to a web page, the browser begins by parsing the
HTML and constructing the Document Object Model (DOM). The DOM
is a tree-like representation of the web page's structure, including its
HTML elements, attributes, and their relationships.

2. Encounter JavaScript:

• As the browser parses the HTML and encounters JavaScript code, it


recognizes it within <script> tags, both inline (within the HTML file)
and external (linked via a separate .js file).

• JavaScript code can also be included in event attributes (e.g., onclick )


and in other HTML elements, such as <a> tags with javascript: URLs.

3. JavaScript Engine:

• The browser's JavaScript engine (e.g., V8 in Google Chrome,


SpiderMonkey in Firefox, or JavaScriptCore in Safari) is responsible for
executing JavaScript code.

• The engine reads and interprets the JavaScript code, converting it into
executable instructions.
4. Execution Context:

• For each <script> block or function call, the JavaScript engine creates
an execution context. This context includes information like variables,
function references, and the call stack.

• The global execution context is created for the entire page.


5. Execution and Scope:

• JavaScript code is executed in a specific order, typically from top to


bottom. Functions and variables are hoisted, meaning they are
registered in the scope before actual execution.

• Variables and functions are accessible based on their scope (e.g., global
or local), and lexical scope rules determine how JavaScript identifies
variable references.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 10/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

6. Event Loop and Callback Queue:

• JavaScript is single-threaded, meaning it executes one task at a time. To


handle asynchronous operations like user interactions or network
requests, browsers employ an event loop.

• Asynchronous tasks are placed in a callback queue. When the main


execution stack is empty, the event loop picks tasks from the queue and
executes them.

7. Interacting with the DOM:

• JavaScript can interact with the DOM, allowing it to manipulate web


page content, styles, and structure dynamically.

• Browsers provide APIs like document and window that JavaScript code
can use to access and modify the DOM.
8. Network Requests:

• JavaScript can initiate network requests using mechanisms like


XMLHttpRequest (XHR) or the Fetch API to communicate with servers
and retrieve data asynchronously.

9. Error Handling:

• Browsers handle JavaScript errors by capturing them, logging them to


the console, and potentially displaying error messages to users.

• Developers can use try...catch blocks to handle exceptions gracefully.


10. Garbage Collection:

• Browsers have built-in garbage collectors that manage memory by


identifying and freeing up memory used by objects and variables that
are no longer in use.
In summary, browsers execute JavaScript by interpreting and executing code
within web pages. This process involves parsing HTML, constructing the DOM,
running JavaScript code within a JavaScript engine, managing execution
contexts and scopes, handling asynchronous tasks, interacting with the DOM
and network, and performing error handling and memory management. This
complex orchestration allows for dynamic and interactive web experiences.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 11/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Where to write JavaScript?


JavaScript can be written in various places depending on your needs and the
context of your web development project. Here are some common places where
you can write JavaScript code:

1. Inline within HTML:

• You can write JavaScript directly within HTML documents using the
<script> element. This approach is useful for adding small scripts or
event handlers to specific HTML elements.

• Example:

<button onclick="myFunction()">Click me</button> <script> func


tion myFunction() { alert('Hello, World!'); } </script>

2. External JavaScript Files:

• For more extensive JavaScript code or when you want to reuse code
across multiple pages, it's common to create separate .js files and link
them to your HTML documents using the <script> element's src
attribute.

• Example:

<script src="myscript.js"></script>

• myscript.js is a separate JavaScript file containing your code.

Logging into Browser

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 12/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

console.log & clear Functions


The console.log() function is a commonly used JavaScript function that allows
you to log messages, data, or any information to the console, which is typically a
part of the browser's developer tools or the Node.js environment. It's a valuable
tool for debugging, testing, and understanding how your code is executing.
Here's how to use console.log() :

console.log(message1, message2, ..., messageN);

• message1 , message2 , ..., messageN are one or more values or expressions


that you want to display in the console. You can pass multiple arguments
separated by commas.

Example usage:

const name = "John"; const age = 30; console.log("Hello, World!"); //


Log a simple string console.log("My name is", name, "and I am", age,
"years old."); // Log multiple values

Common Use Cases:

1. Debugging: You can use console.log() to output variable values or debug


messages to the console to understand the flow of your code.

const x = 5; console.log("The value of x is:", x);

1. Inspecting Objects and Arrays: You can inspect the contents of objects and
arrays to better understand their structure and content.

const person = { name: "Alice", age: 25 }; console.log("Person objec


t:", person); const numbers = [1, 2, 3, 4, 5]; console.log("Numbers ar
ray:", numbers);

1. Timing: In addition to logging data, you can measure the time it takes for
certain operations using console.time() and console.timeEnd() to start
and stop timers.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 13/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

console.time("Timer"); // Some code to measure console.timeEnd("Time


r");

1. Conditional Logging: You can conditionally log messages based on specific


conditions.

const isError = true; if (isError) { console.error("An error occurre


d!"); } else { console.log("Operation successful."); }

1. Styling Output: You can apply styling to your console messages using CSS-
like syntax in some browser environments. For example:

console.log("%cStyled Text", "color: blue; font-size: 16px;");

1. Clearing the Console: You can clear the console using console.clear() to
remove previous log messages.

console.clear();

Keep in mind that while console.log() is a valuable tool for development and
debugging, it's a good practice to remove or comment out debug statements
before deploying your code to production to avoid exposing sensitive
information or cluttering the console.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 14/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

alert
In JavaScript, the alert() function is used to display a pop-up dialog box with
a message and an "OK" button. It's a simple way to provide information or
notifications to the user. Here's how to use it:

alert("This is an alert message!");

When this code is executed, a pop-up dialog will appear in the browser with the
message "This is an alert message!" and an "OK" button. The user must click
"OK" to dismiss the alert.
The alert() function is often used for purposes such as:
1. Displaying important information or warnings to the user.

2. Notifying users of successful or unsuccessful operations.


3. Requesting user confirmation before proceeding with an action.
However, keep in mind that alert() can be disruptive to the user experience,
so it should be used sparingly and for essential notifications. Overusing it can be
annoying to users. In many cases, a less intrusive approach like using HTML
elements to display messages within the page's content or modal dialogs may
be more appropriate.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 15/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

prompt()
In JavaScript, the prompt() function is used to display a dialog box that
prompts the user to enter input, typically a text value. It's a way to interact with
users and gather information from them. Here's how to use it:

const userInput = prompt("Please enter your name:");

In this example:
1. The prompt() function displays a dialog box with the message "Please enter
your name:" and an input field for the user to enter text.

2. The user can type their response into the input field and then press "OK" or
"Cancel."
The prompt() function returns the text entered by the user as a string. If the
user clicks "OK" without entering anything, an empty string "" is returned. If
the user clicks "Cancel" or closes the dialog, null is returned.
You can store the user's input in a variable, as shown in the example with
userInput , and then use it in your JavaScript code.

Here's a more complete example that uses the prompt() function to get the
user's name and then displays a personalized greeting:

const userName = prompt("Please enter your name:"); if (userName !== n


ull && userName.trim() !== "") { alert(`Hello, ${userName}!`); } else
{ alert("You didn't enter a valid name."); }

In this example:

• The user's input is stored in the userName variable.

• We check if the user clicked "OK" (input is not null ) and if they entered a
non-empty name (using trim() to remove leading and trailing spaces). If
both conditions are met, we display a personalized greeting.

• If the user clicked "Cancel" or didn't enter a valid name, we display a


message indicating that they didn't enter a valid name.
Keep in mind that prompt() can be useful for simple input gathering, but for
more complex forms and user interactions, it's often better to use HTML forms
or custom modal dialogs for a better user experience.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 16/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Variables and Data Types

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 17/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Literals and Variables


In JavaScript, literals and variables are fundamental concepts that are used to
store and manipulate data. They serve as the building blocks for writing
JavaScript code.

Literals:
A literal is a direct representation of a fixed value in your code. It's a way to
express values without using variables. JavaScript supports various types of
literals, including:

1. String Literals:

• Enclosed in single ( ' ) or double ( " ) quotes.

• Example: 'Hello, World!' or "JavaScript"

2. Numeric Literals:

• Representing numeric values like integers or floating-point numbers.

• Examples: 42 , 3.14 , 123

3. Boolean Literals:

• Representing true or false .

• Examples: true , false

4. Array Literals:

• Enclosed in square brackets and contain a list of values, separated by


commas.

• Example: [1, 2, 3]
5. Object Literals:

• Enclosed in curly braces and define key-value pairs.

• Example: { name: "John", age: 30 }


6. Regular Expression Literals:

• Used to define patterns for pattern matching and manipulation.

• Example: /pattern/
7. Template Literals (introduced in ES6):

• Enclosed in backticks (\`) and allow for string interpolation and multiline
strings.

• Example: `My name is ${name} and I am ${age} years old.`

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 18/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Variables:
Variables in JavaScript are used to store and manage data that may change or
be referenced multiple times within your code. Variables provide a way to give a
name to a piece of data. To declare a variable, you can use the var , let , or
const keyword:

• var : Used for declaring variables globally or within a function scope. It has
some scoping quirks, so it's generally recommended to use let and const
instead.

• let : Used for declaring variables within block scopes (introduced in ES6). It
allows reassignment of values.

• const : Used for declaring variables within block scopes with values that
should not be reassigned after declaration (constants).
Here's how you declare and use variables:

let age = 25; // Declaring a variable 'age' and initializing it with t


he value 25. const name = "Alice"; // Declaring a constant 'name' and
initializing it with a string value. console.log(`My name is ${name} a
nd I am ${age} years old.`);

Variables are essential for storing and manipulating data in JavaScript, whereas
literals are used to directly represent specific values in your code. Together, they
form the foundation of working with data in JavaScript programs.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 19/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Variable Declaration and Initialization


In JavaScript, variable declaration and initialization are essential concepts for
storing and managing data. Here's how you declare and initialize variables in
JavaScript:
1. Variable Declaration:
To declare a variable, you use one of three keywords: var , let , or const . The
choice of keyword affects the variable's scope (where it can be accessed) and
whether its value can be changed (mutability).

• var : Variables declared with var have function-level scope, meaning they
are accessible throughout the function in which they are declared. Variables
declared with var can be reassigned.

var age; // Variable declaration (undefined)

• let : Introduced in ES6, let allows you to declare variables with block-
level scope. Block-level scope means the variable is accessible only within
the block (typically enclosed by curly braces {} ) where it's declared.
Variables declared with let can be reassigned.

let name; // Variable declaration (undefined)

• const : Also introduced in ES6, const is used to declare variables with


block-level scope. However, variables declared with const cannot be
reassigned after initialization, making them constants.

const PI = 3.14; // Variable declaration and initialization

2. Variable Initialization:
Variable initialization is the process of assigning an initial value to a declared
variable. You can declare and initialize a variable in one step using the =
operator:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 20/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

var age = 30; // Variable declaration and initialization let name = "A
lice"; // Variable declaration and initialization const PI = 3.14; //
Variable declaration and initialization

In the examples above, age , name , and PI are declared and initialized with
values 30 , "Alice" , and 3.14 , respectively.
3. Hoisting:

Variables declared with var are hoisted, which means they are moved to the
top of their function or block scope during the compilation phase. However,
their assignments are not hoisted, so the variables are initially assigned the value
undefined .

console.log(age); // undefined var age = 30;

Variables declared with let and const are also hoisted but have a temporal
dead zone (TDZ). This means you can't access them before the point of
declaration.

console.log(name); // ReferenceError: Cannot access 'name' before init


ialization let name = "Alice";

4. Best Practices:

• Use const for variables that should not be reassigned.

• Use let for variables that need to be reassigned.

• Avoid using var unless you have a specific reason to do so, as it has
function-level scope and can lead to unexpected behavior.
Understanding variable declaration and initialization is crucial for writing clean
and maintainable JavaScript code. Proper variable scoping and initialization help
prevent bugs and improve code readability.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 21/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Manipulating Variables
Manipulating variables in JavaScript involves performing various operations on
them to change their values, combine them, or update their contents. Here are
some common ways to manipulate variables in JavaScript:
1. Assignment:

• You can change the value of a variable by assigning a new value to it


using the assignment operator = .

let x = 5; x = x + 3; // Now 'x' is 8

2. Arithmetic Operations:

• JavaScript supports arithmetic operations like addition, subtraction,


multiplication, division, and modulus.

let a = 10; let b = 5; let sum = a + b; // Addition let difference


= a - b; // Subtraction let product = a * b; // Multiplication let
quotient = a / b; // Division let remainder = a % b; // Modulus (r
emainder)

3. String Concatenation:

• You can concatenate (join) strings together using the + operator.

let firstName = "John"; let lastName = "Doe"; let fullName = first


Name + " " + lastName; // "John Doe"

4. Increment and Decrement:

• You can increment and decrement numerical variables using the ++ and
- operators.

let count = 10; count++; // Increment by 1, count is now 11 count-


-; // Decrement by 1, count is now 10 again

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 22/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. Compound Assignment Operators:

• JavaScript provides shorthand operators for performing arithmetic and


assignment in one step.

let x = 5; x += 3; // Equivalent to x = x + 3; (x is now 8)

6. Comparison and Logical Operators:

• You can use comparison operators ( < , > , <= , >= , == , != ) and
logical operators ( && , || , ! ) to manipulate variables within
conditional statements.

let age = 25; let isAdult = age >= 18; // isAdult is true

7. String Methods:

• JavaScript provides built-in string methods for manipulating string


variables. For example, you can change the case of a string, split it into
an array, replace parts of it, and more.

let text = "Hello, World!"; let uppercaseText = text.toUpperCase


(); // "HELLO, WORLD!" let parts = text.split(", "); // ["Hello",
"World!"] let replacedText = text.replace("World", "JavaScript");
// "Hello, JavaScript!"

8. Array Methods:

• When working with arrays, you can use array methods like push , pop ,
splice , concat , and others to manipulate the contents of array
variables.

let numbers = [1, 2, 3]; numbers.push(4); // Add 4 to the end: [1,


2, 3, 4] numbers.pop(); // Remove the last element: [1, 2, 3]

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 23/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

These are some of the fundamental ways to manipulate variables in JavaScript.


The specific method you choose depends on the type of variable (numeric,
string, array, etc.) and the desired operation. JavaScript's versatility allows you to
perform a wide range of manipulations on variables to achieve your
programming goals.

Operators

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 24/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Arithmetic
Arithmetic operators in JavaScript are used to perform mathematical operations
on numeric values. These operators allow you to add, subtract, multiply, divide,
and more. Here are the primary arithmetic operators in JavaScript:

1. Addition + :

• The addition operator is used to add two or more numbers or


concatenate strings (if at least one operand is a string).

let a = 5; let b = 3; let sum = a + b; // sum is 8 let str1 = "Hel


lo, "; let str2 = "World!"; let greeting = str1 + str2; // greetin
g is "Hello, World!"

2. Subtraction :

• The subtraction operator is used to subtract the right operand from the
left operand.

let a = 10; let b = 5; let difference = a - b; // difference is 5

3. Multiplication :

• The multiplication operator is used to multiply two numbers.

let a = 6; let b = 7; let product = a * b; // product is 42

4. Division / :

• The division operator is used to divide the left operand by the right
operand. It returns a floating-point result.

let a = 15; let b = 3; let quotient = a / b; // quotient is 5

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 25/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. Modulus % :

• The modulus operator calculates the remainder when the left operand is
divided by the right operand.

let a = 10; let b = 3; let remainder = a % b; // remainder is 1

6. Exponentiation * (ES6):

• The exponentiation operator, introduced in ES6, raises the left operand


to the power of the right operand.

let base = 2; let exponent = 3; let result = base ** exponent; //


result is 8 (2^3)

7. Increment ++ and Decrement - :

• The increment operator ++ increases a variable's value by 1, while the


decrement operator - decreases it by 1.

let x = 5; x++; // Increment x by 1 (x is now 6) x--; // Decrement


x by 1 (x is now 5 again)

8. Unary Negation :

• The unary negation operator is used to change the sign of a numeric


value.

let number = 7; let negNumber = -number; // negNumber is -7

9. Unary Plus + :

• The unary plus operator + is used to explicitly convert a value to a


number, although it often has no effect on numbers.

let numStr = "42"; let num = +numStr; // num is 42 (converted to a


number)

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 26/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

These arithmetic operators allow you to perform a wide range of mathematical


operations and calculations in JavaScript. Remember to consider operator
precedence and use parentheses to control the order of operations when
necessary.

Relational
In JavaScript, relational and equality operators are used to compare values and
determine the relationships between them. These operators return Boolean
values ( true or false ) based on the comparison. Here are the primary
relational and equality operators in JavaScript:

Relational Operators:

1. Greater Than ( > ): Checks if the left operand is greater than the right
operand.

let a = 10; let b = 5; console.log(a > b); // true

2. Less Than ( < ): Checks if the left operand is less than the right operand.

let a = 10; let b = 15; console.log(a < b); // true

3. Greater Than or Equal To ( >= ): Checks if the left operand is greater than or
equal to the right operand.

let a = 10; let b = 10; console.log(a >= b); // true

4. Less Than or Equal To ( <= ): Checks if the left operand is less than or equal
to the right operand.

let a = 5; let b = 10; console.log(a <= b); // true

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 27/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Equality
Equality Operators:

1. Equality ( == ): Checks if two values are equal, performing type coercion if


necessary. It converts the values to a common type before comparison.

let a = 5; let b = "5"; console.log(a == b); // true (type coercio


n)

2. Inequality ( != ): Checks if two values are not equal. Like the equality
operator, it performs type coercion.

let a = 5; let b = "5"; console.log(a != b); // false (type coerci


on)

3. Strict Equality ( === ): Checks if two values are equal without type coercion.
It returns true only if both the values and their types are the same.

let a = 5; let b = "5"; console.log(a === b); // false (strict com


parison)

4. Strict Inequality ( !== ): Checks if two values are not equal without type
coercion. It returns true if either the values or their types are different.

let a = 5; let b = "5"; console.log(a !== b); // true (strict comp


arison)

These operators are fundamental for making decisions and performing


comparisons in JavaScript. When choosing between strict and non-strict
equality, it's generally a good practice to use strict equality ( === and !== ) to
avoid unexpected type coercion behavior.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 28/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Logical
Logical operators in JavaScript are used to perform logical operations on
Boolean values or expressions. These operators allow you to combine, negate, or
compare conditions to make decisions in your code. There are three primary
logical operators in JavaScript:
1. Logical AND ( && ):

• The logical AND operator returns true if both operands are true . If
either operand is false , it returns false .

let isAdult = true; let hasLicense = true; let canDrive = isAdult


&& hasLicense; // true

2. Logical OR ( || ):

• The logical OR operator returns true if at least one of the operands is


true . If both operands are false , it returns false .

let hasCreditCard = false; let hasPayPalAccount = true; let canPur


chase = hasCreditCard || hasPayPalAccount; // true

3. Logical NOT ( ! ):

• The logical NOT operator negates the Boolean value of its operand. If
the operand is true , it returns false , and if the operand is false , it
returns true .

let isStudent = true; let isNotStudent = !isStudent; // false

Examples of Combined Logical Operators:

Logical operators are often used in combination to create more complex


conditions:

• Combining AND and OR:

let isWeekend = true; let isSunny = false; let canGoToBeach = isWe


ekend && isSunny; // false (both conditions must be met)

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 29/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

• Negating Conditions:

let isLoggedIn = false; if (!isLoggedIn) { // Execute code if not


logged in }

• Using Parentheses for Priority:

let a = true; let b = false; let c = true; let result = (a && b) |


| c; // true (logical AND has higher priority)

Logical operators are crucial for controlling the flow of your program and
making decisions based on conditions. They are commonly used in conditional
statements, loops, and more complex logical expressions to control the flow of
your JavaScript code.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 30/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Assignment
In JavaScript, the assignment operator ( = ) is used to assign a value to a
variable. It is one of the fundamental operators in the language and plays a
central role in variable initialization and modification. Here's how the assignment
operator works:

let variableName = value;

• variableName : This is the name of the variable to which you want to assign
a value. You should have already declared this variable using let , const ,
or var before assigning a value to it.

• value : This is the value you want to assign to the variable. It can be a literal
value (e.g., a number, string, boolean), the result of an expression, or the
value of another variable.
Examples of using the assignment operator:

let age = 30; // Assign the value 30 to the variable 'age' let name =
"Alice"; // Assign the string "Alice" to the variable 'name' let isStu
dent = true; // Assign the boolean value 'true' to the variable 'isStu
dent' // Assign the result of an expression to a variable let total =
5 + 3; // Assign the result of 5 + 3 (which is 8) to the variable 'tot
al' // Assign the value of one variable to another variable let x = 1
0; let y = x; // Assign the value of 'x' (which is 10) to the variable
'y'

Keep in mind the following points when using the assignment operator:

1. The variable on the left side of the assignment operator ( variableName )


must be declared using let , const , or var before you can assign a value
to it.

2. The value on the right side of the assignment operator ( value ) can be a
literal value, a variable, or the result of an expression.

3. When you use the assignment operator, the variable's previous value, if any,
is overwritten with the new value.

4. The assignment operator does not return a value; it is an expression that


simply assigns a value to a variable.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 31/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

The assignment operator is a fundamental concept in JavaScript and is used


extensively to work with data and variables within your code.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 32/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Precedence and Associativity


In JavaScript, operators have precedence and associativity rules that determine
the order in which they are evaluated when multiple operators are used in a
single expression. Understanding these rules is crucial for writing code that
produces the expected results.

Precedence refers to the order in which operators are evaluated. Operators with
higher precedence are evaluated before operators with lower precedence. When
operators have the same precedence, the order of evaluation is determined by
their associativity.

Here are some key points regarding precedence and associativity in JavaScript:

1. Operator Precedence:

• JavaScript has a hierarchy of operator precedence, which determines


how different operators are evaluated in expressions.

• For example, the multiplication operator ( ) has higher precedence than


the addition operator ( + ). Therefore, expressions with both and +
operators will first evaluate the operation.

2. Parentheses for Explicit Precedence:

• You can use parentheses () to explicitly specify the order of evaluation,


overriding the default precedence rules.

• Expressions within parentheses are always evaluated first.

let result = 2 + 3 * 4; // Multiplication has higher precedence, s


o result is 14. let resultWithParens = (2 + 3) * 4; // Parentheses
change the order, so resultWithParens is 20.

3. Associativity:

• If operators have the same precedence, their associativity determines


the order of evaluation.

• Most binary operators in JavaScript are left-associative, meaning they


are evaluated from left to right.

let result = 5 - 3 - 1; // Left-associative: (5 - 3) - 1, result i


s 1.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 33/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

4. Assignment Operator (=) Has Right Associativity:

• The assignment operator = has right-associative behavior, meaning it


evaluates from right to left when used in succession.

let a, b; a = b = 5; // The rightmost assignment is evaluated firs


t, assigning 5 to both 'a' and 'b'.

5. Operator Precedence Table:

• JavaScript has a well-defined operator precedence table that you can


refer to when in doubt.

• You can find the table in the MDN documentation.

Here's a simplified example of operator precedence and associativity:

let result = 2 + 3 * 4; // Multiplication (*) has higher precedence th


an addition (+). // Steps: 3 * 4 = 12, then 2 + 12 = 14, so 'result' i
s 14.

It's important to be aware of these rules to avoid unexpected behavior in your


JavaScript code, especially when working with complex expressions or mixing
different types of operators.

Data Types

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 34/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Strings
In JavaScript, operators have precedence and associativity rules that determine
the order in which they are evaluated when multiple operators are used in a
single expression. Understanding these rules is crucial for writing code that
produces the expected results.

Precedence refers to the order in which operators are evaluated. Operators with
higher precedence are evaluated before operators with lower precedence. When
operators have the same precedence, the order of evaluation is determined by
their associativity.
Here are some key points regarding precedence and associativity in JavaScript:

1. Operator Precedence:

• JavaScript has a hierarchy of operator precedence, which determines


how different operators are evaluated in expressions.

• For example, the multiplication operator ( ) has higher precedence than


the addition operator ( + ). Therefore, expressions with both and +
operators will first evaluate the operation.
2. Parentheses for Explicit Precedence:

• You can use parentheses () to explicitly specify the order of evaluation,


overriding the default precedence rules.

• Expressions within parentheses are always evaluated first.

let result = 2 + 3 * 4; // Multiplication has higher precedence, s


o result is 14. let resultWithParens = (2 + 3) * 4; // Parentheses
change the order, so resultWithParens is 20.

3. Associativity:

• If operators have the same precedence, their associativity determines


the order of evaluation.

• Most binary operators in JavaScript are left-associative, meaning they


are evaluated from left to right.

let result = 5 - 3 - 1; // Left-associative: (5 - 3) - 1, result i


s 1.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 35/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

4. Assignment Operator (=) Has Right Associativity:

• The assignment operator = has right-associative behavior, meaning it


evaluates from right to left when used in succession.

let a, b; a = b = 5; // The rightmost assignment is evaluated firs


t, assigning 5 to both 'a' and 'b'.

5. Operator Precedence Table:

• JavaScript has a well-defined operator precedence table that you can


refer to when in doubt.

• You can find the table in the MDN documentation.


Here's a simplified example of operator precedence and associativity:

let result = 2 + 3 * 4; // Multiplication (*) has higher precedence th


an addition (+). // Steps: 3 * 4 = 12, then 2 + 12 = 14, so 'result' i
s 14.

It's important to be aware of these rules to avoid unexpected behavior in your


JavaScript code, especially when working with complex expressions or mixing
different types of operators.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 36/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

String functions
JavaScript provides a wide range of built-in string functions (also known as
string methods) that allow you to manipulate and work with strings effectively.
Here are some of the most commonly used string functions in JavaScript:

1. length :

• Returns the length (the number of characters) of a string.

let text = "Hello, World!"; let length = text.length; // 13

2. toUpperCase() :

• Converts all characters in a string to uppercase.

let text = "hello"; let uppercaseText = text.toUpperCase(); // "HE


LLO"

3. toLowerCase() :

• Converts all characters in a string to lowercase.

let text = "WORLD"; let lowercaseText = text.toLowerCase(); // "wo


rld"

4. charAt(index) :

• Returns the character at the specified index in the string. The index is
zero-based.

let text = "JavaScript"; let character = text.charAt(4); // "S"

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 37/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. substring(start, end) :

• Returns a substring of the original string, starting from the start index
(inclusive) and ending at the end index (exclusive).

let text = "Hello, World!"; let substring = text.substring(7, 12);


// "World"

6. slice(start, end) :

• Similar to substring , it returns a substring, but allows negative indices


(counting from the end of the string).

let text = "Hello, World!"; let slice = text.slice(-6, -1); // "Wo


rld"

7. indexOf(substring) :

• Returns the index of the first occurrence of substring in the string.


Returns 1 if not found.

let text = "Hello, World!"; let index = text.indexOf("World"); //


7

8. lastIndexOf(substring) :

• Returns the index of the last occurrence of substring in the string.


Returns 1 if not found.

let text = "Hello, World!"; let lastIndex = text.lastIndexOf("o");


// 8

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 38/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

9. replace(oldSubstring, newSubstring) :

• Replaces the first occurrence of oldSubstring with newSubstring in the


string.

let text = "Hello, World!"; let newText = text.replace("World", "U


niverse"); // "Hello, Universe!"

10. split(separator) :

• Splits the string into an array of substrings based on the specified


separator . Useful for breaking text into parts.

let text = "apple,banana,cherry"; let fruits = text.split(","); //


["apple", "banana", "cherry"]

11. trim() :

• Removes leading and trailing whitespace characters (spaces, tabs,


newlines) from a string.

let text = " Hello, World! "; let trimmedText = text.trim(); // "H
ello, World!"

12. concat(string1, string2, ...) :

• Combines multiple strings into one string.

let firstName = "John"; let lastName = "Doe"; let fullName = first


Name.concat(" ", lastName); // "John Doe"

• You can concatenate strings using the + operator or template literals


(introduced in ES6).

let firstName = "John"; let lastName = "Doe"; let fullName = first


Name + " " + lastName; // "John Doe" let message = `Hello, ${first
Name}!`; // "Hello, John!"

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 39/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

These are some of the most commonly used string functions in JavaScript. String
methods make it easier to manipulate and work with text data in your JavaScript
applications.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 40/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Type Coercion
Type coercion in JavaScript refers to the automatic or implicit conversion of
values from one data type to another during runtime. JavaScript is known for its
loose typing system, which means that it will attempt to perform operations or
comparisons even when the data types of the operands are not strictly
compatible. Type coercion plays a significant role in how JavaScript handles
various operations and comparisons.

Here are some common scenarios where type coercion occurs in JavaScript:
1. String Concatenation:
JavaScript will automatically convert non-string values to strings when using
the + operator for concatenation.

let num = 5; let str = "Hello, " + num; // "Hello, 5" (num is coer
ced to a string)

2. Arithmetic Operations:
When performing arithmetic operations, JavaScript may convert operands to
numbers if needed.

let num1 = "5"; let num2 = 10; let sum = num1 + num2; // "510" (bo
th are coerced to strings) let total = num1 - num2; // -5 (both ar
e coerced to numbers)

3. Comparison Operators:
JavaScript will coerce values to the same type before comparing them using
equality ( == ) and inequality ( != ) operators. This can lead to unexpected
results.

let num = 5; let str = "5"; console.log(num == str); // true (str


is coerced to a number)

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 41/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

4. Truthy and Falsy Values:


JavaScript has truthy and falsy values. Values like 0 , "" (empty string),
null , undefined , NaN , and false are falsy. All other values are truthy.

if (0) { // This code won't execute because 0 is falsy. }

5. Logical Operators:
JavaScript performs type coercion when evaluating logical expressions using
&& and || operators.

let result = "Hello" && true; // true (both operands are truthy)

6. Function Arguments:
Function parameters can receive values of different types, and JavaScript will
attempt to coerce them if necessary.

function greet(name) { console.log("Hello, " + name); } greet("Ali


ce"); // "Hello, Alice" greet(42); // "Hello, 42" (42 is coerced t
o a string)

While type coercion can be convenient, it can also lead to subtle bugs and
unexpected behavior in your code. To mitigate these issues, it's often
recommended to use strict equality ( === and !== ) when comparing values,
explicitly convert data types when needed, and be aware of how JavaScript
handles type coercion in different situations.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 42/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Conversion Between String and Number Type


In JavaScript, you can convert between string and number types using various
methods. These conversions are essential when you need to manipulate or
perform operations involving both string and numeric data. Here are some
common techniques for converting between strings and numbers:

Converting Strings to Numbers:

1. Using parseInt() and parseFloat() :

• You can use the parseInt() function to convert a string to an integer,


and parseFloat() to convert a string to a floating-point number.

let strInt = "42"; let strFloat = "3.14"; let numInt = parseInt(st


rInt); // 42 let numFloat = parseFloat(strFloat); // 3.14

2. Using the Number() Constructor:

• The Number() constructor can be used to convert a string to a number.

let strNum = "123"; let num = Number(strNum); // 123

3. Using the Unary + Operator:

• You can use the unary + operator to convert a string to a number.

let strNum = "456"; let num = +strNum; // 456

Converting Numbers to Strings:

1. Using String() Constructor or .toString() Method:

• You can use the String() constructor or the .toString() method to


convert a number to a string.

let num = 42; let str1 = String(num); // "42" let str2 = num.toStr
ing(); // "42"

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 43/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

2. Using String Concatenation:

• You can concatenate a number with an empty string to implicitly convert


it to a string.

let num = 123; let str = num + ""; // "123"

3. Using Template Literals (ES6 and later):

• Template literals can implicitly convert a variable to a string within a


template literal string.

let num = 789; let str = `${num}`; // "789"

4. Using .toLocaleString() Method:

• The .toLocaleString() method converts a number to a string with


localized formatting.

let num = 1000; let str = num.toLocaleString(); // "1,000" (format


ted as per locale)

Keep in mind that when converting a string to a number, JavaScript will attempt
to parse the string, but if the string cannot be parsed into a valid number (e.g.,
"abc" ), it will result in NaN (Not-a-Number). Therefore, it's a good practice to
check for NaN when converting strings to numbers to handle such cases
gracefully.

let str = "abc"; let num = parseInt(str); if (!isNaN(num)) { console.l


og(num); } else { console.log("Conversion failed."); }

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 44/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Boolean
In JavaScript, the Boolean data type represents a binary value, meaning it can
have one of two values: true or false . Booleans are used to represent logical
values and are fundamental in programming for making decisions and
controlling the flow of code execution. Here are some key points about
Booleans in JavaScript:

1. Boolean Values:

• There are only two possible Boolean values: true and false . These
values are case-sensitive, so True and False are not valid Boolean
values.

let isTrue = true; let isFalse = false;

2. Boolean Expressions:

• Boolean expressions are conditions that evaluate to either true or


false . These expressions are used in control structures like if
statements and loops to make decisions in your code.

if (isTrue) { // This block will execute because isTrue is true. }


if (!isFalse) { // This block will execute because !isFalse is tru
e (logical NOT). }

3. Logical Operators:

• JavaScript provides logical operators like && (logical AND), || (logical


OR), and ! (logical NOT) to work with Boolean values.

let x = true; let y = false; let result1 = x && y; // false (logic


al AND) let result2 = x || y; // true (logical OR) let result3 = !
x; // false (logical NOT)

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 45/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

4. Truthy and Falsy Values:

• JavaScript has truthy and falsy values. Values like 0 , "" (empty string),
null , undefined , NaN , and false are falsy. All other values are truthy.

if (0) { // This block won't execute because 0 is falsy. } if ("He


llo") { // This block will execute because "Hello" is truthy. }

5. Boolean Conversion:

• You can convert other data types to Booleans using the Boolean()
constructor or the double negation !! operator.

let value = 42; let boolValue1 = Boolean(value); // true (any non-


zero number is truthy) let boolValue2 = !!value; // true

6. Comparisons:

• Many JavaScript operations, like comparisons, return Boolean values. For


example, 5 > 3 evaluates to true , and 10 === "10" evaluates to
false .

Booleans are fundamental for creating conditional logic, controlling program


flow, and making decisions in JavaScript code. Understanding how to work with
Booleans is essential for programming in JavaScript.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 46/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Null
In JavaScript, null is a special value that represents the intentional absence of
any object or value. It is a primitive data type, and it's often used to signify that a
variable should not have any meaningful value. Here are some key points about
null in JavaScript:

1. Null as a Value:

• null is a JavaScript keyword that represents the intentional absence of


a value.

• It is often used to initialize a variable when you don't want it to have any
initial value.

let emptyValue = null;

2. typeof null :

• The typeof operator applied to a null value returns "object" . This is


a historical quirk in JavaScript and can be considered a language design
flaw.

typeof null; // "object"

3. Comparison with undefined :

• While null and undefined both represent the absence of value, they
are not the same. undefined typically indicates a variable that has been
declared but hasn't been assigned any value, while null is often used
to represent a deliberate absence of value.

let undefinedValue; // This variable is undefined. let nullValue =


null; // This variable is deliberately set to null.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 47/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

4. Checking for null :

• You can use strict equality ( === ) to check if a variable is null .

let value = null; if (value === null) { // This block will execute
because 'value' is null. }

5. Common Use Cases:

• null is often used to reset or clear the value of a variable, especially


when dealing with objects.

let obj = { name: "Alice" }; // Clearing the object's value obj =


null; // Now 'obj' is null, and the original object is no longer a
ccessible.

6. Avoiding Errors:

• When working with potentially null values, it's a good practice to


check if a value is null before accessing its properties or methods to
avoid runtime errors.

let user = getUserFromDatabase(); if (user !== null) { // It's saf


e to access 'user' properties here. console.log(user.name); }

null is a valuable tool in JavaScript for indicating the absence of a value or


deliberately clearing the value of a variable. Understanding its use cases and
distinctions from undefined can help you write more reliable code.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 48/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Undefined
In JavaScript, undefined is a primitive value that represents the absence of a
value or the lack of a defined value. It is often used to indicate that a variable
has been declared but has not been assigned a value or that a property does
not exist in an object. Here are some key points about undefined in JavaScript:

1. Declaration Without Initialization:

• When you declare a variable without assigning an initial value to it, that
variable's value is undefined .

let myVariable; console.log(myVariable); // undefined

2. Function Parameters:

• If a function expects arguments but is called without providing values


for those arguments, the corresponding parameters inside the function
will have the value undefined .

function greet(name) { console.log(name); } greet(); // undefined


(name parameter is not provided)

3. Accessing Nonexistent Object Properties:

• When you attempt to access a property that does not exist in an object,
the result is undefined .

let person = {}; console.log(person.age); // undefined (age proper


ty does not exist)

4. Explicit Assignment:

• You can explicitly assign the value undefined to a variable or property.

let emptyValue = undefined; let person = { name: "Alice" }; perso


n.age = undefined;

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 49/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. typeof undefined :

• The typeof operator, when applied to undefined , returns the string


"undefined" . This can be used to check the type of a variable or value.

typeof undefined; // "undefined"

6. Comparison with null :

• While undefined and null both represent the absence of a value, they
are not the same. undefined typically indicates an uninitialized variable
or missing property, while null is often used to signify a deliberate
absence of value.

let x; let y = null; console.log(x); // undefined console.log(y);


// null

7. Avoiding Errors:

• When working with potentially undefined values, it's a good practice to


check if a value is undefined before attempting to access its properties
or methods to prevent runtime errors.

let data = fetchData(); if (data !== undefined) { // It's safe to


access 'data' properties here. console.log(data.value); }

Understanding undefined is essential for writing reliable JavaScript code,


especially when dealing with variables and properties that may or may not have
been initialized or assigned a value.

Conditionals

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 50/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Truthy and Falsy


In JavaScript, values are evaluated as either "truthy" or "falsy" when used in a
Boolean context, such as in conditional statements (e.g., if , while ) or logical
expressions (e.g., && , || ). Understanding truthy and falsy values is important
because it helps you write more expressive and efficient code. Here's a detailed
explanation of truthy and falsy values in JavaScript:
Truthy Values:
In JavaScript, values that are considered "truthy" evaluate to true when used in
a Boolean context. Here are the main categories of truthy values:
1. Non-Empty Strings:
Any non-empty string is considered truthy.

if ("Hello") { // This block will execute because "Hello" is truth


y. }

2. Numbers (Except 0):


Numeric values (both positive and negative) other than 0 are considered
truthy.

if (42) { // This block will execute because 42 is truthy. }

3. Non-Empty Arrays and Objects:


Non-empty arrays and objects are considered truthy.

if ([1, 2, 3]) { // This block will execute because the array is t


ruthy. } if ({ name: "Alice" }) { // This block will execute becau
se the object is truthy. }

4. The Boolean Value true :


The Boolean value true is always truthy.

if (true) { // This block will execute because 'true' is truthy. }

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 51/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. Functions:
Functions are considered truthy values, even if they don't return a specific
value.

function myFunction() { // Function body } if (myFunction) { // Th


is block will execute because 'myFunction' is truthy. }

Falsy Values:
In contrast, values that are considered "falsy" evaluate to false when used in a
Boolean context. Here are the main categories of falsy values:
1. The Boolean Value false :
The Boolean value false is always falsy.

if (false) { // This block won't execute because 'false' is falsy.


}

2. The Number 0:
The number 0 is considered falsy.

if (0) { // This block won't execute because '0' is falsy. }

3. The Empty String "" :


An empty string "" is considered falsy.

if ("") { // This block won't execute because '""' is falsy. }

4. The Special Value null : null represents the absence of any value or object
and is considered falsy.

let myVar = null; if (myVar) { // This block won't execute because


'myVar' is falsy. }

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 52/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. The Special Value undefined : undefined represents a declared variable with


no assigned value and is considered falsy.

let myVar; if (myVar) { // This block won't execute because 'myVa


r' is falsy. }

6. The Special Value NaN : NaN represents "Not-a-Number" and is considered


falsy.

let result = 10 / "apple"; // NaN if (result) { // This block wo


n't execute because 'result' is falsy. }

Understanding truthy and falsy values helps you write concise and expressive
code by leveraging the inherent Boolean nature of JavaScript values in
conditional logic and control flow.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 53/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

if, if...else and and if-else-if


Conditional statements, such as if , if...else , and if-else-if , are crucial in
JavaScript for controlling the flow of your code based on specified conditions.
They allow you to make decisions and execute different code blocks depending
on whether a condition evaluates to true or false . Let's explore these
conditional statements in detail:
1. if Statement:

The if statement is used to execute a block of code if a specified condition


evaluates to true . If the condition is false , the code block is skipped, and the
program continues with the next statement.
Syntax:

if (condition) { // Code to execute if the condition is true }

Example:

let age = 25; if (age >= 18) { console.log("You are an adult."); }

In this example, if the age variable is greater than or equal to 18, the message
"You are an adult" will be logged to the console.
2. if...else Statement:

The if...else statement extends the if statement by providing an alternative


block of code to execute when the condition is false . If the condition in the
if statement is true , the code block under if is executed; otherwise, the
code block under else is executed.

Syntax:

if (condition) { // Code to execute if the condition is true } else {


// Code to execute if the condition is false }

Example:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 54/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

let hour = 14; if (hour < 12) { console.log("Good morning!"); } else {


console.log("Good afternoon!"); }

Depending on the value of the hour variable, either "Good morning!" or "Good
afternoon!" will be logged to the console.

3. if...else if...else Statement:


The if...else if...else statement allows you to test multiple conditions
sequentially until one of them evaluates to true . The code block associated
with the first true condition is executed, and the rest of the conditions are
skipped.
Syntax:

if (condition1) { // Code to execute if condition1 is true } else if


(condition2) { // Code to execute if condition2 is true } else { // Co
de to execute if none of the conditions are true }

Example:

let score = 85; if (score >= 90) { console.log("A"); } else if (score


>= 80) { console.log("B"); } else if (score >= 70) { console.log("C");
} else { console.log("D"); }

In this example, the program will determine the grade based on the score
variable and log "A," "B," "C," or "D" accordingly. It tests multiple conditions one
by one until it finds a match.
These conditional statements are fundamental for making decisions and
controlling the flow of your JavaScript code. They are widely used in various web
development scenarios, such as form validation, user authentication, and
rendering dynamic content based on different conditions.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 55/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Ternary Operator
The ternary operator, also known as the conditional operator, is a compact way
to write conditional expressions in JavaScript. It provides a concise alternative to
the traditional if...else statement for evaluating conditions and returning
values based on whether the condition is true or false. The ternary operator has
the following syntax:

condition ? expression_if_true : expression_if_false;

Here's a detailed explanation of the ternary operator in JavaScript:

• Condition: The condition is an expression that is evaluated for its


truthiness or falsiness. If it evaluates to true , the expression_if_true is
executed; otherwise, the expression_if_false is executed.

• Expression If True: This is the value or expression returned if the condition is


true. It's the result of the expression when the condition evaluates to true.

• Expression If False: This is the value or expression returned if the condition


is false. It's the result of the expression when the condition evaluates to
false.
Example 1: Basic Usage

let age = 20; let message = age >= 18 ? "You are an adult" : "You are
not an adult"; console.log(message);

In this example, if age is greater than or equal to 18, the message variable is
assigned the value "You are an adult." Otherwise, it's assigned the value "You are
not an adult."

Example 2: Using Expressions


You can use more complex expressions on both sides of the ternary operator:

let score = 75; let grade = score >= 90 ? "A" : score >= 80 ? "B" : sc
ore >= 70 ? "C" : "D"; console.log(grade);

In this example, the grade variable is assigned a value based on the score . The
ternary operator is nested to handle multiple conditions.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 56/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Example 3: Returning Values


The ternary operator can be used to return values from functions conditionally:

function getDiscount(isMember) { return isMember ? 10 : 0; } let userI


sMember = true; let discount = getDiscount(userIsMember); console.log
(discount); // Output: 10

Here, the getDiscount function returns a discount amount based on whether


the user is a member.
Advantages of the Ternary Operator:

1. Conciseness: The ternary operator can make your code more concise and
readable, especially for simple conditional assignments.
2. Avoiding Repetition: It can help avoid repeating the same variable
assignment with slight variations.

Considerations:
While the ternary operator is useful for simplifying straightforward conditional
assignments, it may become less readable for complex conditions or when
multiple expressions are involved. In such cases, using if...else statements
can enhance code clarity.

let result; if (condition1) { result = expression1; } else if (conditi


on2) { result = expression2; } else { result = expression3; }

In summary, the ternary operator is a powerful tool for handling simple


conditional expressions and can make your code more compact. However, for
more complex conditions, it's important to prioritize code readability and
choose the appropriate approach based on the specific context.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 57/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Nested if...else
Nested if...else statements are a way to handle multiple conditional
scenarios within one another. They allow you to evaluate one condition, and
based on the outcome, you can further evaluate additional conditions. This is
useful when you have complex decision-making processes with multiple
branches. Here's the syntax for nested if...else statements:

if (condition1) { // Code to execute if condition1 is true if (conditi


on2) { // Code to execute if both condition1 and condition2 are true }
else { // Code to execute if condition1 is true but condition2 is fals
e } } else { // Code to execute if condition1 is false }

Here's an example to illustrate nested if...else statements:

let temperature = 25; let isRaining = false; if (temperature > 30) { i


f (isRaining) { console.log("It's hot, but don't forget your umbrell
a!"); } else { console.log("It's hot, enjoy the weather!"); } } else {
if (isRaining) { console.log("It's not too hot, but don't forget your
umbrella!"); } else { console.log("It's a pleasant day!"); } }

In this example:

• The outer if statement checks the temperature. If it's greater than 30


degrees, it evaluates whether it's raining with the inner if statement.

• If the temperature is less than or equal to 30, the outer else statement is
executed, which again evaluates whether it's raining with the inner if
statement.
Nested if...else statements can be as deeply nested as needed to
accommodate complex conditional logic. However, it's important to maintain
code readability and avoid excessive nesting by potentially using alternative
control structures like switch statements or refactoring your code for better
organization.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 58/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

switch...case
The switch...case statement is a control structure in JavaScript that allows you
to evaluate an expression and execute different code blocks depending on the
value of that expression. It provides a way to streamline conditional logic when
you have multiple conditions to check against a single variable or expression.
Here's the basic syntax of a switch...case statement:

switch (expression) { case value1: // Code to execute if expression ma


tches value1 break; case value2: // Code to execute if expression matc
hes value2 break; // Additional cases can be added as needed default:
// Code to execute if expression doesn't match any case }

Here's a detailed explanation of the switch...case statement in JavaScript:

• switch : The switch keyword starts the switch statement and is followed
by a pair of parentheses.

• expression : This is the value or expression that you want to evaluate. It is


typically a variable, but it can be any expression that produces a value. The
expression's value is compared against the case values.

• case : Each case label specifies a value or expression to compare against


the switch expression. If the switch expression matches a case value, the
code block associated with that case label is executed. If there's no match,
execution moves to the default case (if present) or continues with the next
statement outside the switch .

• break : The break statement is used to exit the switch statement after a
case block is executed. Without break , execution would continue to the
next case (this is called "fall-through").

• default (optional): The default case is executed when none of the case
values match the switch expression. It serves as a catch-all block.
Here's an example of a switch...case statement:

let day = "Monday"; switch (day) { case "Monday": console.log("It's th


e start of the workweek."); break; case "Friday": console.log("It's al
most the weekend."); break; default: console.log("It's another day.");
}

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 59/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

In this example, the value of the day variable is compared against the case
values. Since day is "Monday," the code block under the "Monday" case is
executed, and the output is "It's the start of the workweek."
It's important to note that break statements are crucial within switch...case
statements to prevent fall-through behavior, where multiple cases might be
executed if break is omitted.

The switch...case statement is a valuable tool for handling multiple conditions


efficiently and improving code readability, especially when you have a single
expression to compare against several possible values.

Loops

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 60/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

while loop
In JavaScript, the while loop is a control structure that allows you to repeatedly
execute a block of code as long as a specified condition remains true. It's a
common choice when you want to perform a task iteratively until a certain
condition is met or becomes false. Here's the basic syntax of a while loop:

while (condition) { // Code to execute as long as the condition is tru


e }

Here's a more detailed explanation of how the while loop works:

• The condition is a Boolean expression that is evaluated before each


iteration of the loop.

• If the condition is true, the code block inside the while loop is executed.

• After the code block execution, the condition is checked again.

• If the condition is still true, the loop continues to execute.

• This process repeats until the condition becomes false, at which point the
loop terminates, and the program continues with the code following the
while loop.

Here's an example of a simple while loop:

let count = 0; while (count < 5) { console.log("Count: " + count); cou


nt++; }

In this example:

• count is initially set to 0 .

• The while loop checks if count is less than 5 .

• As long as the condition is true, it executes the code block.

• Inside the loop, it logs the current value of count and then increments it by
1 .

• The loop continues until count reaches 5 , at which point the condition
becomes false, and the loop exits.
This would produce the following output:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 61/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Count: 0 Count: 1 Count: 2 Count: 3 Count: 4

It's important to ensure that the condition in a while loop eventually becomes
false; otherwise, you can create an infinite loop, which will cause your program
to run indefinitely.
Here's an example of an infinite loop:

while (true) { console.log("This is an infinite loop!"); }

To avoid infinite loops, make sure your condition is designed to change over
time or due to user interaction. You can also use the break statement to exit a
loop when a specific condition is met within the loop's code block.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 62/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

do while loop
The do...while loop is a control structure in JavaScript that allows you to
repeatedly execute a block of code as long as a specified condition remains true.
It's similar to the while loop, but with one key difference: in a do...while
loop, the code block is executed at least once before the condition is checked.
Here's the basic syntax of a do...while loop:

do { // Code to execute at least once } while (condition);

Here's a detailed explanation of how the do...while loop works:

• The code block inside the do section is executed first.

• After the code block execution, the condition is checked.

• If the condition is true, the loop continues to execute.

• If the condition is false, the loop terminates, and the program continues with
the code following the do...while loop.

Here's an example of a simple do...while loop:

let count = 0; do { console.log("Count: " + count); count++; } while


(count < 5);

In this example:

• count is initially set to 0 .

• The code block inside the do section is executed first, which logs the
current value of count and then increments it by 1 .

• After the code block executes, the condition count < 5 is checked.

• As long as the condition is true, the loop continues to execute.

• The loop terminates when count reaches 5 , and the condition becomes
false.
This would produce the following output, with the code block running at least
once:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 63/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Count: 0 Count: 1 Count: 2 Count: 3 Count: 4

The do...while loop is useful when you want to ensure that a code block runs
at least once, even if the condition initially evaluates to false. Just like with
while loops, it's crucial to make sure that the condition in a do...while loop
eventually becomes false to avoid infinite loops.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 64/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

for loop
A for loop is a control structure in JavaScript that allows you to repeatedly
execute a block of code for a specific number of iterations. It's one of the most
commonly used loops in JavaScript and is particularly useful when you know in
advance how many times you want to repeat a task. The for loop has the
following syntax:

for (initialization; condition; increment/decrement) { // Code to exec


ute in each iteration }

Here's a detailed explanation of the components and how a for loop works:

• Initialization: This part is executed once before the loop begins. It's where
you typically initialize a counter variable or set up initial values.

• Condition: The condition is evaluated before each iteration. If it evaluates to


true , the loop continues; if it evaluates to false , the loop terminates.

• Increment/Decrement: After each iteration, this part is executed. It's where


you typically update the counter variable to control the loop's progression.

• Code Block: The code block inside the for loop is executed in each
iteration. It's where you place the code that you want to repeat.

Here's an example of a simple for loop:

for (let i = 0; i < 5; i++) { console.log("Iteration " + i); }

In this example:

• let i = 0 initializes a counter variable i to 0 .

• i < 5 is the condition that checks whether i is less than 5 .

• i++ increments the value of i by 1 after each iteration.

• The code block inside the loop logs the current value of i .
The output of this loop will be:

Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 65/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Common Use Cases:

• Iterating Over Arrays: You can use a for loop to iterate over the elements
of an array.

const fruits = ["apple", "banana", "cherry"]; for (let i = 0; i <


fruits.length; i++) { console.log(fruits[i]); }

• Counting Down: You can also use a for loop to count down from a higher
number to a lower number.

for (let i = 5; i > 0; i--) { console.log(i); }

• Nested Loops: for loops can be nested inside each other to create more
complex iteration patterns.

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


e.log(i, j); } }

The for loop is a versatile tool for performing repetitive tasks in JavaScript.
However, it's important to ensure that the initialization, condition, and
increment/decrement parts are set up correctly to avoid infinite loops or other
unintended behavior.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 66/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

break and continue


In JavaScript, the break and continue statements are used within loops (such
as for , while , and do...while ) to control the flow of the loop and change
how the loop behaves under certain conditions.
1. break Statement:

The break statement is used to exit a loop prematurely, even if the loop's
condition is still true. When break is encountered, the loop immediately
terminates, and program control moves to the next statement outside the loop.

Here's an example of using break in a for loop to exit the loop when a
specific condition is met:

for (let i = 0; i < 5; i++) { if (i === 3) { break; } console.log(i);


}

In this example, the loop will terminate when i becomes 3 , and the output
will be:

0 1 2

2. continue Statement:

The continue statement is used to skip the current iteration of a loop and
continue with the next iteration. When continue is encountered, the remaining
code in the current iteration is skipped, and the loop proceeds to the next
iteration.

Here's an example of using continue in a for loop to skip the iteration when a
specific condition is met:

for (let i = 0; i < 5; i++) { if (i === 2) { continue; } console.log


(i); }

In this example, the loop will skip the iteration when i is 2 , and the output will
be:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 67/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

0 1 3 4

Use Cases:

• break is often used when you want to exit a loop prematurely based on a
certain condition, such as finding a specific value in an array or reaching a
particular state.

• continue is used when you want to skip a specific iteration but continue
with the rest of the loop, typically when processing elements in an array or
performing actions on specific items.

Both break and continue can be used within nested loops, allowing you to
control the flow of both the inner and outer loops. However, it's important to
use them judiciously to ensure that your code behaves as expected and to avoid
unexpected behavior or infinite loops.

Arrays

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 68/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Understanding Arrays
Arrays in JavaScript are ordered, list-like collections of values that can hold
multiple items, including numbers, strings, objects, functions, and even other
arrays. Arrays are a fundamental data structure used to store and manipulate
collections of data in JavaScript. Here are some key characteristics and concepts
to understand about arrays in JavaScript:
1. Declaring Arrays:
You can create an array in JavaScript using square brackets [] . You can
declare an empty array or initialize it with values.

// Empty array let emptyArray = []; // Array with values let numbe
rs = [1, 2, 3, 4, 5]; let fruits = ["apple", "banana", "cherry"];

2. Accessing Elements:
Array elements are accessed using zero-based indices. You can use square
brackets with the index to retrieve or modify elements.

let fruits = ["apple", "banana", "cherry"]; console.log(fruits


[0]); // Output: "apple" fruits[1] = "orange"; // Modifies the sec
ond element to "orange"

3. Array Length:
You can find the number of elements in an array using the length property.

let numbers = [1, 2, 3, 4, 5]; console.log(numbers.length); // Out


put: 5

4. Adding and Removing Elements:


Arrays have methods like push , pop , shift , and unshift to add and
remove elements.

let fruits = ["apple", "banana"]; fruits.push("cherry"); // Adds


"cherry" to the end fruits.pop(); // Removes the last element ("ch
erry") fruits.unshift("orange"); // Adds "orange" to the beginning
fruits.shift(); // Removes the first element ("orange")

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 69/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

5. Iterating Through Arrays:


You can use loops like for and for...of to iterate through the elements
of an array.

let numbers = [1, 2, 3, 4, 5]; for (let i = 0; i < numbers.length;


i++) { console.log(numbers[i]); } for (let number of numbers) { co
nsole.log(number); }

6. Common Array Methods:


JavaScript provides various built-in array methods for performing operations
like filtering, mapping, and reducing arrays. Some common array methods
include map , filter , reduce , forEach , and find .

let numbers = [1, 2, 3, 4, 5]; let doubled = numbers.map((num) =>


num * 2); // [2, 4, 6, 8, 10] let evenNumbers = numbers.filter((nu
m) => num % 2 === 0); // [2, 4]

7. Arrays of Different Types:


JavaScript allows you to create arrays that contain elements of different data
types.

let mixedArray = [1, "apple", true, { name: "John" }];

8. Multidimensional Arrays:
You can create arrays of arrays to represent multidimensional data structures
like matrices.

let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 70/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

9. Array Destructuring:
JavaScript supports array destructuring, which allows you to assign array
elements to variables.

let [first, second] = [1, 2]; console.log(first); // Output: 1 con


sole.log(second); // Output: 2

Arrays are versatile and widely used in JavaScript for tasks such as storing data,
iterating through data, and implementing various algorithms and data
structures. Understanding how to work with arrays is fundamental for JavaScript
development.

Objects

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 71/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Understanding Objects
In JavaScript, an object is a composite data type that allows you to store and
organize related data and functionality. Objects consist of properties (variables)
and methods (functions). They are a fundamental building block in JavaScript
and are used extensively in web development.
Let's use a hypothetical Netflix movie object as a reference to understand
JavaScript objects:

let netflixMovie = { title: "Inception", year: 2010, director: "Christ


opher Nolan", genres: ["Sci-Fi", "Action", "Thriller"], duration: 148,
isAvailable: true, play: function() { console.log("Now playing: " + th
is.title); }, pause: function() { console.log("Paused: " + this.titl
e); } };

In this example, netflixMovie is an object with several properties and methods:

1. Properties:

• title : A string that stores the movie's title.

• year : An integer that stores the movie's release year.

• director : A string that stores the name of the movie's director.

• genres : An array that stores the movie's genres.

• duration : An integer that stores the movie's duration in minutes.

• isAvailable : A boolean that indicates whether the movie is available


for streaming.
2. Methods:

• play : A method (function) that logs a message indicating that the


movie is now playing.

• pause : A method (function) that logs a message indicating that the


movie is paused.

You can access properties and call methods of an object using dot notation:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 72/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

console.log(netflixMovie.title); // Output: "Inception" console.log(ne


tflixMovie.year); // Output: 2010 console.log(netflixMovie.genres); //
Output: ["Sci-Fi", "Action", "Thriller"] netflixMovie.play(); // Outpu
t: "Now playing: Inception" netflixMovie.pause(); // Output: "Paused:
Inception"

Here are some key concepts to understand about JavaScript objects:

• Properties: Objects can have various data types as properties, including


strings, numbers, arrays, and other objects.

• Methods: Methods are functions that are attached to an object and can
perform actions or computations related to the object's data.

• this Keyword: Inside object methods, the this keyword refers to the
current object. It allows you to access and modify the object's properties
and call other methods.

• Object Literal Notation: Objects can be created using object literal notation,
as shown in the example. You define the properties and methods within
curly braces {} .

• Dynamic Nature: JavaScript objects are dynamic, which means you can add,
modify, or remove properties and methods from an object at any time.
JavaScript objects are fundamental to modern web development, as they are
used to represent and manipulate data in a structured way. They play a crucial
role in building interactive websites and web applications.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 73/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Accessing keys
To access the keys (property names) of an object in JavaScript, you can use
various methods. Given your Netflix movie object reference, here are a few ways
to access its keys:

1. Using Object.keys() : The Object.keys() method returns an array of the


object's own enumerable property names (keys).

let netflixMovie = { title: "Inception", year: 2010, director: "Christ


opher Nolan", genres: ["Sci-Fi", "Action", "Thriller"], duration: 148,
isAvailable: true }; let keys = Object.keys(netflixMovie); console.log
(keys); // Output: ["title", "year", "director", "genres", "duration",
"isAvailable"]

2. Using a for...in Loop: You can iterate through the object's keys using a
for...in loop.

for (let key in netflixMovie) { console.log(key); // Output: "title",


"year", "director", "genres", "duration", "isAvailable" }

3. Using Object.getOwnPropertyNames() : The Object.getOwnPropertyNames()


method returns an array of all property names (both enumerable and non-
enumerable) of an object.

let keys = Object.getOwnPropertyNames(netflixMovie); console.log(key


s); // Output: ["title", "year", "director", "genres", "duration", "is
Available"]

4. Using Reflect.ownKeys() : The Reflect.ownKeys() method returns an array


of all property names (including symbols) of an object.

let keys = Reflect.ownKeys(netflixMovie); console.log(keys); // Outpu


t: ["title", "year", "director", "genres", "duration", "isAvailable"]

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 74/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Choose the method that suits your specific use case. Generally, Object.keys()
is commonly used when you want to access only the enumerable property
names, but if you need non-enumerable properties as well, you can use
Object.getOwnPropertyNames() or Reflect.ownKeys() .

Once you have the keys, you can use them to access the corresponding values in
the object or perform other operations as needed.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 75/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

for...in loop
The for...in loop in JavaScript is used to iterate over the properties (also
called enumerable keys) of an object. It provides an easy way to loop through
the keys of an object, making it particularly useful for working with objects and
dictionaries. Here's the basic syntax of the for...in loop:

for (let key in object) { // Code to execute for each property/key }

Here's a detailed explanation of how the for...in loop works:

• key is a variable that represents the current property/key being iterated


over.

• object is the object you want to iterate through.

Here's an example of using a for...in loop to iterate over the properties of an


object:

let person = { firstName: "John", lastName: "Doe", age: 30 }; for (let


key in person) { console.log(key + ": " + person[key]); }

In this example, the for...in loop iterates over the properties of the person
object ( firstName , lastName , and age ) and logs both the property name and
its corresponding value.
The output will be:

firstName: John lastName: Doe age: 30

It's important to note a few key considerations when using for...in loops:

1. Enumeration Order: The order in which properties are enumerated in a


for...in loop is not guaranteed to be in any particular order. Different
JavaScript engines may iterate over object properties in different orders.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 76/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

2. Inherited Properties: for...in also iterates over inherited properties in


addition to the object's own properties. To avoid this, you can use the
hasOwnProperty method to check if a property is an object's own property.

for (let key in object) { if (object.hasOwnProperty(key)) { // Cod


e to execute for each own property } }

3. Prototype Chain: Be cautious when using for...in with objects that are
part of a prototype chain (e.g., objects created from constructors or classes).
It may iterate over properties defined in the prototype chain as well.
In summary, the for...in loop is a useful way to iterate over the properties of
an object, making it suitable for tasks like enumerating object properties,
working with dictionaries, or dynamically inspecting and interacting with objects.
However, consider the order of iteration, inherited properties, and prototype
chain implications when using this loop construct.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 77/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Properties and Methods


In JavaScript, objects are at the core of the language, and they can have
properties and methods. Properties are like variables attached to objects, while
methods are like functions that are associated with objects. Here's an overview
of properties and methods in JavaScript:
Properties:

1. Object Properties: Objects can have named properties that store values.
These properties are accessed using dot notation ( object.property ) or
bracket notation ( object["property"] ).

let person = { firstName: "John", lastName: "Doe", age: 30 }; cons


ole.log(person.firstName); // Output: "John"

2. Built-in Object Properties: Some objects in JavaScript have built-in


properties. For example, strings have a length property, arrays have a
length property and forEach method, and functions have a name
property.

let text = "Hello, world!"; console.log(text.length); // Output: 1


3

Methods:
1. Object Methods: Objects can have methods, which are functions associated
with the object. These methods can perform actions or calculations related
to the object's data.

let car = { brand: "Toyota", model: "Camry", start: function() { c


onsole.log("Engine started."); } }; car.start(); // Output: "Engin
e started."

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 78/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

2. Built-in Object Methods: JavaScript provides built-in methods for many


objects, such as arrays, strings, and dates. For example, arrays have methods
like push , pop , map , and filter , while strings have methods like
toUpperCase , toLowerCase , and slice .

let numbers = [1, 2, 3, 4, 5]; numbers.push(6); // Adds 6 to the e


nd of the array let uppercaseText = "Hello".toUpperCase(); // Conv
erts "Hello" to "HELLO"

3. Function Methods: Functions are objects in JavaScript and can have


methods of their own. For example, you can define custom methods on
functions or use built-in methods like apply and call to control their
execution context.

function greet() { console.log("Hello, " + this.name + "!"); } gre


et.name = "John"; greet(); // Output: "Hello, John!"

4. Prototype Methods: In JavaScript, you can add methods to object


prototypes, which makes those methods available to all objects of that type.
For instance, you can add a custom method to the Array.prototype to
extend the functionality of all arrays.

Array.prototype.getFirstElement = function() { return this[0]; };


let numbers = [1, 2, 3]; console.log(numbers.getFirstElement());
// Output: 1

Understanding properties and methods is essential when working with objects


in JavaScript. Properties store data associated with objects, while methods
define behaviors or actions that objects can perform. You can use built-in
methods or create custom properties and methods to tailor objects to your
specific needs.

Functions

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 79/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Understanding Functions
In JavaScript, functions are a fundamental building block of the language, and
they play a crucial role in organizing and executing code. Let's understand
functions in JavaScript using your Netflix project reference.
Defining Functions:
You can define functions in JavaScript using the function keyword. Here's a
simple example of a function that represents playing a Netflix movie:

function playNetflixMovie(movie) { console.log("Now playing: " + movi


e.title); }

In this function:

• playNetflixMovie is the name of the function.

• (movie) is the parameter (input) the function accepts.

• console.log("Now playing: " + movie.title) is the code inside the


function that gets executed when the function is called.
Calling Functions:
To execute a function, you "call" it by using its name followed by parentheses,
passing any required arguments (values) inside the parentheses.

let netflixMovie = { title: "Inception", year: 2010, director: "Christ


opher Nolan", genres: ["Sci-Fi", "Action", "Thriller"], duration: 148,
isAvailable: true }; playNetflixMovie(netflixMovie); // Output: "Now p
laying: Inception"

In this example, we're calling the playNetflixMovie function and passing the
netflixMovie object as an argument.

Function Parameters:
Functions can accept parameters (inputs) that are used within the function.
These parameters act as variables inside the function.

function greet(name) { console.log("Hello, " + name + "!"); } greet("J


ohn"); // Output: "Hello, John!"

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 80/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

In the greet function, name is a parameter that accepts a value when the
function is called.

Return Values:
Functions can also return values using the return keyword. This allows you to
get results from a function.

function add(a, b) { return a + b; } let result = add(3, 5); console.l


og(result); // Output: 8

In the add function, the return a + b; statement returns the sum of a and
b to the caller.

Anonymous Functions:
You can define functions without a name, called anonymous functions, which are
often used as callbacks or assigned to variables.

let multiply = function(a, b) { return a * b; }; console.log(multiply


(4, 6)); // Output: 24

Arrow Functions (ES6):


ES6 introduced arrow functions, which provide a more concise syntax for
defining functions.

let divide = (a, b) => a / b; console.log(divide(8, 2)); // Output: 4

These are the fundamental concepts of functions in JavaScript. They allow you to
encapsulate code, reuse it, and make your code more organized and
maintainable. Functions are an essential part of building dynamic and interactive
applications, including your Netflix project.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 81/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Declaring and defining function


In JavaScript, you can declare and define functions using the function keyword.
Functions are blocks of code that can be named and reused to perform specific
tasks. Let's look at how you can declare and define functions with a reference to
your Netflix project.
Declaring Functions:

To declare a function in JavaScript, you use the function keyword, followed by


the function name, a set of parentheses for parameters (if any), and curly braces
for the function body. Here's an example declaration of a function that plays a
Netflix movie:

function playNetflixMovie(movie) { // Function body console.log("Now p


laying: " + movie.title); }

In this example:

• playNetflixMovie is the name of the function.

• (movie) is the parameter that the function accepts. It represents the movie
object passed to the function.

• Inside the function, there's a console.log statement that logs the title of
the movie.
Defining Functions:
Defining a function involves providing the actual code that the function will
execute. It's essentially the implementation of the function. Here's how you
define the playNetflixMovie function:

function playNetflixMovie(movie) { console.log("Now playing: " + movi


e.title); }

In the definition, we've included the console.log statement that displays the
movie title when the function is called.
Calling Functions:
To execute (or call) a function, you use its name followed by parentheses. You
can pass arguments (values) to the function if it expects parameters.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 82/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

let netflixMovie = { title: "Inception", year: 2010, director: "Christ


opher Nolan", genres: ["Sci-Fi", "Action", "Thriller"], duration: 148,
isAvailable: true }; playNetflixMovie(netflixMovie); // Calling the fu
nction with the movie object

In this example, we call the playNetflixMovie function and pass the


netflixMovie object as an argument.

Functions in JavaScript are a fundamental concept that allows you to


encapsulate code into reusable blocks, improving code organization and
maintainability. In your Netflix project, you can create and use functions to
perform various actions like playing movies, displaying information, and
handling user interactions.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 83/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

anonymous functions
In JavaScript, an anonymous function is a function that doesn't have a name.
Instead of being declared with a specific identifier, it's defined inline where it's
needed or assigned to a variable. Anonymous functions are also known as
"function expressions." They are commonly used for tasks like callbacks, event
handling, and immediate invocation. Here's how you can define and use
anonymous functions:
1. As a Function Expression:
You can define an anonymous function as an expression by assigning it to a
variable. This is useful when you need to pass functions as arguments to other
functions, such as in the case of callbacks.

let add = function(a, b) { return a + b; }; let result = add(3, 5); //


Calling the anonymous function console.log(result); // Output: 8

In this example, the anonymous function calculates the sum of two numbers and
is assigned to the add variable.
2. As Immediately Invoked Function Expressions (IIFE):
Anonymous functions can be invoked immediately after they are defined. This is
often used to create private scopes and avoid polluting the global namespace.

(function() { console.log("This is an IIFE."); })();

In this case, the function is wrapped in parentheses and immediately followed by


another pair of parentheses, which triggers the function execution.

3. As Function Arguments (Callbacks):


Anonymous functions are frequently used as callbacks when passing functions
as arguments to other functions, like in asynchronous operations or array
methods.

let numbers = [1, 2, 3, 4, 5]; let squared = numbers.map(function(numb


er) { return number * number; }); console.log(squared); // Output: [1,
4, 9, 16, 25]

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 84/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

In this example, an anonymous function is used as a callback within the map


method to square each number in the array.
Anonymous functions are versatile and handy in scenarios where you need a
simple function for a specific purpose without the need to give it a name. They
help keep your code concise and can be used in various situations where named
functions might not be required.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 85/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

methods
In JavaScript, methods are functions that are associated with objects. They are
one of the key features of object-oriented programming in the language.
Methods allow objects to perform actions or operations and can also be used to
compute and manipulate data within those objects. Here's how methods work in
JavaScript:
1. Defining Methods:
Methods are defined within object literals or as properties of a class prototype.
Here's an example of defining methods within an object literal:

let person = { firstName: "John", lastName: "Doe", fullName: function


() { return this.firstName + " " + this.lastName; } };

In this example, fullName is a method that returns the full name of the person
object.

2. Calling Methods:
To call a method, you use dot notation ( object.method() ). For example:

console.log(person.fullName()); // Output: "John Doe"

Here, we call the fullName method on the person object to retrieve the full
name.
3. The this Keyword:
Inside a method, the this keyword refers to the object that the method
belongs to. It allows you to access and modify properties of the object.

let person = { firstName: "John", lastName: "Doe", greet: function() {


console.log("Hello, " + this.firstName + " " + this.lastName + "!"); }
}; person.greet(); // Output: "Hello, John Doe!"

In the greet method, this.firstName and this.lastName access the


properties of the person object.

4. Methods in Classes (ES6):

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 86/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

In modern JavaScript (ES6 and beyond), classes are often used to define objects
with methods. Here's an example of a class with a method:

class Car { constructor(brand) { this.brand = brand; } start() { conso


le.log(this.brand + " is starting."); } } let myCar = new Car("Toyot
a"); myCar.start(); // Output: "Toyota is starting."

In this example, the Car class has a start method that can be called on
instances of the class.

5. Built-in Object Methods:


JavaScript provides many built-in methods for various objects, such as arrays,
strings, and dates. These methods allow you to perform operations on objects of
those types.

let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce(function(tota


l, num) { return total + num; }, 0); console.log(sum); // Output: 15

Here, reduce is a built-in method of arrays that is used to calculate the sum of
the numbers in the array.

Methods are essential for organizing and encapsulating behavior within objects,
making code more modular and maintainable. Understanding how to define,
call, and work with methods is a fundamental aspect of JavaScript programming.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 87/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Higher Order Functions


Higher-order functions are a fundamental concept in JavaScript that can greatly
enhance your ability to work with data and perform complex operations. In the
context of your Netflix-like OTT (Over-The-Top) streaming service project,
understanding higher-order functions can help you manage and manipulate
large datasets, filter content, and create a more dynamic user experience.
What Are Higher-Order Functions?
A higher-order function is a function that takes one or more functions as
arguments, returns a function as its result, or both. These functions allow you to
abstract and modularize common patterns of behavior in your code.
Examples of Higher-Order Functions in JavaScript:
Let's explore some commonly used higher-order functions and how they can be
applied in your Netflix OTT project:
1. map :
The map function is used to transform each element in an array into a new array
based on a provided function. In your project, this can be used to extract specific
data from a list of movies, such as their titles.

const movieData = [ { title: 'Movie 1', rating: 4.5 }, { title: 'Movie


2', rating: 3.8 }, { title: 'Movie 3', rating: 4.2 } ]; const movieTit
les = movieData.map(movie => movie.title); // Result: ["Movie 1", "Mov
ie 2", "Movie 3"]

2. filter :

The filter function creates a new array containing elements that meet a
specified condition. You can use it to filter out movies that meet certain criteria,
such as a minimum rating.

const highRatedMovies = movieData.filter(movie => movie.rating > 4.0);


// Result: [{ title: 'Movie 1', rating: 4.5 }, { title: 'Movie 3', rat
ing: 4.2 }]

3. reduce :

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 88/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

The reduce function is used to accumulate values in an array and return a


single result. You can employ it to calculate the total rating of all movies in your
project.

const totalRating = movieData.reduce((accumulator, movie) => accumulat


or + movie.rating, 0); // Result: 12.5

4. forEach :
The forEach function iterates over an array and performs a specified action for
each element. You can use it to display a list of movies or execute side effects,
such as updating user profiles.

movieData.forEach(movie => { console.log(`Title: ${movie.title}, Ratin


g: ${movie.rating}`); });

Custom Higher-Order Functions:

In your project, you may also create custom higher-order functions that
encapsulate specific behaviors. For example, you can create a function that
accepts a callback to fetch movie data from an API or a function to validate user
inputs during registration.

function fetchData(url, callback) { // Perform an HTTP request and cal


l the callback with the data } fetchData('<https://api.netflix-clone.c
om/movies>', movieData => { // Process movieData });

By understanding and effectively using higher-order functions, you can write


cleaner, more modular, and maintainable code for your Netflix OTT project.
These functions enable you to work with data and perform operations on it in a
functional and expressive manner, enhancing the overall user experience.

Advanced JavaScript

ES6

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 89/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

What is ECMAScript?
ECMAScript (ES) is a standardized scripting language specification primarily used
for defining the syntax, semantics, and behavior of scripting languages.
JavaScript, along with several other scripting languages like ActionScript and
JScript, is an implementation of the ECMAScript specification. Here's what you
need to know about ECMAScript:
1. Standardization: ECMAScript is not a programming language itself but rather
a standard specification for scripting languages. It was created to standardize
the behavior of scripting languages across different web browsers and
environments.
2. JavaScript: JavaScript is the most well-known and widely used
implementation of the ECMAScript specification. When people refer to
"JavaScript," they are often referring to the ECMAScript-compliant version of the
language used for web development.
3. Versions: ECMAScript has gone through several versions over the years, each
introducing new features, improvements, and changes to the language. The
major versions of ECMAScript are often referred to by their year of release, such
as ECMAScript 5 (ES5), ECMAScript 6 (ES6), and so on. ES6, also known as
ECMAScript 2015, introduced significant enhancements to JavaScript.

4. Compatibility: Web browsers and JavaScript engines implement specific


versions of ECMAScript. This means that not all features of the latest ECMAScript
version are immediately available in all browsers. Developers often use
transpilers like Babel to convert code written in the latest ECMAScript version
into code that can run in older browser environments.
5. Evolving Standard: The ECMAScript standard continues to evolve, with new
proposals and features being discussed and added in each new version. The
ECMAScript specification is maintained by Ecma International, a standards
organization.
6. Beyond the Web: While ECMAScript is most commonly associated with web
browsers and client-side scripting, it is also used in server-side environments
(Node.js) and for building cross-platform desktop and mobile applications (via
frameworks like React Native and Electron).

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 90/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

In summary, ECMAScript is a standardized specification that defines the core


features and behavior of scripting languages like JavaScript. It has played a
critical role in the growth and evolution of web development, enabling
developers to write more consistent and reliable code across different platforms
and browsers. Understanding ECMAScript versions and their features is
important for JavaScript developers to stay up-to-date with the latest language
enhancements and best practices.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 91/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Pass by Value & Pass by Reference


JavaScript uses a mechanism that is often referred to as "pass by value" when
passing arguments to functions. However, this can be a bit misleading, and it's
more accurate to say that JavaScript passes primitive types by value and objects
(including arrays and functions) by reference. Let's explore both concepts:
Passing by Value (Primitive Types):
When you pass a primitive type (like numbers, strings, or booleans) to a
function, a copy of the actual value is passed to the function. This means that
changes made to the parameter within the function do not affect the original
value outside the function.

function modifyValue(x) { x = x + 1; console.log("Inside function: " +


x); } let num = 5; modifyValue(num); console.log("Outside function: "
+ num);

In this example, the value of num remains unchanged outside the modifyValue
function because it's passed by value.
Passing by Reference (Objects, Arrays, Functions):
When you pass an object, array, or function to a function, you're passing a
reference to that object, not a copy. This means that changes made to the
object's properties or elements within the function will affect the original object
outside the function.

function modifyArray(arr) { arr.push(4); console.log("Inside function:


" + arr); } let myArray = [1, 2, 3]; modifyArray(myArray); console.log
("Outside function: " + myArray);

In this example, both the inside and outside of the function will display the
modified array [1, 2, 3, 4] because arrays are passed by reference.
Note: While objects, arrays, and functions are passed by reference in terms of
their memory address, it's essential to understand that reassigning the reference
variable within the function will not affect the original variable outside the
function. For example:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 92/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

function reassignObject(obj) { obj = { prop: "new value" }; } let myOb


j = { prop: "old value" }; reassignObject(myObj); console.log(myObj.pr
op); // Output: "old value"

In this case, myObj remains unchanged because we reassigned obj within the
function. However, if we modify properties of obj directly, those changes
would affect myObj as well.
In summary, JavaScript behaves differently when passing primitive types (pass by
value) and objects, arrays, or functions (pass by reference). Understanding this
distinction is crucial when working with JavaScript to avoid unexpected behavior
in your code.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 93/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Scope, Lifetime and Lexical Scope


In JavaScript, scope, lifetime, and lexical scope are important concepts that
govern how variables and functions are defined, accessed, and maintained
within the language. Let's explore each of these concepts:
1. Scope:

Scope refers to the context in which variables and functions are declared and
accessed. It determines where in your code you can use a particular variable or
function. JavaScript has two main types of scope:

• Global Scope: Variables and functions declared at the top level of a


JavaScript program or outside of any function have global scope. They can
be accessed from anywhere in the code, including within functions.

let globalVariable = "I'm global"; function globalFunction() { con


sole.log(globalVariable); } globalFunction(); // Output: "I'm glob
al"

• Local Scope: Variables and functions declared inside a function have local
scope. They can only be accessed within the function where they are
defined.

function localFunction() { let localVariable = "I'm local"; consol


e.log(localVariable); } localFunction(); // Output: "I'm local" //
This would result in an error because localVariable is not accessi
ble here. // console.log(localVariable);

2. Lifetime:
Lifetime refers to the duration for which a variable or function remains in
memory and retains its value. In JavaScript, the lifetime of a variable depends on
its scope:

• Global Variables: Global variables exist for the entire duration of your
application. They are created when your program starts and are only
destroyed when the program terminates or if you explicitly remove them.

• Local Variables: Local variables are created when the function is called and
destroyed when the function exits. They are short-lived and their values are
not retained between function calls.
3. Lexical Scope:

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 94/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Lexical scope, also known as static scope, refers to how the JavaScript engine
determines the scope of a variable by looking at the physical structure of the
code. It is based on where a variable is declared in your source code.

function outer() { let x = 10; function inner() { console.log(x); // L


exical scope allows inner() to access x from outer(). } inner(); } out
er();

In this example, inner() can access the variable x from outer() due to lexical
scope.
Understanding these concepts is crucial for writing clean and maintainable
JavaScript code. Properly managing scope and understanding the lifetime of
variables helps prevent issues like variable name collisions and memory leaks.
Lexical scope allows you to reason about variable access based on code
structure, enhancing code predictability and maintainability.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 95/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

Using 'let' and 'const'


In JavaScript, let and const are two keywords used for declaring variables.
They were introduced in ECMAScript 6 (ES6) and provide more control over
variable scope and reassignment compared to the older var keyword. Here's
how to use let and const effectively:
1. let Declaration:
The let keyword is used to declare variables that can be reassigned. Variables
declared with let have block scope, meaning they are limited in scope to the
block (within curly braces {} ) where they are defined.

let x = 5; // Declare and initialize a variable 'x' x = 10; // Reassig


n the value of 'x' if (true) { let y = 20; // 'y' is scoped to this bl
ock console.log(x); // Accesses the outer 'x' console.log(y); // Acces
ses 'y' within this block } console.log(x); // Outputs 10 console.log
(y); // Throws an error, 'y' is not defined here

2. const Declaration:
The const keyword is used to declare variables that cannot be reassigned once
they are defined. const variables also have block scope.

const PI = 3.14159; // Declare and initialize a constant 'PI' PI = 3.1


4; // This will result in an error, as you cannot reassign a constant
if (true) { const radius = 5; // 'radius' is scoped to this block cons
ole.log(PI); // Accesses the outer 'PI' console.log(radius); // Access
es 'radius' within this block } console.log(PI); // Outputs 3.14159 co
nsole.log(radius); // Throws an error, 'radius' is not defined here

Key Points:

• Use let when you need a variable that may change its value.

• Use const when you want to declare a constant variable whose value
should not change.

• Both let and const have block scope, so they are confined to the block in
which they are defined.

• Attempting to reassign a const variable or accessing it before initialization


will result in an error.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 96/97
9/15/23, 8:41 PM Notes - JavaScript Zero to Hero in 5 Days

• It's good practice to use const by default and only use let when you
explicitly need reassignment.
By using let and const , you can write more reliable and maintainable code by
reducing the risk of unintentional variable reassignments and making the scope
of your variables clearer.
Classes

Understanding classes
To help you understand how classes can be used in JavaScript with a reference
to a Netflix-like project, let's create a simplified example. We'll define classes for
movies, users, and a movie rental system. This is a basic representation, and a
real Netflix-like system would be far more complex, but it should help illustrate
the concepts.

1. Movie Class:
We'll start with a Movie class that represents movies available on the streaming
platform. Each movie has a title, year, genre, and availability status.

class Movie { constructor(title, year, genre) { this.title = title; th


is.year = year; this.genre = genre; this.available = true; } rent() {
if (this.available) { this.available = false; console.log(`You have re
nted ${this.title}. Enjoy!`); } else { console.log(`${this.title} is c
urrently unavailable.`); } } returnMovie() { this.available = true; co
nsole.log(`You have returned ${this.title}. Thank you!`); } }

2. User Class:
Next, we'll define a User class to represent users of the platform. Each user has
a name, subscription status, and a list of rented movies.

https://letsupgrade.notion.site/Notes-JavaScript-Zero-to-Hero-in-5-Days-6e2e4aab47e74c55874af9534f531ef1 97/97

You might also like