100% found this document useful (2 votes)
13 views

Instant ebooks textbook 50 JavaScript Concepts Every Developer Should Know: The Perfect Guide Every JavaScript Developer Needs to Get Started (50 Concepts Every Developer Should Know Book 1) Abella download all chapters

Every

Uploaded by

kvavikkaimet49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
13 views

Instant ebooks textbook 50 JavaScript Concepts Every Developer Should Know: The Perfect Guide Every JavaScript Developer Needs to Get Started (50 Concepts Every Developer Should Know Book 1) Abella download all chapters

Every

Uploaded by

kvavikkaimet49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Download Full Version ebookmass - Visit ebookmass.

com

50 JavaScript Concepts Every Developer Should


Know: The Perfect Guide Every JavaScript Developer
Needs to Get Started (50 Concepts Every Developer
Should Know Book 1) Abella
https://ebookmass.com/product/50-javascript-concepts-every-
developer-should-know-the-perfect-guide-every-javascript-
developer-needs-to-get-started-50-concepts-every-developer-
should-know-book-1-abella/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

50 Studies Every Anesthesiologist Should Know 1st Edition


Anita Gupta

https://ebookmass.com/product/50-studies-every-anesthesiologist-
should-know-1st-edition-anita-gupta/

ebookmass.com

50 Studies Every Obstetrician-Gynecologist Should Know 1st


Edition Liu

https://ebookmass.com/product/50-studies-every-obstetrician-
gynecologist-should-know-1st-edition-liu/

ebookmass.com

A Friendly Guide to Software Development: What You Should


Know Without Being a Developer Leticia Portella

https://ebookmass.com/product/a-friendly-guide-to-software-
development-what-you-should-know-without-being-a-developer-leticia-
portella/
ebookmass.com

Women, Literature and Finance in Victorian Britain:


Cultures of Investment 1st ed. Edition Nancy Henry

https://ebookmass.com/product/women-literature-and-finance-in-
victorian-britain-cultures-of-investment-1st-ed-edition-nancy-henry/

ebookmass.com
Developer Advocacy: Establishing Trust, Creating
Connections, and Inspiring Developers to Build Better 1st
Edition Riley Chris
https://ebookmass.com/product/developer-advocacy-establishing-trust-
creating-connections-and-inspiring-developers-to-build-better-1st-
edition-riley-chris/
ebookmass.com

Flow and Heat Transfer in Geothermal Systems. Basic


Equations for Describing and Modelling Geothermal
Phenomena and Technologies 1st Edition Aniko Toth
https://ebookmass.com/product/flow-and-heat-transfer-in-geothermal-
systems-basic-equations-for-describing-and-modelling-geothermal-
phenomena-and-technologies-1st-edition-aniko-toth/
ebookmass.com

On The Origin of Evolution : Tracing ‘Darwin’s Dangerous


Idea’ From Aristotle to DNA John Gribbin

https://ebookmass.com/product/on-the-origin-of-evolution-tracing-
darwins-dangerous-idea-from-aristotle-to-dna-john-gribbin/

ebookmass.com

Nonideal Social Ontology: The Power View Åsa Burman

https://ebookmass.com/product/nonideal-social-ontology-the-power-view-
asa-burman/

ebookmass.com

Dying by the Sword Monica Duffy Toft

https://ebookmass.com/product/dying-by-the-sword-monica-duffy-toft/

ebookmass.com
Teachers Schools and Society 10th Edition – Ebook PDF
Version

https://ebookmass.com/product/teachers-schools-and-society-10th-
edition-ebook-pdf-version/

ebookmass.com
50 JavaScript
Concepts Every
Developer
Should Knouu

Hernando Abella
THANK YOU FOR TRUSTING OUR PUBLISHING HOUSE. IF YOU HAVE THE OPPORTUNITY TO EVALUATE
OURWORK AND GIVE US A COMMENT ON AMAZON, WE WILL APPRECIATE IT VERY MUCH!

THIS BOOK MAY NOT 8E COPIED OR PRINTED WITHOUT THE PERMISSION OF THE AUTHOR

COPYRIGHT 2023 ALUNA PUBLISHING HOUSE


1. Call Stack 06
2. Primitive Types 07
3. Value Types and Reference Types 08
4. Implicit, Explicit, Nominal, Structural, and Duck Typing 10
5. == vs === vs typeof 12
6. Function Scope, Block Scope, and Lexical Scope 13
7. Expression vs Statement 15
8. IIFE, Modules, and Namespaces 17
9. Message Queue and Event Loop 19
10. setTimeout, setinterval, and requestAnimationFrame 21
11. JavaScript Engines 23
12. Bitwise Operators, Typed Arrays, and Array Buffers 25
13. DOM and Document Trees 27
14. Factories and Classes 29
15. this, call, apply, and bind 31
16. new, Constructor, instanceof, and Instances 33
17. Prototypal Inheritance and Prototype Chain 35
18. Object.create and Object.assign 37
19. map, reduce, and filter 39
20. Pure Functions, Side Effects, State
40
Mutation, and Event Propagation
21. Closures 42
22. High Order Functions 43
23. Recursion 45
24. Collections and Generators 46
25. Promises 48
26. async/await 50
27. Data Structures 52
28. Costly Operations and Big O Notation 54
29. Algorithms 56
30. Inheritance, Polymorphism, and Code Reusability 58
31. Design Patterns 61
32. Partial Application, Currying, Composition, and Pipe 64
33. Clean Code 67
34. Error Handling (try...catch) 69
35. ES6 Modules 70
36. Ternary Operator 72
37. Spread and Rest Operators 73
38. Destructuring 75
39. Template Literals 77
40. Arrow Functions 79
41. Array Methods (forEach, some, every,
find, findindex, etc.)
42. String Methods (split, trim, replace, eta) 84
43. Object Methods (kegs, values, entries, etc.) 86
44. Math Methods (floor, ceil, random, etc.) 88
45. JSON and Object Serialization/Deserialization 90
46. Fetch API and AJAX 92
47. Localstorage and Sessionstorage 94
48. WebSockets and Socket.10 96
49. Canvas and WebGL 100
50. Testing with Jest or Mocha 102
This book is on essential guide for all JavaScript
programmers since it has very important concepts such as:

• Design Patterns
• Clean Code
• Fetch API and AJAX
• Destructuring
• Partial Application, Currying, Composition, and Pipe

Learning these concepts will help you level up quickly as a


JavaScript developer, they are concepts that you should
know if you want to be at a higher level.

05
1. Call Stack
A call stack is a data structure that stores information about the
active subroutines or function calls in a computer program. It
operates on a Last In, First Out (LIFO) basis, meaning that the last
function called is the first one to be resolved or completed.

// Function definitions
function washDishO {
console.log("Washing dish");
dryDishO;
console.log("Finished washing dish");
}

function dryDishO {
console.log("Drying dish");
storeDish();
console.logC'Finished drying dish");
}

function storeDishO {
console.log("Storing dish");
}

// Calling the main function


washDishO;

In this example, when washDish is called, it gets added to the call


stack. Inside washDish, dryDishO's called, which, in turn, gets added
to the call stack Finally, storeDishQ is called from dryDishQ, and it
also gets added to the call stack

06
2. Primitive Types
Primitive types refer to the fundamental data types that are not
composed of other types. They are the simplest and most basic data
entities directly supported by the programming language. Primitive
types are usually built-in and include fundamental data categories
such as integers, floating-point numbers, characters, and boolean
values.

Integer:
let age = 25; // Integer

Floating-point:
let temperature = 26.5; // Float

Floating-point:
let grade = 'A1; // Character

Floating-point:
let isStudent = true; // Boolean

These are examples of primitive types because they represent the


most basic forms of data in the language and are not composed of
other types. They serve as the building blocks for more complex data
structures.

97
3. Value Types and Reference Types
Values can be classified into two categories: value types and reference
types. This distinction is crucial to understand how data is handled and
stored in memory.

Value Types (Primitives): Value types represent simple data and are
stored directly in the variable. When you assign a primitive value to a
variable, the actual value is copied into the variable.

Example:

1. Number
2. String
3. Boolean
4. Null
5. Undefined
6.Symbol
7. Biglnt

let numl = 42; // Value type (Number)


let text = "Hello"; // Value type (String)
let isTrue = true; // Value type (Boolean)

08
Reference Types (Objects): Reference types represent more complex
objects and are stored by reference, meaning the variable contains a
reference to the memory location where the object is stored.

1 .Literal Objects
2 .Arrays
3 . Functions
4 .User-Defined Objects

Example:

let person = { name: "Ana", age: 30 };


// Reference type (Literal Object)
let colors = ["red", "green", "blue"];
11 Reference type (Array)
function greet() { console.log("Hello"); }
// Reference type (Function)

Key Difference: The main difference between value types and reference
types Lies in how they are stored and manipulated in memory. Value types
are immutable, meaning that modifying them creates a new instance in
memory. In contrast, reference types are passed by reference, so
modifying them also modifies the original object in memory.

09
4. Implicit, Explicit, Nominal,
Structural, and Duck Typing
The concepts of typing refer to how data types are managed and
assigned in a language. Here is a description of the different types of
typing:

Implicit Typing: In Languages with implicit typing, a variable's data type


is automatically determined based on the assigned value. No explicit type
declaration is needed.

let number = 42; // Type is inferred as Number

Explicit Typing: In languages with explicit typing, the programmer must


explicitly declare the data type of a variable during its creation.

let name: string = "Juan"; // Type is declared as String

Nominal Typing: Nominal typing relies on type names and focuses on


nominal differences between types, even if their internal structure is
identical.

type User = { name: string };


type Employee = { name: string };

function greet(user: User) {


console.log('Hello, ${user.name}');
}

const employee: Employee = { name: "Ana" };


greet(employee); // Nominal typing error, even though the
structure is the same

ie
Structural Typing: Structuraltyping is based on the structure and shape
of data types, rather than their names. Two types are considered
compatible if they have the same structure.

type Person = { name: string


type Citizen = { name: string };

function greet(person: Person) ■{


console.log('Hello, ${person.name}');
}

const citizen: Citizen = { name: "Carlos" };


greet(citizen); // No structural typing error, the structure is
the same

Duck Typing: Duck typing is based on whether an object behaves Like a


certain type, regardless of its structure or name.

interface CanSing {
sing(): void;

function entertain(concert: CanSing) {


concert.sing();

const canary = ■{
sing: () => console.log("Tweet tweet")
};

entertain(canary); // Type doesn't matter, as long as it has the


'sing' method
5. == vs === vs typeof
=- ==- and typeof are operators used to compare values and retrieve
information about data types. Here's an explanation of each:

== (Weak Equality): The == operator compares two values for equality


but performs type conversion if the values are of different types. This is
called "weak equality" or "type coercion."

5 == "5"; // true, type conversion is performed

=== (Strict Equality): The === operator compares two values for
equality without performing type conversion. This is known as "strict
equality" and is recommended for precise comparisons.

5 === "5"; // false, no type conversion is performed

typeof (typeof Operator): The typeof operator is used to obtain the data
type of an expression. It returns a string representing the data type.

typeof 42; // "number"


typeof "Hello"; // "string"
typeof true; // "boolean"

• == compares values allowing type conversion.


• === compares values without allowing type conversion (strict
equality).
• ypeof returns the data type of an expression as a string.

It is important to understand the difference between == and === to avoid


unexpected comparison issues due to automatic type conversion. The use
of === is generally safer and recommended as it provides more accurate
comparisons and avoids surprises in your program's behavior.
ii n
xc

6. Function Scope, Block Scope, and


Lexical Scope
The concepts of function scope, block scope, and Lexical scope refer to how
variables are accessed and managed in different contexts within the code.

Function Scope: In JavaScript, variables declared within a function are


visible and accessible only within that function and any nested functions
within it This is called function scope. Variables declared with var have
function scope.

function myFunctionO {
var functionvariable = 42;
console.log(functionVariable);
// Accessible within the function
}

console.log(functionvariable);
// Not accessible outside the function

Block Scope: With the introduction of Let and const in ES6, block scope
was introduced. Variables declared with let and const have a scope
Limited to the block in which they are declared, such as within an if, a for, a
while, etc.

if (true) {
let blockvariable = "Hello";
const anotherBlockVariable = "World";

console.log(blockvariable); // Error, outside block scope


console.log(anotherBlockVariable); // Error, outside block scope
16

Lexical Scope: Lexical scope refers to how nested functions can access
variables from their parent functions, regardless of where they are called.
This is because functions in JavaScript maintain a reference to the scope in
which they were created.

function outer() {
let outervariable = "Outer";

function inner() {
console.log(outerVariable); // Access to the variable
from the parent function
}

return inner;
}

const nestedFunction = outerO;


nestedFunctionO; // Prints "Outer"

Function scope, block scope, and lexical scope are essential concepts to
understand how variables behave in different contexts. These concepts
play a key role in understanding JavaScript execution and preventing
errors related to variable scope.
14

7. Expression vs Statement
Expressions and statements are fundamental concepts used to construct
programs.

Expression: An expression is a combination of values, operators, and


function calls that evaluates to a single value. It can be as simple as a
literal value or as complex as a mathematical operation or a function call.

5 + 3 // Mathematical operation
"Hello, " + "World" // String concatenation
myFunctionO // Function call
42 // Literal value

Statement: A statement is a unit of code that performs an action or a


series of actions. It represents a complete instruction in a program and
can be a control flow statement, an assignment, a function declaration,
etc.

if (condition) {
// If statement
}

let x = 10; // Assignment

function greet() {
// Function statement
}

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


// For loop statement
}
15

• Expression: It is a combination of values, operators, and/or function


calls that evaluates to a single value.
• Statement: It is a unit of code that performs an action or a series of
actions in a program.

An important distinction is that expressions have a resulting value, while


statements can change the program's execution flow or perform
operations without necessarily returning a value. Both concepts are
essential for writing coherent and effective code in any programming
language.
16

8. IIFE, Modules, and Namespaces


Immediately Invoked Function Expressions (IIFE), modules, and
namespaces are techniques used to modularize and organize code. Each
addresses scope management and code organization in different ways.

IIFE (Immediately Invoked Function Expression): An IIFE is a function


that is defined and executed immediately after its creation. It is useful for
creating a private function scope and avoiding pollution of the global
scope.

(functionO {
// Code inside the IIFE
BO;

Modules: Modules are a more modern and structured way of organizing


code, f hey allow breaking the code into separate and reusable parts while
maintaining the local scope of variables. In ES6, the import and export
keywords were introduced to work with modules.

// module.js
export function greet() {
console.log("Hello from the module!");
}

// main.js
import { greet F from "./module.js";
greet();
17

Namespaces: Namespaces are an older approach to code organization.


They allow grouping related objects and functions under a common name
to avoid naming collisions. This is done using global objects.

// MyNamespace.js
var MyNamespace = {
variable: 42,
func: functionO {
console.logC'Function in MyNamespace");

MyNamespace.funcO;

Each approach has its own advantages and disadvantages. IIFE is useful
for creating private scopes but can become complex in large projects.
Modules are the modern way to modularize code and are more efficient
for maintenance and scalability. Namespaces are an older technique but
can still be useful in certain situations where full modularity is not
necessary.

In modern projects, it is recommended to use modules to effectively


organize code and maintain cleaner control over scope and code reuse.
18

9. Message Queue and Event Loop


The message queue and event Loop are crucial concepts to understand
how event handling and asynchronous operations work in JavaScript

Message Queue: The message queue is a structure where events and


pending callback functions are stored to be executed. These events can
include user interactions, timers, network requests, and more.

Event Loop: The event Loop is a continuous cycle running in the


background of the JavaScript program. Its function is to constantly check
if there are tasks in the message queue to be processed. If there are tasks
pending in the queue, the event Loop takes them one by one and executes
them in order.

The interaction between the message queue and the event loop is
fundamental to understanding how JavaScript handles asynchronous and
non-blocking tasks. When an event occurs or an asynchronous task is
completed (such as an AJAX request or a timer), a callback function is
added to the message queue. The event Loop takes these functions one by
one and executes them.

Example of Message Queue and Event Loop:

console.log("Start of the program");

setTimeout(function() {
console.log("Asynchronous task completed");
}, 1000);

console.log("End of the program");


19

Expected Output:

Start of the program End of the program Asynchronous task completed


In this example, the code executes in the following order:

1 . "Start of the program" is printed.


2 . A timer is initiated with setTimeout
3 ."End ofthe program" is printed.
4 .After 1 second (1000 ms), the timer completes, and the callback
function is added to the message queue.
5 .The event loop takes the callback function from the queue and
executes it, printing "Asynchronous task completed."

Understanding how the message queue and event loop work is crucial for
writing asynchronous JavaScript code and avoiding blocking and
bottlenecks in program execution.
20

10. setTimeout, setinterval, and


requestAnimationFrame
These three functions are very useful for working with timers and
performing asynchronous tasks in JavaScript However, each has its own
purpose and advantages.

setTimeout: setTimeout is used to schedule the execution of a function


after a certain period of time (in milliseconds). You can use it to create
delays in code execution or to perform actions after a specified time.

console.log("Start");

setTimeout(function() {
console.log("Step after 1000 ms");
1000);

console.log("End");

setinterval: setinterval is used to repeatedly execute a function at regular


time intervals. Unlike setTimeout, setlnterval will keep running the function
in a loop until explicitly stopped.

let counter = 0;

let interval = setlnterval(function() {


console.logO'Counter:", counter);
counter++;

if (counter > 5) ■{
clearlnterval(interval); // Stop the interval after 5
times
}
1 mnnV
21

requestAnimationFrame: requestAnimationFrame is a function


specifically used for creating smooth animations in the browser. It ensures
that animations run in sync with screen refreshes, improving performance
and user experience.

function animate(timestamp) {
// Perform animation changes here
// Call requestAnimationFrame again
requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

• setTimeout: Executes a function after a certain time.


• setinterval: Executes a function at regular intervals.
• requestAnimationFrame: Used for creating smooth and efficient
animations.

Choose the appropriate function based on your needs. setTimeout and


setinterval are useful for controlling time and executing code after certain
intervals, while requestAnimationFrame is specific for creating smooth
and efficient animations in the browser.
11. JavaScript Engines
JavaScript engines are fundamental components in browsers and
execution environments that interpret and execute JavaScript code. Each
browser and environment has its own JavaScript engine.

Here are some of the well-known engines:

V8 (Google Chrome, Node.js): V8 is an open-source JavaScript engine


developed by Google. It is known for its speed and efficiency in executing
code. It is used in Google Chrome and is also the engine behind Node.js,
enabling JavaScript to run on the server.

SpiderMonkey (Mozilla Firefox): SpiderMonkey is the JavaScript engine


used in Mozilla Firefox. It was one of the first JavaScript engines and has
been extensively optimized overtime to improve performance.

JavaScriptCore (Safari): JavaScriptCore, also known as Nitro, is the


JavaScript engine for Safari. It is developed by Apple and is used in Safari
browsers and other Apple products.

Chakra (Internet Explorer, Microsoft Edge Legacy): Chakra was the


JavaScript engine used in earlier versions of Internet Explorer and the
initial versions of Microsoft Edge (up to EdgeHTML). However, Microsoft
Edge has migrated to a new engine called Blink.
23

Blink (Chromium, Microsoft Edge): Blink is an open source rendering


engine that also includes a JavaScript engine. It is used in the Chromium
project (the base for Google Chrome) and in the latest version of Microsoft
Edge.

JerryScript: JerrgScript is a JavaScript engine designed for devices with


Limited resources,such as microcontrollers and embedded systems.

Nashorn (Java): Nashorn was a JavaScript engine developed by Oracle


and integrated into the Java platform. However, starting from Java 11,
Nashorn was removed from the JDK in favor of other technologies.

These are just a few examples of the many JavaScript engines that exist
Each engine has its own features and approaches to optimizing and
executing JavaScript code, contributing to the browsing experience and
performance of online applications.
24

12. Bitwise Operators, Typed


Arrays, and Array Buffers
These concepts are related to advanced data manipulations in JavaScript

Bitwise Operators: Bitwise operators allow you to perform


manipulations at the bit level rather than on entire integer values. They
are useful for bitwise operations such as masks and individual bit
manipulations.

Some bitwise operators in JavaScript include:

• &(AND): Performs a bitwise AND operation.


• I (OR): Performs a bitwise OR operation.
. a (XOR): Performs a bitwise XOR operation.
. -(NOT): Performs a bitwise NOT operation.
• « (Left Shift): Shifts bits to the left
• » (Right Shift with Sign): Shifts bits to the right preserving the sign.

Typed Arrays: Typed Arrays are data structures in JavaScript that allow
you to store binary data of specific types, such as integers, floats, etc. They
are useful for manipulating raw data and performing low-level operations
efficiently.

Some types of typed arrays in JavaScript are:

• lnt8Array: 8-bit signed integer array.


• UintSArray: 8-bit unsigned integer array.
• Float32Arrau: S?-hit fioatina-noint number arrau.
const intArray = new Int8Array([10, 20, 30]);

25

Array Buffers: Array Buffers are a data structure representing a raw


memory area that can contain binary data. Array Buffers are used to
work with binary data efficiently, and Typed Arrays are views of these
buffers that provide a manipulation interface.

const buffer = new ArrayBuffer(8);


/I Create an 8-byte buffer
const intArray = new Int32Array(buffer);
// View the buffer as a 32-bit integer array

These concepts are more advanced and are typically used when bitwise
manipulation and low-level operations are required. They are especially
useful in applications dealing with network protocols, binary data, and
performance optimization.
26

13. DOM and Document Trees


The DOM (Document Object Model) is a structural representation of an
HTML or XML document that allows interaction and manipulation of a
web page's content and structure through programming. The DOM
organizes document elements into a hierarchical structure called the
documenttree.

Document Tree (DOM Tree): The document tree is a hierarchical


structure that organizes all the elements of an HTML or XML document
Each element attribute, and text content is represented as a node in the
tree. Nodes are organized hierarchically, starting from the root node,
which represents the entire document.

In the case of a web page, the document tree represents how HTML
elements are nested and related to each other.

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<hl>Page Title</hl>
<p>This is a paragraph.</p>
</body>
</htmt>

The corresponding document tree would have a structure similar to this:


27

Document (html)
— html
I— head
I I-- title
I I-- "My Page"
|— body
I I- hl
I II— "Page Title"
I I- P
I I— "This is a paragraph."

DOM Manipulation: Through JavaScript, you can interact and modify the
content and structure of a web page via the DOM. You can access
elements, modify their attributes, add or remove nodes, and change their
content

// Access an element and change its content


const heading = document.querySelector("hl");
heading.textcontent = "New Title";

The DOM and the document tree are essential concepts for
understanding how browsers represent and manipulate HTML and XML
documents. The ability to interact with the DOM through JavaScript
enables the creation of dynamic interactions and rich experiences on web
pages.
28

14. Factories and Classes


Factories and classes are two approaches to creating objects and
structures in JavaScript Each has its own purpose and advantages.

Factories: Factories are functions that generate and return objects. These
functions act as "factories" to create instances of objects with specific
properties and methods. Factories are a flexible way to create objects in
JavaScript as they can customize object creation based on the provided
arguments.

function createPerson(name, age) {


return {
name: name,
age: age,
greet: function() ■{
console.log('Hello, I'm ${this.name} and I'm
Sfthis.age} years old.);
}
};

const personl = createPerson("John", 30);


personl.greet();
// Prints "Hello, I'm John and I'm 30 years old."
29

Classes: Classes are a concept introduced in ES6 that allows creating


objects using a more object-oriented syntax. Classes serve as a blueprint
for creating objects and define properties and methods that all instances
will share. Although in JavaScript, classes are "syntactic sugar" over the
prototype system, they provide a more structured way of working with
objects.

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greetO {
console.log('Hello, I'm Sfthis.name} and I'm Sfthis.age}
years old.');

const person2 = new Person("Jane", 25);


person2. greetO;
// Prints "Hello, I'm Jane and I'm 25 years old."

In summary:

• Factories: Use functions to create and customize objects.


• Classes: Define object blueprints with shared properties and methods.

The choice between factories and classes depends on your needs and
preferences. Factories are more flexible and versatile, while classes
provide a more object-oriented structure and are especially useful when
working with inheritance and similar objects.

30

15. this, call, apply, and bind


this, call, apply, and bind are concepts and methods in JavaScript related
to managing the value of this in the context of a function. Here's a
description of each of them:

this: In JavaScript, this refers to the object that is the current "execution
context" in a function. The value of this can change depending on how a
function is called and where it is in the code.

call and apply: Both methods allow temporarily changing the value of
this in a function and then executing it The main difference between call
and apply Lies in how arguments are passed:

call: Invokes a function with a specific value for this and individually
passed arguments.

function greet(name) {
console.logCHello, ${name}! My name is Sfthis.name}');
}

const person - { name: 'John'

greet.call(person, 'Maria'); // Prints: "Hello, Maria! My name is


John"

apply: Similar to call, but arguments are passed as an array.


31

function greet(name) {
console.log('Hello, ${name}! My name is Sfthis.name}');
}

const person - { name: 'John' };

greet.apply(person, ['Maria']);
// Prints: "Hello, Maria! My name is John"

bind: The bind method returns a new function where the value of this is
fixed to the provided value, and the initial arguments (if any) are "bound"
to the new function.

function greet(name) ■{
console.log('Hello, ${name}! My name is Sfthis.name}');
}

const person - { name: 'John'


const greetPerson - greet.bind(person);

greetPerson('Maria'); // Prints: "Hello, Maria! My name is John"

In summary:

• this: Refers to the current execution context


♦ call: Invokes a function with a specific value for this and individually
passed arguments.
• apply: Similar to call, but arguments are passed as an array.
• bind: Creates a new function with this and arguments fixed.
These methods ore useful for controlling the context of this in different
situations, especially when working with functions that are part of objects
or when you need to manipulate how a function is invoked.

32

16. neuu, Constructor, instanceof,


and Instances
These concepts are related to the creation and use of objects through
constructors in JavaScript.

new: new is a keyword used to create a new instance of an object from a


constructor function. When used with a constructor function, new creates
a new object and assigns the value of this within the function to the new
object Then, the constructor function can initialize properties and
methods on that object

function Person(name, age) {


this.name = name;
this.age = age;
}

const personl = new PersonC'John", 30);

Constructor: A constructor is a function used to create and configure


objects. Constructors often follow a naming convention with the first
Letter capitalized. Inside the constructor, you can initialize properties and
methods of the object that will be created with new.

instanceof: instanceof is an operator used to check if an object is an


instance of a specific class or constructor. It returns true if the object is an
instance of the given class, otherwise, it returns false.
33

console.log(personl instanceof Person); // Returns true

Instances: An instance is a unique object created from a constructor. Each


time you use new with a constructor, a new instance of the object is
created with its own properties and methods.

const person2 = new Person("Maria", 25);

In summary:

• new: A keyword used to create instances of objects from constructors.


• Constructor: A function used to create and configure objects.
• instanceof: An operator to check if an object is an instance of a class
or constructor.
• Instances: Unique objects created from constructors.

Constructors and instances are essential for object-oriented


programming in JavaScript, allowing the creation of objects with shared
properties and behaviors.
34

17. Prototypal Inheritance and


Prototype Chain
Prototypal inheritance and the prototype chain are fundamental concepts
in JavaScript for achieving code reuse and establishing relationships
between objects.

Prototypal Inheritance: In JavaScript, prototypal inheritance is a


mechanism by which an object can inherit properties and methods from
another object called its "prototype." Instead of traditional classes,
JavaScript uses prototypal inheritance to create relationships between
objects. When a property or method is looked up in an object, if it's not
found in the object itself, it is searched in its prototype and in the
ascending prototype chain.

Prototype Chain: The prototype chain is a series of links between


prototype objects. Each object has an internal link to its prototype, and
that prototype, in turn, may have its own prototype. This chain continues
until it reaches the base object, which is the final prototype in the chain.

Example of Prototypal Inheritance and Prototype Chain:

// Define an "Animal" constructor


function Animal (name) ■{
this.name = name;
}

// Add a "greet" method to the prototype of "Animal"


Animal.prototype.greet = functionU i
console.log(Hello, I'm a ${this.name}');
};

35

// Define a "Dog" constructor that inherits from "Animal"


function Dog(name, breed) I
Animal.call(this, name); // Call the "Animal" constructor
this.breed = breed;
}

// Establish prototypal inheritance


Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// Add an additional method to "Dog"


Dog.prototype.bark = functionO {
console.logC'Woof woof!");
};

// Create an instance of "Dog"


const myDog = new Dog("Max", "Labrador");
myDog.greet(); // Prints "Hello, I'm Max"
myDog.bark(); // Prints "Woof woof!"

In this example:

• We create the Animal constructor with a greet method.


• We create the Dog constructor that inherits from Animal and has a
bark method.
• Prototypal inheritance is established using Object create Q, and we
ensure that the Dog constructor points correctly.
• We create an instance of Dog, and we can access methods from both
Animaland Dog.
Prototypal inheritance and the prototype chain are crucial for
understanding how objects work and code reuse in JavaScript

36

18. Object.create and Object.assign


Both Objectcreate and Objectassign are important methods in JavaScript
used for working with objects, but they serve different purposes.

Objectxreate: Objectcreate is a method used to create a new object and


set its prototype (parent object). It allows creating objects that inherit
properties and methods from another object It's especially useful for
implementing prototypal inheritance in JavaScript

const newObj = Object.create(prototype);

Example of Objectcreate:

const animal = {
sound: "Makes a sound",
makeSound: function() ■{
console.log(this.sound);
}
};

const dog = Object.create(animal);


dog.sound = "Woof woof";
dog.makeSound(); // Prints "Woof woof"

Objectassign: Objectassign is a method used to copy enumerable


properties from one or more source objects to a target object If there are
properties with the same name in the target object they will be
overwritten. It's usefulfor combining objects or cloning objects.
Object.assign(targetobject, sourceObjectl, source0bject2, ...);

37

Example of Objectassign:

const target =
const sourcel = ■{ name: "John", age: 30
const source2 = { city: "New York" };

Object.assign(target, sourcel, source2);


console.log(target);
// Prints { name: "John", age: 30, city: "New York" }

In summary:

• Objectcreate: Creates a new object with a specified prototype.


• Objectassign: Combines or copies enumerable properties from
source objects to a target object

Objectcreate is useful for establishing prototypal inheritance


relationships, while Objectassign is useful for combining properties from
multiple objects or for cloning objects.
38

19. map, reduce, and filter


These are three high-level methods provided by JavaScript for working
with arrays in a more functional and elegant way. Each one has a specific
purpose and is widely used for transforming, filtering, and reducing data in
arrays.

map: The map method is used to transform each element of an array into
a new array by applying a function to each element It returns a new
array with the results of applying the function to each original element in
the same order.

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


const doubles = numbers.map(number => number * 2);
// doubles is now [2, 6, 8]

filter: The filter method is used to create a new array with all elements
that pass a test (meet a condition) provided by a function. It returns a new
array with the elements that satisfy the condition.

const numbers - [1, 2, 3, 5, 6];


const evens - numbers.filter(number => number % 2 --- 0);
// evens is now [2, 6]

reduce: The reduce method is used to reduce an array to a single


cumulative value. It applies a function to an accumulator and each
element in the array (from left to right), reducing the array to a single
value.
Exploring the Variety of Random
Documents with Different Content
PRINTED BY
MORRISON AND GIBB LIMITED, EDINBURGH.

FOOTNOTES:

[1]More accurately the coffee-house of the dome.—Translator’s


Note.
[2]The Arabs in this country keep no account of their age. The
most they can remember is that they were born the year this or
that happened.
[3]Chest.
[4]Correspondence in the Paris newspaper, the Journal des
Debats of 5th September 1893.
[5]M. Rouvier is newly appointed to Stockholm as French
Representative.
[6]Anthropologie Criminelle des Tunisiens Musulmans; Les
formes de la famille chez les premiers habitants de l’Afrique du
Nord; Exploration anthropologique de la Khroumirie.
[7]Duveyrier, Les Touareg du Nord; Captain Bissuel, Les
Touareg de l’Ouest; Largeau, Le Sahara Algerien.
[8]From Dr. E. F. Bojesen’s Handbook on Greek Antiquities.
*** END OF THE PROJECT GUTENBERG EBOOK THE CAVE
DWELLERS OF SOUTHERN TUNISIA ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright
in these works, so the Foundation (and you!) can copy and
distribute it in the United States without permission and without
paying copyright royalties. Special rules, set forth in the General
Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree to
abide by all the terms of this agreement, you must cease using
and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it
away or re-use it under the terms of the Project Gutenberg
License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country where
you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of the
copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite
these efforts, Project Gutenberg™ electronic works, and the
medium on which they may be stored, may contain “Defects,”
such as, but not limited to, incomplete, inaccurate or corrupt
data, transcription errors, a copyright or other intellectual
property infringement, a defective or damaged disk or other
medium, a computer virus, or computer codes that damage or
cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES -


Except for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU
AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE,
STRICT LIABILITY, BREACH OF WARRANTY OR BREACH
OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE
TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER
THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR
ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE
OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF
THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If


you discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person or
entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you do
or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status by
the Internal Revenue Service. The Foundation’s EIN or federal
tax identification number is 64-6221541. Contributions to the
Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or
determine the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
back
back
back
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like