Javascript Manual 2
Javascript Manual 2
md 8/9/2023
Javascript Manual
1. Introduction to Javascript
What is Javascript?
History and evolution of Javascript
Setting up the development environment
2. Javascript Basics
Variables
Constants
Primitive Types
Reference Types
Object
Array
1 / 26
manual.md 8/9/2023
Function
3. Operators
Operators in Javascript
Arithmetic Operators
Assignment Operators
Comparison Operators
Ternary Operators
Logical Operators
Logical Operators with Non-boolean
4. Control Flow
Conditional Statement - if, if-else
Conditional Statement - SWitch-Case
Loops - (for, while, do-while, for-in, for-of)
Break & Continue
1. Introduction to Javascript
What is JavaScript ?
JavaScript is a versatile and widely-used programming language primarily used for creating interactive and
dynamic elements on websites. It plays a pivotal role in front-end web development, enabling developers to
enhance user experiences by adding functionality, handling user interactions.
Role of Javascript in Web Development
2 / 26
manual.md 8/9/2023
3 / 26
manual.md 8/9/2023
2. Javascript Basics
4 / 26
manual.md 8/9/2023
1. Variable
A temporary storage location for data in the computer memory.
A variable can be declared with the let or const keywords. The let keyword declares variable, whose
value can change, while the const is used to declare immutable(cannot change) variables.
let is used to create variable below:
2. Constants
Constants are variables whose value must be initialized and cannot change:
3. Primitive types
5 / 26
manual.md 8/9/2023
4. Reference Types
6 / 26
manual.md 8/9/2023
Object
Objects in javascript is a grouping together of related variables called properties, so they can moved and
used as a single whole.
//separate variables
let firstName = "kemi";
let lastName = "john";
let age = 18;
// as an object
const person = {
firstName: "kemi",
lastName: "john",
age: 18,
};
console.log(person);
console.log(typeof person);
Dot Notation
You can use to access and set the values of those properties:
console.log(person.firstName);
console.log(person.lastName);
Bracket Notation
You can also use the bracket notation. This is particularly usedful when the particular property will be
determined by what a user selected:
console.log(person["firstName"]);
console.log(person["lastName"]);
6. Arrays
Whenever you are dealing with a list of items. It could be a list of object in a shopping cart, or a list of
colors, you should always think about an array.
creating an array
A array is created with the square bracket []
// An array
const colors = ["blue", "green"];
// Items in an array are indexed
// Add an item to index 2
colors[2] = "purple";
// the type of items in array is dynamic
colors[3] = 12;
7. Function
8 / 26
manual.md 8/9/2023
What is a function?
A function is a reusable block of codes, which is called by name to that performs a specific task or a set of
tasks. It allows you to encapsulate logic, group related actions, and make your code more organized and
modular.
. Function Declaration: You can define a function using the function keyword followed by the
function name, a list of parameters enclosed in parentheses, and a block of code enclosed in curly
braces.
function greet(name) {
console.log(`Hello, ${name}!`);
}
. Function Expression: Another way to define functions is through function expressions. In this case,
you assign the function to a variable. This is useful for creating anonymous functions (functions
without names) or passing functions as arguments to other functions.
. Arrow Functions (ES6+): Arrow functions provide a more concise syntax for creating functions,
especially when the function body is a single expression. They have a simpler structure and lexically
bind the value of this.
. Parameters and Arguments: Parameters are placeholders in the function's declaration, while
arguments are the actual values passed when calling the function.
function greet(name) {
console.log(`Hello, ${name}!`);
}
. Return Statement: Functions can return a value using the return statement. When the function is
called, the expression following return is evaluated, and the result is returned to the caller.
function add(x, y) {
return x + y;
9 / 26
manual.md 8/9/2023
3. Operators
1. Operators in Javascript
Operators are used with variables to create expressions in your javascript codes.
2. Arithmetic Operators
In JavaScript, arithmetic operators are used to perform mathematical operations on numerical values. Here
are the main arithmetic operators in JavaScript:
. Addition (+): Adds two operands together. Example: let sum = 5 + 3; // sum will be 8
. Subtraction (-): Subtracts the right operand from the left operand. Example: let difference =
10 - 4; // difference will be 6
. Multiplication (_): Multiplies two operands. Example: let product = 3 _ 7; // product will
be 21
. Division (/): Divides the left operand by the right operand. Example: let quotient = 15 / 3; //
quotient will be 5
. Modulus (%): Returns the remainder of the division of the left operand by the right operand. Example:
let remainder = 17 % 4; // remainder will be 1
. Exponentiation (**): Raises the left operand to the power of the right operand. Example: let result
= 2 ** 3; // result will be 8
. Increment (++) and Decrement (--): This is a little tricky, because the position of these operator will
slightly affect the output.
Increment before(++number) increases the value of a variable 'first' by 1, then returns the new
value. Example: let x = 5; ++x; // returns 6. In contrast, let x = 5; x++; //
returns 5 first, then increases x to 6.
Decrement operator behaves exactly like above. Example: let y = 10; y--; // returns
10 first, then decreses the value by 1
. Parentheses(): The BODMAS rule also applies in arithmetic operators. The bracket, also called
parenthesis, can be used to control the flow of operation.
10 / 26
manual.md 8/9/2023
3. Assignment Operators
In JavaScript, assignment operators are used to assign values to variables. They allow you to update the
value of a variable by performing an operation on the existing value and a new value. Here are the main
assignment operators in JavaScript:
. Assignment (=): You have seen this already since we started working with variables. This assigns the
value on the right to the variable on the left. Example: let x = 10; // x is assigned the
value 10
. Addition Assignment (+=): Adds the value on the right to the existing value of the variable on the left
and assigns the result back to the variable on the left. Example: let y = 5; y += 3; // y is
now 8
. Subtraction Assignment (-=): Subtracts the value on the right from the existing value of the variable
on the left and assigns the result back to the variable on the left. Example: let z = 15; z -= 7;
// z is now 8
. Multiplication Assignment (_=): Multiplies the existing value of the variable on the left by the value on
the right and assigns the result back to the variable on the left. Example: let a = 3; a _= 4; //
a is now 12
. Division Assignment (/=): Divides the existing value of the variable on the left by the value on the right
and assigns the result back to the variable on the left. Example: let b = 20; b /= 5; // b is
now 4
. Modulus Assignment (%=): Performs the modulus operation between the existing value of the
variable on the left and the value on the right, then assigns the result back to the variable on the left.
Example: let c = 17; c %= 5; // c is now 2
. Exponentiation Assignment (**=): Raises the existing value of the variable on the left to the power of
the value on the right and assigns the result back to the variable on the left. Example: let d = 2;
d **= 3; // d is now 8
These assignment operators provide a shorthand way to update variables based on their existing values
and the value on the right side of the operator.
4. Comparison Operators
In JavaScript, comparison operators are used to compare values and determine their relationship. They
return a Boolean value (true or false) based on whether the comparison is true or false. Here are the
main comparison operators in JavaScript:
. Equal (==): Checks if two values are equal, performing type coercion if necessary. Example: let x =
5; let y = "5"; console.log(x == y); // true. Javascript performed a type coercion
here by converting y, which is a string, into a number and then perform the comparison.
. Not Equal (!=): Checks if two values are not equal, performing type coercion if necessary. Example:
let a = 10; let b = "10"; console.log(a != b); // false
11 / 26
manual.md 8/9/2023
. Strict Equal (===): Checks if two values are equal without performing type coercion (strict equality).
This means both operands must be of the same type. Example: let p = 15; let q = "15";
console.log(p === q); // false
. Strict Not Equal (!==): Checks if two values are not equal without performing type coercion (strict
inequality). Example: let m = 20; let n = "20"; console.log(m !== n); // true
. Greater Than (>): Checks if the value on the left is greater than the value on the right. Example:
console.log(8 > 5); // true
. Less Than (<): Checks if the value on the left is less than the value on the right. Example:
console.log(3 < 7); // true
. Greater Than or Equal To (>=): Checks if the value on the left is greater than or equal to the value on
the right. Example: console.log(10 >= 10); // true
. Less Than or Equal To (<=): Checks if the value on the left is less than or equal to the value on the
right. Example: console.log(5 <= 7); // true
Comparison operators are commonly used in conditional statements and loops to make decisions based on
the relationships between values. It's important to understand the difference between regular equality (==)
and strict equality (===) to avoid unexpected behavior when comparing values of different types. It is
recommended that you ALWAYS use the strict equality EVERY TIME.
5. Ternary Operators
Ternary operator is a shorthand way of writing a conditional (if-else) statement, though we have not looked
at the conditional statements yet. It allows you to evaluate a condition and return one of two values based
on whether the condition is true or false. The syntax of the ternary operator is as follows:
// Syntax
12 / 26
manual.md 8/9/2023
In this example, the ternary operator is used to determine whether the age is considered an adult (18 years
or older) and assigns the appropriate string value to the isAdult variable.
Here, the ternary operator is used to assign a value to the weather variable based on whether the
temperature is considered "Hot" (greater than 30) or "Moderate" (30 or lower).
6. Logical Operators
The logical operators are used to combine multiple conditions or negating a condition. There are three main
logical operators in JavaScript:
. Logical AND (&&): Returns true if both operands are true, otherwise, it returns false. Example:
let result = (5 > 3) && (10 < 20); // result will be true
. Logical OR (||): Returns true if at least one of the operands is true; and returns false if both
operands are false. Example: let result = (5 > 10) || (8 < 15); // result will be
true
. Logical NOT (!): Negates the Boolean value of its operand. If the operand is true, it returns false,
and if the operand is false, it returns true. Example: let result = !(3 > 5); // result
will be true
let result =
age >= 18 && hasDriverLicense
? "You are eligible to drive."
: "You are not eligible to drive.";
console.log(result);
13 / 26
manual.md 8/9/2023
Logical operators play a crucial role in controlling the flow of your JavaScript code based on various
conditions and combinations of values.
14 / 26
manual.md 8/9/2023
// Logical OR (||)
let result3 = 0 || "JavaScript";
console.log(result3); // Output: "JavaScript" (first operand is falsy,
returns the first truthy value)
It's important to understand how logical operators handle truthy and falsy values when working with non-
Boolean values, as this behavior can be leveraged to write concise and expressive code in JavaScript.
4. Control Flow
Conditional Statements (If-else, switch-case)
1. if-else
Conditional statements are used to make decisions in your code based on certain conditions. These
statements allow you to control the flow of execution by executing different blocks of code depending on
whether a specified condition is true or false. Here are the main conditional statements in JavaScript:
. If Statement: The if statement allows you to execute a block of code only if a specified condition is
true.
if (condition) {
// Code to execute if the condition is true.
}
15 / 26
manual.md 8/9/2023
. If-Else Statement: The if-else statement allows you to execute one block of code if a condition is
true and another block of code if the condition is false.
if (condition) {
// Code to execute if the condition is true.
} else {
// Code to execute if the condition is false.
}
. If-Else-If Statement: The if-else-if statement allows you to test multiple conditions and execute
different blocks of code based on the first true condition.
if (condition1) {
// Code to execute if condition1 is true.
} else if (condition2) {
// Code to execute if condition2 is true.
} else {
// Code to execute if none of the conditions are true.
}
16 / 26
manual.md 8/9/2023
2. switch-case
The switch statement is used to evaluate an expression against multiple possible case values and execute
the code block associated with the first matching case.
//Syntax
switch (variable) {
case value1 | expression:
// Code to execute if expression matches value1.
break;
case value2 | expression:
// Code to execute if expression matches value2.
break;
default:
// Code to execute if no cases match.
}
NB: Note that a break statement must added after each cases body, except the default. Else, the body of
the next case will also be executed.
1. Using Numbers as Cases:
let dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
console.log("Sunday");
break;
case 2:
console.log("Monday");
break;
case 3:
console.log("Tuesday");
break;
default:
console.log("Other day");
}
17 / 26
manual.md 8/9/2023
switch (isWeekend) {
case true:
console.log("Enjoy your weekend!");
break;
case false:
console.log("Back to work.");
break;
}
switch (true) {
case score >= 90:
console.log("Excellent!");
break;
case score >= 70:
console.log("Good job!");
break;
case score >= 50:
console.log("You passed.");
break;
default:
console.log("You need to improve.");
}
Recommendation: switch-case statement is not bad, but use the if-else in professional projects as
more developers only use the if-else statement.
Classwork
Convert all the switch case samples above to if-else.
// Syntax
for (initialization; condition; iteration) {
// Code to be executed in each iteration
}
Initialization: This part is executed only once before the loop starts and is used to initialize loop
variables.
Condition: The loop continues executing as long as this condition is true.
Iteration: This part is executed at the end of each iteration and is used to update loop variables.
Here are some code examples demonstrating the use of for loops:
. Iterating Over an Array:
. Iterating Backward:
. Nested Loops:
The for loop is a versatile construct that can be used in various scenarios to perform repeated tasks.
Whether you're iterating over arrays, generating sequences, or implementing complex patterns, the for
loop is an essential tool in JavaScript programming.
While loop
A while loop is a control flow statement in JavaScript that repeatedly executes a block of code as long as a
specified condition remains true. It's useful when you need to perform a task multiple times without
knowing the exact number of iterations in advance. The while loop continues execution until the condition
evaluates to false.
Here's the general syntax of a while loop:
while (condition) {
// Code to be executed as long as the condition is true
}
The loop will repeatedly execute the code block within the curly braces as long as the specified condition is
true.
Here are some code examples illustrating the use of while loops:
. Counting Up:
20 / 26
manual.md 8/9/2023
let count = 1;
. Countdown:
let countdown = 5;
. Sum of Numbers:
5. Do-While statement
The do-while loop is similar to a while loop, with one key difference: the do-while loop executes the
code block at least once before checking the loop condition. This ensures that the code block is executed
at least once, regardless of whether the condition is initially true or false. After the first iteration, the loop
condition is checked, and the loop continues executing as long as the condition remains true.
Here's the general syntax of a do-while loop:
do {
// Code to be executed at least once
} while (condition);
21 / 26
manual.md 8/9/2023
The loop will first execute the code block within the curly braces, and then it will check the specified
condition. If the condition is true, the loop continues executing; if it's false, the loop terminates.
Here are some code examples illustrating the use of do-while loops:
. Sample:
let counter = 1;
do {
console.log(counter);
} while (counter <= 10);
. Menu Selection:
let choice;
do {
console.log("1. Play Game");
console.log("2. Quit");
choice = prompt("Enter your choice:");
. Sum of Numbers:
do {
sum += numbers[index];
index++;
} while (index < numbers.length);
The do-while loop is particularly useful when you need to ensure that a certain piece of code is executed
at least once, regardless of the initial condition. Just like with other loops, be cautious to avoid infinite loops
by ensuring that the loop condition eventually evaluates to false.
22 / 26
manual.md 8/9/2023
6. For-in Loop
The for-in loop is used to iterate over the properties of an object. It allows you to access and perform
operations on each enumerable property of an object, one at a time. This loop is especially useful for
working with objects and their key-value pairs.
Here's the general syntax of a for-in loop:
variable : A variable that represents the current property key in each iteration.
object: The object whose enumerable properties are being iterated over.
Here are some code examples demonstrating the use of for-in loops:
. Iterating Over Object Properties:
let person = {
name: "Alice",
age: 30,
occupation: "Engineer",
};
The for-in loop is a valuable tool for iterating through object properties. However, when working with
arrays, it's recommended to use the for-of loop or other array iteration methods to avoid unintended.
for-of ia discussed next.
7. For-of Loop
The for-of loop is a modern control flow statement in JavaScript that is used to iterate over the values of
iterable objects, such as arrays, strings, maps, sets, and more. It provides a simpler and cleaner way to loop
through elements without dealing with the index or properties. The for-of loop is especially useful when
you want to focus on the values themselves rather than the underlying structure.
Here's the general syntax of a for-of loop:
23 / 26
manual.md 8/9/2023
Here are some code examples demonstrating the use of for-of loops:
. Iterating Over an Array:
. Though for-of is not really meant to iterating an object's property, we still achieve that by
combining it with Object class (with Object.values() or Object.heys()):
let person = {
name: "Alice",
age: 30,
occupation: "Engineer",
};
1. break Statement: The break statement is used to immediately exit a loop, regardless of whether the
loop condition is still satisfied. It is commonly used when a specific condition is met, and you want to stop
further iterations of the loop.
Syntax:
Example:
2. continue Statement: The continue statement is used to skip the current iteration of a loop and move
to the next iteration. It is often used when you want to skip certain iterations based on a condition but
continue with the rest of the loop.
Syntax:
Example:
Both the break and continue statements can be used in for, while, and do-while loops. They provide
ways to fine-tune the behavior of loops based on specific conditions, making your code more flexible and
efficient.
26 / 26