Quail JS
Quail JS
JAVASCRIPT
ARIHARASUDHAN
arihara-sudhan.github.io/books.html
INTRODUCTION
According to WIKI, JavaScript ,
often abbreviated as JS, is a
programming language that is
one of the core technologies of
the World Wide Web, alongside
HTML and CSS. As of 2023,
98.7% of websites use
JavaScript on the client side
for webpage behavior, often
rd
incorporating 3 party libraries.
All major web browsers have a
dedicated JavaScript engine to
execute the code on users'
devices. JavaScript is a high-level,
often just-in-time compiled
language that conforms to the
ECMAScript standard. It has
dynamic typing, prototype-based
object-orientation, and first-class
functions. Java and JavaScript are
similar in name, syntax, and
respective standard libraries but
distinct by design.
VARIABLES
Variables are used to store
values under a given name. We
can declare variables using the
var, let, or const keywords.
★ var declares a variable
globally or locally to a
function, regardless of block
scope.
★ let declares a variable with
block scope, which means it is
limited to the block where it's
defined.
DATATYPES
Datatype represents the type of
the data. In JavaScript, there
are several data types that we
can use to store and manipulate
different kinds of data.
Here are some of the most
common data types in
JavaScript along with examples
and explanations:
★ Number: Used to represent
both integer and floating-point
numbers.
let age = 25; // Integer
let temp = 98.6; // Float
★ String: Used to represent
textual data enclosed in single
or double quotes.
// Using Double quotes
let name = "John";
// Using Single quotes
let city = 'New York';
★ Boolean: Represents a binary
value, either true or false.
let isStudent = true;
let isWorking = false;
★ Array: An ordered collection
of values, which can be of
different data types (in JS).
let fruits = ["apple", "banana",
"orange"];
let numbers = [1, 2, 3, 4, 5];
★ Object: A collection of key-
value pairs, where keys are
strings (properties) and values
can be of any data type.
let person = {
name: "Alice",
age: 30,
isStudent: false
};
★ Undefined: Represents that a
variable has been declared but
has no assigned value.
let x;
console.log(x); // undefined
★ Null: Represents an
intentional absence of any
object value or no value at all.
let car = null;
★ Function: A callable object
that can execute a block of
code.
function greet(name) {
return "Hello, "+name+"!"; }
★ Symbol: A unique and
immutable data type often used
as object property keys.
const uniq = Symbol("hey");
★ BigInt: A data type that can
represent arbitrarily large
integers.
const big = 134567890123450;
★ Date: Used to work with
dates and times.
const curDate = new Date();
★ RegExp: Represents regular
expressions for pattern
matching.
const pattern = /ab+c/;
OPERATORS
Operators are symbols that
allow us to perform operations
on variables and values.
Here are some of the most
commonly used operators in
JavaScript along with examples
and explanations:
★ Arithmetic Operators:
+ (Addition)
let sum = 5 + 3; // 8
- (Subtraction)
let difference = 10 - 3; // 7
(Multiplication)
let product = 4 6; // 24
/ (Division)
let quotient = 20 / 5; // 4
% (Modulus)
let remainder = 10 % 3; // 1
★ Assignment Operators:
= (Assignment)
let x = 5;
+=, -=, =, /=, %= (Compound
Assignment): Performs an
operation and assigns.
let y = 10;
y += 2; // y is now 12
★ Comparison Operators:
== (Equality): Compares two
values for equality, but
performs type coercion.
console.log(5 == "5"); // true
(coerced to the same value)
=== (Strict Equality): Compares
two values for equality without
type coercion.
console.log(5 === "5"); // false
(different types)
!= (Inequality): Compares two
values for inequality with type
coercion.
console.log(5 != "5"); // false
(coerced to the same value)
!== (Strict Inequality):
Compares two values for
inequality without type
coercion.
console.log(5 !== "5"); // true
(different types)
★ Logical Operators:
&& (Logical AND): Returns
true if both operands are true.
let isTrue= true && true; //true
|| (Logical OR): Returns true if
at least one operand is true.
let isTrue = true || false; //true
! (Logical NOT): Returns the
opposite boolean value of the
operand.
let isFalse = !true; //false
★ Unary Operators:
++ (Increment): Increases a
variable's value by 1.
let count = 5;
count++; // count is now 6
-- (Decrement): Decreases a
variable's value by 1.
let count = 5;
count--; // count is now 4
EXPRESSIONS
Expressions are combinations
of values, operators, and
variables that can be evaluated
to produce a result.
★ Arithmetic Expressions
let additionResult = 5+3;
let subtractionResult = 10-2;
let multiplicationResult = 46;
let divisionResult = 12/2;
★ String Expressions
let greeting = "Hello, ";
let name = "John";
let message = greeting + name;
★ Comparison Expressions
let isEqual = 5 === 5; // true
let isNotEqual = 5!==10; // true
★ Logical Expressions
let True = true;
let False = false;
let res= True && False; // false
★ Ternary Expressions
let age = 18;
let can =(age>=18)? "Y":"N";
★ Function Call Expressions
function add(x, y) {
return x + y; }
let sum = add(3, 4);
★ Array Expressions
let numbers = [1, 2, 3, 4, 5];
let firstNumber = numbers[0];
★ Object Property Access
Expressions
let person = {
name: "Alice",
age: 30 };
let personName = person.name;
person.age = 31;
★ Template Literals
let item = "apple";
let quantity = 3;
let orderDetails = You ordered
${quantity} ${item}s.;
Some may seem a bit harder to
get. We don’t need to worry as
we are about to explore them
later in this petite book.
CONDITIONAL CONSTRUCTS
Conditional statements like if,
else if, else, and switch are
used in JavaScript to control
the flow of our code based on
certain conditions.
★ if Statement
The if statement is used to
execute a block of code if a
specified condition is true. It
can be followed by an optional
else if and else statement for
more complex conditional
logic.
★ switch Statement
The switch statement is used
when we have multiple
conditions to check against a
single value. It provides an
alternative to a long series of
else if statements.
In this example, the code will
execute the block corresponding
to the value of day. These
conditional statements are
essential for implementing
decision-making logic in our
JavaScript programs. They
allow us to control the
execution of code based on
various conditions, making our
programs more versatile and
responsive.
FUNCTIONS
Functions are reusable blocks
of code that perform a specific
task or set of tasks. They are
fundamental to programming
and allow us to organize and
modularize our code.
★ Defining a Function
We can define a function using
the function keyword followed
by the function's name, a list
of parameters enclosed in
parentheses, and the function
body enclosed in curly braces
{}. Parameters are optional,
and a function can also have no
parameters.
★ Calling a Function
To execute a function and
make it perform its defined
tasks, we call it by using its
name followed by parentheses.
If the function has parameters,
we provide arguments within
the parentheses.
★ Returning Values
Functions can return values
using the return statement. This
allows you to get results or
data from a function.
★ Function Expressions
We can also define functions as
expressions. In this case, we
don't need to provide a
function name (anonymous
function), and we can assign
the function to a variable.
★ Arrow Functions (ES6)
Arrow functions provide a more
concise way to write functions,
especially for simple one-liners.
They use the => syntax.
★Immediately Invoked
Function Expressions (IIFE)
An IIFE is a function that is
defined and executed
immediately after its creation.
The (function() { / code
here / })(); syntax is commonly
used to create an Immediately
Invoked Function Expression
(IIFE) in JavaScript. An IIFE is
a function that is declared and
executed immediately after its
creation. It's often used to
create a private scope for
variables and functions,
preventing them from polluting
the global scope. Here's an
example:
In this example, we've created
an IIFE that encapsulates a
private scope. Inside the IIFE,
we have a counter variable and
twofunctions,incrementCounter
and resetCounter.
These functions can modify and
access the counter variable but
are not accessible from outside
the IIFE. When we run this
code, we'll see that it maintains
its own counter, and the
functions can be used to
manipulate it. However, the
counter variable and the
functions themselves are not
accessible in the global scope,
helping to keep our code clean
and prevent naming conflicts
with other parts of your
program. IIFE is less commonly
used in modern JavaScript
development due to the
introduction of block-scoped
variables with let and const, as
well as modules. However, it's
still a useful technique in
certain situations, especially for
compatibility with older
browsers or for creating
isolated environments.
K UTT Y TA SK : 1 [ A SIM PLE C AL CU LA TO R]
ARRAYS
Arrays are used to store and
manage collections of values,
which can be of any data type.
JavaScript provides several
built-in methods for
manipulating arrays efficiently.
★ Creating Arrays
let fruits = ["apple", "banana"];
★ Accessing Elements
We can access elements in an
array using their index, where
the index starts from 0.
let firstFruit = fruits[0]; //
"apple"
★ Modifying Elements
We can modify elements in an
array by assigning new values
to specific indexes.
fruits[1] = "orange"; // Changes
"banana" to "orange"
★Array Methods
1. push() and pop() : These
methods add and remove
elements from the end of an
array.
2. unshift() and shift() : These
methods add and remove
elements from the beginning of
an array.
OBJECTS
Objects are a fundamental data
type used to store and organize
data. An object is a collection
of key-value pairs, where each
key (also called a property) is
associated with a value. These
properties can be of various
data types, including numbers,
strings, functions, other objects,
and more. Objects in JavaScript
are used to represent real-world
entities, and they are versatile
for organizing and manipulating
data.
★ Creating Objects
We can create an object using
either object literal notation or
the Object constructor.
Object Literal Notation:
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
};
Using Object Constructor:
let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;
★ Accessing Properties
We can access the properties of
an object using dot notation or
square bracket notation.
Dot Notation:
console.log(person.firstName);
console.log(person.age); // 30
Square Bracket Notation:
console.log(person["lastName"]); // "Doe"
★ Modifying Properties
We can modify the values of
object properties by assigning
new values.
person.age = 31;
person["isStudent"] = true;
★ Adding Properties
We can add new properties to
an existing object simply by
assigning values to them.
person.city = "New York";
★ Removing Properties
We can delete properties from
an object using the delete
keyword.
delete person.city;
★ Object Methods
Objects can also have methods,
which are functions associated
with the object. In the
following example, fullName is
a method of the person object
that concatenates the first name
and last name properties.
★ Nested Objects
Objects can contain other
objects as properties, creating a
nested structure.
let address = {
street: "123 Main St",
city: "Cityville"
};
let person = {
firstName: "John",
lastName: "Doe",
address: address
};
console.log(person.address.street
); // "123 Main St"
LOOPING CONSTRUCTS
Loops in JavaScript are used to
repeatedly execute a block of
code until a specified condition
is met. JavaScript provides
several types of loops to cater
to different looping scenarios.
★ for Loop
The for loop is used for
iterating over a range of
values, typically based on a
counter variable.
★ while Loop
The while loop repeatedly
executes a block of code as
long as a specified condition
evaluates to true.
★ do...while Loop
Similar to the while loop, but
it guarantees at least one
execution of the block of code
before checking the condition.
★ for...in Loop
The for...in loop is used to
iterate over the properties of an
object.
★ for...of Loop (ES6):
The for...of loop is used to
iterate over the values of
iterable objects like arrays and
strings.
★ Nested Loops :
We can nest loops inside each
other to handle more complex
looping scenarios.
document.querySelector( selector )
This method selects the first
element that matches a CSS
selector.
document.querySelectorAll (s e le ct or )
This method selects all
elements that match a CSS
selector. It returns a NodeList.
★ Modifying DOM Elements
Once we've selected DOM
elements, we can modify their
content, attributes, and styling.
element.innerHTML : Gets or
sets the HTML content within
an element.
element.textContent : Gets or
sets the text content within an
element (ignores HTML tags).
element.setAttribute(name,val) :
Sets an attribute of an element.
element.style.property : Sets a
CSS property of an element.
element.classList : Allows
adding, removing, and toggling
CSS classes on an element.
★ Event Handling
Events are interactions or
occurrences on a webpage, like
clicks, keypresses, or mouse
movements.
Event handling allows us to
specify what should happen
when an event occurs. The
following example illustrates
attaching an event listener to a
button element :
2 . M o u s e Ov e r E v e n t : m o u s e ov e r
3 . M o u s e Ou t E v e n t : m ou s e o u t
4 . M o u s e Do wn E v e n t : m o u s e d o wn
5 . M o u s e Up E v e n t : m ou s e u p
6 . K e y Do wn E v e n t : k ey d o wn
7 . K e y Up E v e nt : k e y u p
9 . S u b m i t E v e nt ( f o r f o r m s ) : s u b m i t
1 0 . C h a n g e E v en t ( f o r f o r m e l e m e n t s ) : c h a n g e
1 1 . F o c u s Ev en t : f o c u s
1 3 . S c ro l l E v e n t : s c r o l l
1 5 . Un l o ad E v e n t ( w h e n t h e p a ge u n l o ad s ) : u n l o a d
★ Promises
Promises provide a more
structured way to handle
asynchronous operations.
They represent a value that
may not be available yet but
will be resolved at some point,
either successfully with a value
or with an error. Promises have
three states: pending, resolved
(fulfilled), or rejected. They
offer cleaner and more
maintainable code compared to
callbacks.
★ Async/Await
Async/await is a more recent
addition to JavaScript and
provides a way to write
asynchronous code in a
synchronous style.
It's built on top of promises
and simplifies asynchronous
code, making it easier to read
and maintain.
K UTT Y TA SK : 4 [W EA TH ER A PP]