JavaScript Fundamental Guide To Learning JavaScript
JavaScript Fundamental Guide To Learning JavaScript
Fundamentals
A Comprehensive
Introduction
History of JavaScript 7
Chapter 1 Introduction to JavaScript 9
Introduction to Programming Languages 11
Understanding the Spectrum: 11
Types of Programming Languages: 12
JavaScript's Unique Features: 13
Role in Web Development 14
Empowering Interactivity: 14
Enhancing User Experience: 15
Seamless Integration with HTML and CSS: 15
Client-Side vs. Server-Side: 15
Setting Up Your Development Environment 16
Choosing a Text Editor 16
Understanding Text Editors: 17
Considerations When Choosing a Text Editor: 17
Visual Studio Code: An Industry-Standard Choice: 18
Getting Started with Visual Studio Code: 19
First Steps with JavaScript 19
Basic Syntax: 20
Statements and Semicolons: 20
Whitespace: 21
Variables and Data Types: 21
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
1
typeof operator 21
Number: 22
String: 22
Boolean: 22
Undefined: 22
Null: 22
Object: 23
Array: 23
Function: 23
Symbol: 23
BigInt: 24
Typeof with Expressions: 24
Variable Declaration: 24
Data Types: 25
Operators and Expressions: 26
Arithmetic Operators: 26
Addition +: 27
Subtraction -: 27
Multiplication *: 27
Division /: 27
Modulus % (Remainder): 27
Increment ++: 27
Decrement --: 28
Exponentiation **: 28
Assignment with Addition +=: 28
Assignment with Multiplication *=: 28
Comparison Operators: 29
Loose Equality (==): 29
Strict Equality (===): 30
Coding Best Practices: 31
Coding example exponentiation operator 33
console.log: 34
alert: 35
Introduction to a function: 35
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
2
Test your Knowledge Quiz 1 36
Introduction to JavaScript (7 Questions): 36
First Steps with JavaScript (13 Questions): 39
Chapter 2 Control Flow in JavaScript 43
Conditional Statements: 45
if statement: 45
Coding Exercise Sign of a Number 46
if-else statement: 47
if-else if-else statement: 48
Switch Statement: 49
Coding Exercise : Day of the Week 51
Loops: 53
for Loop: 53
while Loop: 54
do-while Loop: 55
Break and Continue: 56
Coding exercise Multiplication Table 56
Test Your Knowledge Chapter 2 Quiz 58
Chapter 3 Functions in JavaScript 63
Introduction to Functions in JavaScript 65
Function Declaration: 65
Coding Exercise Area of Rectangle 66
Function Parameters: 67
Coding Exercise Triangle Area 68
Coding Exercise Even and Odd 69
Function Invocation: 70
Return Statement: 71
Coding Exercise Factorial of a Number 72
Conditional Statements in Functions: 73
JavaScript Scope and Closures 74
Scope in JavaScript Functions: 74
Example of Function Scope: 75
Coding Exercise Understanding Scope 75
Closures in JavaScript Functions: 78
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
3
Example of Closure: 78
Scope Chain: 79
Example of Scope Chain: 79
Coding Exercise Closure Counter 80
Test Your Knowledge Chapter 3 82
Introduction to Functions in JavaScript: 82
Function Invocation: 84
Return Statement: 85
Conditional Statements in Functions: 85
JavaScript Scope and Closures: 86
Chapter 4 Working with Data Structures 87
Working with Data Structures 88
Arrays: 89
Coding Exercise Arrays 8 Tasks 90
JavaScript Array Methods 92
push() 92
pop() 92
shift() 92
unshift() 93
concat() 93
slice() 93
splice() 94
indexOf() 94
forEach() 94
map() 95
Coding Exercise Array Methods 95
Objects: 97
Object Properties and Methods 98
Object Properties: 98
Using Dot Notation: 99
Using Square Bracket Notation: 99
Object Methods: 100
Coding Exercise Object Person 102
Sets: 104
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
4
Maps: 105
Custom Data Structures: 106
Javascript Object-oriented 108
Objects and Classes: 108
Creating Objects: 109
Properties and Methods: 109
Prototypes: 110
Inheritance: 110
Encapsulation: 111
Coding Exercise Object Car 113
Test your Knowledge Chapter 4 117
Arrays: 117
JavaScript Array Methods: 118
Objects: 119
Sets: 120
Maps: 121
Custom Data Structures: 121
Objects and Classes: 122
Prototypes: 123
Encapsulation: 123
Chapter 5 Mastering Strings and Advanced String Methods 124
Line Breaks in Strings 126
Template Literals: 126
Benefits of Template Literals: 127
Escaping Backticks: 127
Advanced String Methods 128
length: 128
charAt(index): 128
concat(str1, str2, ...): 128
toLowerCase() Method: 129
toUpperCase() Method: 129
Using These Methods with Variables: 130
Use Cases: 130
toUpperCase(): 131
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
5
toLowerCase(): 131
slice(startIndex, endIndex): 132
indexOf(searchStr, startIndex): 132
replace(searchStr, replaceStr): 132
split(separator): 132
trim(): 133
JavaScript Substring 133
Example of substring(): 133
Coding Exercise Substrings 134
Additional Considerations: 135
indexOf() method in JavaScript 136
Checking for the Existence of a Substring: 136
Using startIndex: 137
Case-Sensitive Search: 137
Multiple Occurrences: 138
How to Empty an Array 139
Coding Exercise Array Empty: 139
What is NaN 140
Examples of NaN: 141
Undefined Mathematical Operation: 141
Failed Conversion: 141
Invalid Number Operation: 141
Checking for NaN: 141
Special Behavior of NaN: 142
Handling NaN: 142
Type conversion JavaScript Number and String 143
Convert String to Number: 143
Using parseInt(): 143
Using parseFloat(): 143
Convert Number to String: 144
Using toString() Method: 144
Handling Radix in parseInt(): 144
Summary: 145
Math object JavaScript 145
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
6
Math Constants: 145
Math.PI 145
Basic Mathematical Operations: 146
Math.abs(x) 146
Math.round(x) 146
Math.floor(x) 146
Math.ceil(x) 146
Math.random() 147
Exponents and Logarithms: 147
Math.pow(x, y) 147
Math.sqrt(x) 147
Math.log(x) 147
JavaScript Hoisting 148
Variable Hoisting: 148
Function Hoisting: 149
Hoisting with Function Expressions: 149
Considerations and Best Practices: 149
Test your knowledge on chapter 5 150
Line Breaks in Strings and Template Literals: 150
Advanced String Methods: 151
JavaScript Substring: 153
NaN and Type Conversion: 154
Math object JavaScript: 156
Chapter 6 Test your JavaScript Knowledge 157
Overview of JavaScript 157
Setting Up Your Development Environment 158
First Steps with JavaScript 159
History of JavaScript
JavaScript, conceived in the mid-1990s, has undergone a transformative evolution,
establishing itself as a fundamental and versatile programming language integral
to modern web development. Originating at Netscape Communications
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
7
Corporation in 1995, Brendan Eich's task was to create a lightweight scripting
language for enhancing client-side web development. Initially named "Mocha"
and later "LiveScript," it eventually settled on JavaScript with the goal of adding
interactivity to static HTML pages. Netscape's collaboration with Sun
Microsystems in 1996 ensured compatibility with Java, leading to the creation of
the JavaScript standard and its inclusion in the Netscape Navigator 2.0 browser.
Subsequently, ECMAScript standardization in 1997, managed by the European
Computer Manufacturers Association (ECMA), solidified JavaScript's open
standard status.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
8
Chapter 1 Introduction to JavaScript
Welcome to Chapter 1, where we embark on a journey into the fascinating world
of JavaScript—a dynamic and versatile programming language that has become a
cornerstone in modern web development. This chapter serves as your gateway to
understanding the foundational concepts of JavaScript, from its basic syntax and
unique features to its pivotal role in enhancing interactivity and user experience
on the web. As we delve into the intricacies of programming languages, we will
explore the diverse spectrum of language types and, more specifically, the
distinctive features that set JavaScript apart. Gain insights into the types of
programming languages and how JavaScript seamlessly integrates with HTML and
CSS, empowering developers to craft interactive and visually engaging web
applications.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
9
● Choosing a Text Editor: Understanding and Considerations
● Visual Studio Code: An Industry-Standard Choice
● Getting Started with Visual Studio Code
● First Steps with JavaScript: Basic Syntax and Statements
● Whitespace and Semicolons
● Variables and Data Types: Number, String, Boolean, Undefined, Null, Object,
Array, Function, Symbol, BigInt
● Typeof Operator and Expressions
● Variable Declaration and Data Types
● Operators and Expressions
● Arithmetic Operators: Addition, Subtraction, Multiplication, Division,
Modulus, Increment, Decrement, Exponentiation
● Assignment Operators: Addition and Multiplication
● Comparison Operators
● Loose Equality (==) and Strict Equality (===)
● Coding Best Practices
● Coding Example: Exponentiation Operator
● Working with console.log and alert Functions
● Dive into this comprehensive chapter to lay the foundation for your
JavaScript journey, equipping yourself with the essential knowledge to
navigate the language's syntax, data types, and best practices. Whether you
are a novice explorer or a seasoned developer, this chapter provides
valuable insights and hands-on examples to enhance your proficiency in
JavaScript.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
10
Welcome to the world of web development, where JavaScript plays a pivotal role
in shaping interactive and dynamic websites. In this introductory chapter, we'll
explore the origins and evolution of JavaScript, its role in modern web
development, and the fundamental concepts that make it a versatile and essential
programming language.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
11
Types of Programming Languages:
Procedural Languages:
● Examples: C, Pascal
development.
Object-Oriented Languages:
● Examples: Java, C++
Functional Languages:
● Examples: Haskell, Lisp
arguments.
Scripting Languages:
● Examples: Python, JavaScript
analysis.
Markup Languages:
● Examples: HTML, XML
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
12
● Define the structure and presentation of documents.
representation.
Now, let's shine a spotlight on JavaScript and explore what makes it stand out:
● Versatility: JavaScript is a multi-paradigm language, supporting both
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
13
features, and practical applications, empowering you to become a proficient
JavaScript developer.
Empowering Interactivity:
JavaScript is the backbone of interactivity on the web. Unlike HTML and CSS,
which primarily handle the structure and presentation of a webpage, JavaScript is
responsible for making web pages dynamic and responsive to user actions.
Through event-driven programming, JavaScript can respond to user interactions
such as clicks, form submissions, and keyboard inputs, enabling the creation of
interactive and user-friendly interfaces.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
14
Enhancing User Experience:
The user experience (UX) is a critical aspect of web development, and JavaScript is
a key player in enhancing it. With JavaScript, developers can implement features
like sliders, carousels, accordions, and modals, providing users with a more
engaging and enjoyable browsing experience. Asynchronous operations,
facilitated by JavaScript's event loop, enable seamless updates to page content
without requiring a full page reload, contributing to a smoother and faster user
experience.
JavaScript works hand-in-hand with HTML and CSS to create cohesive and visually
appealing web applications. While HTML defines the structure of a webpage and
CSS styles its presentation, JavaScript adds behavior and functionality. Through
the Document Object Model (DOM), JavaScript can dynamically manipulate HTML
elements, update styles, and create a fluid connection between the structure and
behavior of a webpage.
JavaScript is unique in its ability to run on the client side, directly in the user's
browser. This allows for real-time interactions and reduces the need for constant
server requests, resulting in a more responsive application. Frameworks like React,
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
15
Angular, and Vue.js leverage JavaScript to build powerful client-side applications,
further exemplifying its significance in contemporary web development.
● Form Validation: JavaScript ensures that user inputs in forms meet specified
criteria, providing instant feedback and preventing erroneous submissions.
● AJAX Requests: JavaScript enables the asynchronous retrieval of data from
servers, allowing for dynamic content updates without requiring a full page
reload.
● User Interface Animation: With JavaScript, developers can create smooth
animations and transitions, contributing to a visually appealing user
interface.
By understanding JavaScript's pivotal role in web development, you gain insight
into its transformative power in creating interactive, user-centric, and visually
stunning web applications. As we progress through this journey, you'll discover
how to harness the full potential of JavaScript to build dynamic and compelling
online experiences.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
16
Selecting the right text editor is a pivotal decision for any developer, as it serves as
the primary interface for writing, editing, and managing code. A text editor is
essentially a tool that empowers you to interact with your source code efficiently.
In this section, we'll navigate through the various choices of text editors and
highlight why settling on an industry-standard tool like Visual Studio Code can
significantly enhance your coding experience.
Text editors come in various forms, ranging from simple and lightweight to
feature-rich integrated development environments (IDEs). The fundamental
purpose of a text editor is to provide a platform for writing and editing code files
in different programming languages.
● Ease of Use: Look for a text editor that has an intuitive interface, allowing
you to focus on your code without being overwhelmed by unnecessary
features.
● Extensibility: An extensible text editor allows you to enhance its
functionality through plugins or extensions. This is particularly valuable as it
enables customization based on your specific needs and preferences.
● Syntax Highlighting: Syntax highlighting makes code more readable by using
different colors for different elements (keywords, strings, comments, etc.).
It helps catch errors and understand the code structure more easily.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
17
● Autocomplete and IntelliSense: A good text editor should provide
autocomplete suggestions and intelligent code completion, saving you time
and reducing the chances of typos.
● Version Control Integration: Integration with version control systems, such
as Git, is crucial for managing and tracking changes in your codebase.
● Multi-Language Support: Ensure that the text editor supports the
programming languages you are working with. This is especially important if
you work on projects that involve a variety of languages.
Visual Studio Code (VS Code) has emerged as a popular and widely adopted text
editor in the developer community. Here's why it's a solid choice:
● Free and Open Source: VS Code is free to download and use, making it
accessible to developers of all levels.
● Rich Extension Ecosystem: VS Code boasts a vast library of extensions that
cater to different languages, frameworks, and tools. This extensibility allows
you to tailor the editor to your specific needs.
● Integrated Terminal: The integrated terminal within VS Code streamlines the
development workflow by allowing you to execute commands without
switching to a separate terminal window.
● Built-in Git Integration: Git is an integral part of many development
workflows, and VS Code seamlessly integrates with Git, providing features
for version control and collaboration.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
18
● Cross-Platform Compatibility: VS Code runs on Windows, macOS, and Linux,
ensuring a consistent experience across different operating systems.
1. Installation: Download and install Visual Studio Code from the official
website. https://code.visualstudio.com/
2. Extensions: Explore and install extensions from the VS Code Marketplace to
preferences.
4. Learning Resources: Take advantage of the rich documentation and
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
19
with operators and expressions, and utilizing the essential console.log and alert
functions.
Basic Syntax:
JavaScript syntax forms the foundation of writing code in this language.
Understanding the basics is crucial for crafting clear and functional programs.
// Single-line comment
/* Multi-line
comment */
// Logging to console
console.log("Hello, " + firstName + " " + lastName);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
20
Use comments (// for single-line comments, /* */ for multi-line comments) to
annotate your code. Comments are ignored by the JavaScript interpreter and are
useful for explaining your code to others or to yourself in the future.
Whitespace:
JavaScript is lenient when it comes to white spaces, but proper indentation
enhances code readability. Consistent indentation is a good practice for
maintaining clean and organized code.
typeof operator
The typeof operator in JavaScript is used to determine the type of a variable or an
expression. It returns a string that represents the data type of the operand. The
basic syntax is typeof operand.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
21
Usage and Examples:
Number:
let num = 42;
console.log(typeof num); // Output: "number"
String:
let text = "Hello, World!";
console.log(typeof text); // Output: "string"
Boolean:
let isTrue = true;
console.log(typeof isTrue); // Output: "boolean"
Undefined:
let undefinedVariable;
console.log(typeof undefinedVariable); // Output:
"undefined"
Null:
let nullValue = null;
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
22
console.log(typeof nullValue); // Output: "object"
(Note: typeof null is a known quirk, it returns
"object")
Object:
let person = { name: "John", age: 30 };
console.log(typeof person); // Output: "object"
Array:
let numbers = [1, 2, 3];
console.log(typeof numbers); // Output: "object"
Function:
function greet() {
console.log("Hello!");
}
console.log(typeof greet); // Output: "function"
Symbol:
let symbolValue = Symbol("unique");
console.log(typeof symbolValue); // Output: "symbol"
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
23
BigInt:
let bigInteger = 123n;
console.log(typeof bigInteger); // Output: "bigint"
Note:
The typeof operator returns a string representing the data type.
It's important to note that typeof null returns "object," which is a historical quirk
in JavaScript.
typeof can be used with variables, literals, or expressions.
Using typeof is useful in scenarios where you want to dynamically check the type
of a variable or ensure that a variable is of a specific type before performing
certain operations.
Variable Declaration:
Use the var, let, or const keyword to declare variables. The choice between them
depends on the scope and mutability of the variable.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
24
Data Types:
JavaScript has several primitive data types, including strings, numbers, booleans,
null, and undefined. Additionally, it has more complex types like objects and
arrays.
// Variable declaration
let age = 25;
const pi = 3.14;
// Strings
let greeting = "Hello";
let message = greeting + ", " + firstName;
// Booleans
let isAdult = age >= 18;
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
25
// Arrays
let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits[0];
// Objects
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
isStudent: false
};
Arithmetic Operators:
Addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) are
common arithmetic operators.
Here are some coding examples of arithmetic operators in JavaScript:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
26
Addition +:
let sum = 5 + 3;
console.log(`Sum: ${sum}`); // Output: 8
Subtraction -:
let difference = 10 - 4;
console.log(`Difference: ${difference}`); // Output: 6
Multiplication *:
let product = 6 * 7;
console.log(`Product: ${product}`); // Output: 42
Division /:
let quotient = 20 / 4;
console.log(`Quotient: ${quotient}`); // Output: 5
Modulus % (Remainder):
let remainder = 15 % 7;
console.log(`Remainder: ${remainder}`); // Output: 1
Increment ++:
let number = 5;
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
27
number++;
console.log(`Incremented: ${number}`); // Output: 6
Decrement --:
let anotherNumber = 8;
anotherNumber--;
console.log(`Decremented: ${anotherNumber}`); //
Output: 7
Exponentiation **:
let base = 2;
let exponent = 3;
let result = base ** exponent;
console.log(`Exponentiation Result: ${result}`); //
Output: 8
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
28
productValue *= 4;
console.log(`Updated Product Value: ${productValue}`);
// Output: 12
Comparison Operators:
Compare values using operators such as equality (==, ===), inequality (!=, !==),
greater than (>), less than (<), etc.
In JavaScript, == (loose equality) and === (strict equality) are two comparison
operators used to compare values. Understanding the difference between them is
crucial for writing robust and bug-free code.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
29
If the operands are of different types, JavaScript will try to convert them to a
common type before making the comparison.
For equality, it checks if the values are equal after type coercion.
Example:
let numValue = 5;
let stringValue = "5";
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
30
console.log(numValue === stringValue); // false (strict
equality, no type coercion)
In this example, the strict equality operator checks that the values are not only
equal but also of the same type, so the result is false.
let numValue = 5;
let stringValue = "5";
Explicitly converting the string to a number before using strict equality ensures the
desired comparison result.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
31
In summary, while both == and === are used for equality comparisons in
JavaScript, it's generally recommended to use === for strict equality to prevent
unexpected type coercion and ensure more reliable code.
Coding Examples
// Arithmetic Operators
let num1 = 10;
let num2 = 5;
// Comparison Operators
let isEqual = num1 === num2;
let isGreaterThan = num1 > num2;
let isNotEqual = num1 !== num2;
console.log and alert Functions:
// Logging to console
console.log("Sum:", sum);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
32
console.log("Is John an adult?", isAdult);
// Displaying an alert
alert("Welcome to our website, " + firstName + "!");
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
33
let decimalExponent = 0.5;
let decimalResult = decimalBase ** decimalExponent;
These functions are essential for interacting with and debugging JavaScript code.
console.log:
Outputs information to the browser console. Useful for debugging and logging
variable values.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
34
alert:
Displays a pop-up dialog with a message. Useful for simple user interactions and
debugging.
// Example of console.log and alert Functions
console.log("This is a log message"); // log to console
alert("Hello, User!"); // display an alert
Introduction to a function:
Functions in JavaScript allow you to encapsulate code into reusable blocks, making
your programs more organized and easier to understand.We will provide more in
depth on functions coming up in chapter 3. Below is an example of a function in
JavaScript.
// Function Declaration
function greet(name) {
// The function body
console.log("Hello, " + name + "!");
}
// Function Call
greet("John");
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
35
// Output: Hello, John!
In this example, we've created a simple function named greet that takes a
parameter name. Inside the function body, it uses console.log to print a greeting
message to the console. The function is then called with the argument "John,"
resulting in the output "Hello, John!".
Functions in JavaScript are reusable blocks of code that can be defined and
invoked as needed. They help in organizing code, promoting reusability, and
making the code more modular. In this case, the function greet is a basic
illustration of a function that performs a specific task - greeting a person by their
name.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
36
A) Database Management
B) Styling Web Pages
C) Enhancing Interactivity
D) Server Configuration
Answer: C) Enhancing Interactivity
JavaScript is known for its seamless integration with which of the following?
A) XML
B) Python
C) HTML and CSS
D) Java
Answer: C) HTML and CSS
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
37
C) Database operations
D) Backend processing
Answer: B) Code executed on the user's device
Which of the following is a common text editor used for JavaScript development?
A) Photoshop
B) Visual Studio Code
C) Microsoft Word
D) Eclipse
Answer: B) Visual Studio Code
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
38
Answer: D) Ease of use and features
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
39
What is the role of the undefined data type in JavaScript?
A) Represents a missing value
B) Indicates an error
C) Denotes an unused variable
D) Represents infinity
Answer: A) Represents a missing value
A) ^
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
40
B) **
C) //
D) %
Answer: B) ** (Double Asterisk)
What does the strict equality operator (===) check for in JavaScript?
A) Value equality
B) Type equality
C) Both value and type equality
D) Inequality
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
41
Answer: C) Both value and type equality
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
42
Chapter 2 Control Flow in JavaScript
Embark on a journey through the intricacies of control flow in JavaScript as we
navigate the paths of decision-making and iteration. In this chapter, we unravel
the fundamental concepts that govern the execution flow of JavaScript code,
empowering you to craft dynamic and responsive applications. Explore the
nuances of conditional statements, dive into the versatility of loops, and sharpen
your coding skills through hands-on exercises. Here are the key topics awaiting
your exploration:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
43
● Coding Exercise: Day of the Week: Put your skills to the test with a coding
exercise focused on determining the day of the week.
● Loops: Delve into the world of iteration and repetition with loops.
● for Loop: Master the for loop for executing a block of code a specified
number of times.
● while Loop: Learn the while loop for creating flexible and conditional loops.
● do-while Loop: Explore the do-while loop, ensuring the execution of the
loop at least once.
● Break and Continue: Understand the use of break to exit loops and switch
statements.Harness the power of continue to skip code within a loop for
specific iterations.
● Coding Exercise: Multiplication Table: Strengthen your coding prowess with
a hands-on exercise focused on creating a multiplication table.
Embark on this chapter to gain a solid foundation in controlling the flow of your
JavaScript programs, making informed decisions and efficiently iterating through
tasks. Engage with practical exercises to reinforce your understanding and emerge
equipped with the skills to navigate the dynamic landscape of control flow in
JavaScript.
Control flow in JavaScript refers to the order in which statements are executed in a
script. JavaScript provides several control flow statements that allow you to make
decisions in your code and execute different blocks of code based on those
decisions.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
44
In this chapter we will be introducing coding exercises, they are used to
demonstrate how the code works. It's suggested to run the code in your editor,
make changes to the code being presented to get a feel for how it works and what
it can do.
Here are some key control flow statements in JavaScript:
Conditional Statements:
if statement:
The if statement allows you to execute a block of code only if a specified condition
is true.
if (condition) {
// Code to be executed if the condition is true
}
if (x > 5) {
console.log("x is greater than 5");
}
In this example, the console.log statement will be executed because the condition
x > 5 is true.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
45
Coding Exercise Sign of a Number
This coding exercise will demonstrate the use of an if statement in JavaScript. In
this exercise, we'll check if a given number is positive, negative, or zero.
// Test cases
console.log(checkSign(5)); // Output: Positive
console.log(checkSign(-8)); // Output: Negative
console.log(checkSign(0)); // Output: Zero
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
46
● The checkSign function takes a parameter number.
● The if statement checks three conditions:
○ If number is greater than 0, it returns "Positive".
○ If number is less than 0, it returns "Negative".
○ If neither of the above conditions is met, it returns "Zero".
● Three test cases are provided using console.log to demonstrate the
function's behavior with different input values.
Feel free to run this code in a JavaScript environment to see how the if statement
is used to determine the sign of a given number. You can modify the test cases or
the function to experiment with different scenarios.
if-else statement:
The if-else statement allows you to execute one block of code if the condition is
true and another block if the condition is false.
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
47
if-else if-else statement:
You can use else if to test multiple conditions.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions is
true
}
The else if statement allows you to check multiple conditions in sequence. If the
first if condition is false, it moves on to the next else if condition. The else
statement is used to define a block of code that will be executed if none of the
previous conditions are true. Here's an example:
let num = 0;
if (num > 0) {
console.log("Number is positive");
} else if (num < 0) {
console.log("Number is negative");
} else {
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
48
console.log("Number is zero");
}
In this case, the output will be "Number is zero" because the value of num is not
greater than 0, and it's not less than 0.
Switch Statement:
The switch statement is used to perform different actions based on different
conditions.
switch (expression) {
case value1:
// Code to be executed if expression === value1
break;
case value2:
// Code to be executed if expression === value2
break;
// Additional cases as needed
default:
// Code to be executed if none of the cases match
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
49
It's often used when you have a variable with multiple possible values. Here's an
example:
let day = "Wednesday";
switch (day) {
case "Monday":
console.log("It's the start of the week");
break;
case "Wednesday":
console.log("It's the middle of the week");
break;
case "Friday":
console.log("It's the end of the week");
break;
default:
console.log("It's some other day");
}
In this example, the output will be "It's the middle of the week" because the value
of day is "Wednesday". The break statement is crucial to exit the switch block
after a case is matched.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
50
Coding Exercise : Day of the Week
In this exercise, we'll create a function that takes a day of the week as input and
prints a message based on the day using a switch statement.
// Exercise: Day of the Week Message
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
51
case "Saturday":
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("Invalid day entered. Please enter a
valid day.");
}
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
52
Loops:
Loops in JavaScript are control flow structures that allow you to repeatedly
execute a block of code as long as a specified condition is true. Loops are a
fundamental part of programming, as they provide a way to automate repetitive
tasks and iterate over collections of data. JavaScript supports several types of
loops, including the for loop, while loop, and do-while loop. Each type has its own
use cases and syntax.
for Loop:
The for loop is used to iterate over a block of code a specific number of times.
The for loop is commonly used when you know the number of iterations you want
to perform. It consists of three parts: initialization, condition, and iteration
expression.
for (let i = 0; i < 5; i++) {
// Code to be executed in each iteration
console.log(i);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
53
}
In this example, the loop initializes a variable i to 0, executes the code block as
long as i is less than 5, and increments i by 1 in each iteration.
while Loop:
The while loop continues to execute a block of code as long as the specified
condition is true.
while (condition) {
// Code to be executed while the condition is true
}
The while loop is used when you don't know the number of iterations in advance,
and the loop continues as long as the specified condition is true.
let i = 0;
while (i < 5) {
// Code to be executed in each iteration
console.log(i);
i++;
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
54
In this example, the loop continues as long as i is less than 5. The increment of i
(i++) needs to be done explicitly within the loop.
do-while Loop:
Similar to the while loop, but the code block is executed at least once before
checking the condition.
do {
// Code to be executed at least once
} while (condition);
The do-while loop is similar to the while loop, but it ensures that the code block is
executed at least once before checking the loop condition.
let i = 0;
do {
// Code to be executed in each iteration
console.log(i);
i++;
} while (i < 5);
In this example, the code block is executed once, and then the loop continues as
long as i is less than 5.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
55
Break and Continue:
The break statement is used to terminate a loop or switch statement.
The continue statement is used to skip the rest of the code inside a loop for the
current iteration and move to the next iteration.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
if (i === 3) {
continue; // Skip the rest of the code for i equals
3 and move to the next iteration
}
// Code here
}
These control flow statements provide the foundation for creating logic, making
decisions, and controlling the flow of execution in your JavaScript programs.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
56
console.log(`Multiplication Table for ${number}:`);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
57
3. The function is then tested with different numbers (5 and 8 in this case).
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
58
A) Day of the Week
B) Multiplication Table
C) Sign of a Number
D) Break and Continue
Answer: C) Sign of a Number
What statement is used when you want to provide an alternative action if the if
condition is not true?
A) else
B) for
C) switch
D) while
Answer: A) else
A) To end a loop
B) To create a function
C) To specify additional conditions after the initial if statement
D) To print to the console
Answer: C) To specify additional conditions after the initial if statement
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
59
B) To make decisions based on a condition
C) To define a function
D) To provide an alternative action
Answer: B) To make decisions based on a condition
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
60
Answer: A) To create a loop that always executes at least once
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
61
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
62
Chapter 3 Functions in JavaScript
Embark on a transformative exploration of JavaScript functions, the building
blocks of modular and reusable code. This chapter delves into the intricacies of
function declarations, parameters, and invocations, empowering you to wield the
power of functions in your programming endeavors. Engage in hands-on coding
exercises, from calculating the area of geometric shapes to understanding the
factorial of a number and distinguishing between even and odd values. Uncover
the nuances of conditional statements within functions and unravel the mysteries
of JavaScript scope and closures. Here are the key topics awaiting your discovery:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
63
● Coding Exercise: Even and Odd : Dive into a coding exercise to identify and
differentiate between even and odd numbers within a function.
● Function Invocation : Learn the process of invoking or calling functions to
execute their defined tasks. Understand the importance of function
invocation in JavaScript.
● Return Statement : Grasp the significance of the return statement in
functions. Participate in a coding exercise focused on calculating the
factorial of a number.
● Coding Exercise: Factorial of a Number: Strengthen your coding prowess
with a hands-on exercise centered on computing the factorial of a number.
● Conditional Statements in Functions: Explore the integration of conditional
statements within functions. Understand how functions can adapt their
behavior based on conditions.
● JavaScript Scope and Closures: Unravel the concept of scope in JavaScript
functions. Witness examples of function scope and engage in a coding
exercise to solidify your understanding.
● Closures in JavaScript Functions: Delve into the intriguing world of closures,
understanding their definition and purpose.
● Explore examples of closures and their role in the scope chain.
● Coding Exercise: Closure Counter: Apply your knowledge through a coding
exercise focused on creating a closure counter.
Embark on this chapter to acquire a profound understanding of JavaScript
functions, from their inception and invocation to the intricacies of scope and
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
64
closures. Engage in practical exercises that fortify your coding skills, and emerge
equipped to leverage functions as powerful tools in your programming arsenal.
Function Declaration:
// Syntax for declaring a function
function sayHello() {
console.log("Hello, World!");
}
In this example:
The function body, enclosed in curly braces {}, contains the code to be executed
when the function is called.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
65
Coding Exercise Area of Rectangle
exercise for practicing JavaScript function declaration. In this exercise, we'll create
a function that calculates the area of a rectangle.
// Test cases
const rectangle1Area = calculateRectangleArea(5, 8);
console.log("Area of Rectangle 1:", rectangle1Area); //
Output: Area of Rectangle 1: 40
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
66
console.log("Area of Rectangle 3:", rectangle3Area); //
Output: Area of Rectangle 3: 49
Feel free to run this code in a JavaScript environment and experiment with
different test cases to see how the function behaves. This exercise is designed to
reinforce the concept of function declaration and basic arithmetic operations
within a function.
Function Parameters:
// Function with parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
Functions can take parameters, which act as variables within the function.
In this example, name is a parameter, and its value is used inside the function.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
67
Coding Exercise Triangle Area
This coding exercise focuses on passing parameters to a JavaScript function. In this
exercise, we'll create a function that calculates the area of a triangle using its base
and height.
// Coding Exercise: Calculate the Area of a Triangle
// Test cases
const triangle1Area = calculateTriangleArea(4, 6);
console.log("Area of Triangle 1:", triangle1Area); //
Output: Area of Triangle 1: 12
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
68
console.log("Area of Triangle 3:", triangle3Area); //
Output: Area of Triangle 3: 15
Feel free to run this code in a JavaScript environment and experiment with
different test cases. This exercise is designed to reinforce the concept of passing
parameters to a function and using them in the function's logic.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
69
return "Even";
} else {
return "Odd";
}
}
// Test cases
const result1 = checkEvenOrOdd(10);
console.log("Number 10 is:", result1); // Output:
Number 10 is: Even
Function Invocation:
// Calling a function
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
70
sayHello(); // Output: Hello, World!
Return Statement:
// Function with a return statement
function addNumbers(a, b) {
return a + b;
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
71
Coding Exercise Factorial of a Number
This coding exercise involves returning values from a JavaScript function. In this
exercise, we'll build a function that calculates the factorial of a given positive
integer.
// Coding Exercise: Calculate the Factorial of a Number
// Test cases
var result1 = calculateFactorial(5);
console.log("Factorial of 5:", result1); // Output:
Factorial of 5: 120
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
72
console.log("Factorial of 8:", result2); // Output:
Factorial of 8: 40320
factorial: n!=n×(n−1)!.
4. Three test cases are provided to demonstrate how the function can be used
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
73
} else {
return "Zero";
}
}
This exercise helps reinforce the concept of passing parameters to a function and
using them in conditional statements within the function's logic.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
74
Example of Function Scope:
function exampleFunction() {
var localVar = "I am a local variable";
console.log(localVar);
}
exampleFunction(); // Outputs: I am a local variable
// Global variable
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
75
var globalVar = "I am a global variable";
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
76
console.log("Inside function:", functionVar);
}
// Test cases
console.log("Outside function:", globalVar);
exampleFunction();
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
77
Closures in JavaScript Functions:
Closures occur when a function is defined within another function, allowing the
inner function to access variables from the outer (enclosing) function even after
the outer function has finished executing.
Example of Closure:
function outerFunction() {
var outerVar = "I am from outerFunction";
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
78
Closures are powerful because they allow functions to "remember" the
environment in which they were created, preserving the state of variables even
after the outer function has completed execution.
Scope Chain:
JavaScript utilizes a scope chain to determine the scope of a variable. When a
variable is referenced, the JavaScript engine looks for the variable in the current
scope and, if not found, continues to the outer scopes until it finds the variable or
reaches the global scope.
function outerFunction() {
var outerVar = "I am from outerFunction";
function innerFunction() {
console.log(outerVar); // Found in the outer
scope
console.log(globalVar); // Found in the global
scope
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
79
innerFunction();
}
outerFunction();
In this example, innerFunction can access both outerVar and globalVar because of
the scope chain.
function createCounter() {
// Counter variable within the closure
let count = 0;
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
80
// Returning the inner function (closure)
return counter;
}
// Test cases
counter1(); // Output: 1
counter1(); // Output: 2
counter2(); // Output: 1
counter1(); // Output: 3
counter2(); // Output: 2
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
81
4. Each time a counter is invoked (counter1() or counter2()), it increments and
logs its own count, while maintaining its own separate state.
This exercise illustrates the concept of closures, where the inner function
(counter) "closes over" the count variable, allowing it to retain and modify its
value between different invocations.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
82
What is the importance of creating modular code in JavaScript?
A) It improves code readability
B) It enables code reuse
C) It reduces redundancy
D) All of the above
Answer: D) All of the above
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
83
B) It allows dynamic and customizable functions
C) It simplifies code indentation
D) It eliminates the need for loops
Answer: B) It allows dynamic and customizable functions
How does the function in the coding exercise determine whether a number is
even or odd?
A) By checking the remainder of division
B) By comparing the number with zero
C) By using the eval function
D) By counting the number of digits
Answer: A) By checking the remainder of division
Function Invocation:
What does it mean to invoke or call a function in JavaScript?
A) To declare a function
B) To define a function
C) To execute a function's code
D) To comment out a function
Answer: C) To execute a function's code
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
84
C) It executes the function's defined tasks
D) It prevents errors in the code
Answer: C) It executes the function's defined tasks
Return Statement:
What is the primary role of the return statement in functions?
A) To stop the function's execution
B) To return a value from the function
C) To define variables
D) To print to the console
Answer: B) To return a value from the function
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
85
C) To adapt function behavior based on conditions
D) To define variables
Answer: C) To adapt function behavior based on conditions
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
86
Chapter 4 Working with Data Structures
Embark on a comprehensive exploration of data structures in JavaScript, essential
tools for organizing and manipulating information in your programs. This chapter
delves into the versatile world of arrays, from understanding basic operations to
mastering powerful array methods. Engage in hands-on coding exercises that span
eight tasks, reinforcing your skills in array manipulation. Transition to the realm of
objects, unraveling the intricacies of properties, methods, and different notation
techniques. Explore the concepts of sets and maps, understanding their unique
features and applications. The journey continues with a dive into custom data
structures, including an introduction to object-oriented programming in
JavaScript. Here are the key topics awaiting your exploration:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
87
○ Explore object properties using both dot notation and square bracket
notation.
○ Uncover the world of object methods.
○ Apply your knowledge in a coding exercise centered on creating a
person object.
● Sets: Explore the concept and functionality of sets in JavaScript.
● Maps:Understand the unique features and applications of maps.
● Custom Data Structures: Introduce yourself to the realm of object-oriented
programming in JavaScript. Learn to create objects, define properties and
methods, and explore the concept of prototypes. Delve into inheritance and
encapsulation, key pillars of object-oriented programming.
Embark on this chapter to deepen your understanding of essential data structures
in JavaScript. From arrays to objects, sets, maps, and custom data structures, this
exploration equips you with the skills to organize and manage information
efficiently in your programming endeavors. Engage with practical coding exercises
that solidify your grasp of these fundamental concepts.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
88
Arrays:
An array is a collection of elements, each identified by an index or a key. Arrays in
JavaScript are dynamic and can hold elements of different data types.
Example:
// Creating an array
let fruits = ['Apple', 'Banana', 'Orange'];
// Accessing elements
console.log(fruits[0]); // Output: Apple
// Modifying elements
fruits[1] = 'Grapes';
// Adding elements
fruits.push('Mango');
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
89
Coding Exercise Arrays 8 Tasks
Below coding exercise that focuses on creating arrays and performing basic
operations on them.
// Coding Exercise: Working with Arrays
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
90
// Task 7: Calculate the sum of all elements in the
array
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
91
8. We check if a specific number is present in the array using includes.
push()
Adds one or more elements to the end of an array.
let fruits = ['Apple', 'Banana'];
fruits.push('Orange');
// fruits is now ['Apple', 'Banana', 'Orange']
pop()
Removes the last element from an array and returns that element.
let fruits = ['Apple', 'Banana', 'Orange'];
let removedFruit = fruits.pop();
// removedFruit is 'Orange', fruits is now ['Apple',
'Banana']
shift()
Removes the first element from an array and returns that element.
let fruits = ['Apple', 'Banana', 'Orange'];
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
92
let removedFruit = fruits.shift();
// removedFruit is 'Apple', fruits is now ['Banana',
'Orange']
unshift()
Adds one or more elements to the beginning of an array.
let fruits = ['Banana', 'Orange'];
fruits.unshift('Apple');
// fruits is now ['Apple', 'Banana', 'Orange']
concat()
Combines two or more arrays.
slice()
Returns a portion of an array without modifying the original array.
let fruits = ['Apple', 'Banana', 'Orange', 'Grapes'];
let selectedFruits = fruits.slice(1, 3);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
93
// selectedFruits is ['Banana', 'Orange'], fruits is
unchanged
splice()
Changes the contents of an array by removing or replacing existing elements
and/or adding new elements in place.
let fruits = ['Apple', 'Banana', 'Orange'];
fruits.splice(1, 1, 'Grapes', 'Watermelon');
// fruits is now ['Apple', 'Grapes', 'Watermelon',
'Orange']
indexOf()
Returns the first index at which a given element can be found in the array.
let fruits = ['Apple', 'Banana', 'Orange'];
let index = fruits.indexOf('Banana');
// index is 1
forEach()
Executes a provided function once for each array element.
let numbers = [1, 2, 3, 4];
numbers.forEach(function (num) {
console.log(num);
});
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
94
// Output: 1, 2, 3, 4
map()
Creates a new array with the results of calling a provided function on every
element in the array.
let numbers = [1, 2, 3, 4];
let squared = numbers.map(function (num) {
return num * num;
});
// squared is [1, 4, 9, 16]
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
95
// Task 3: Remove the last fruit from the array using
pop
let removedFruit = fruits.pop();
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
96
1. We start by creating an array of fruits.
2. We use the push method to add a new fruit ('Grapes') to the end of the
array.
3. We use the pop method to remove the last fruit from the array and store it
in the removedFruit variable.
4. We use the unshift method to add a new fruit ('Pineapple') to the beginning
of the array.
5. We use the shift method to remove the first fruit from the array and store it
in the removedFirstFruit variable.
6. We display the modified array and the fruits that were removed.
Objects:
An object is a collection of key-value pairs, where each key is a string (or a symbol)
and each value can be any data type.
// Creating an object
let person = {
name: 'John',
age: 25,
city: 'New York'
};
// Accessing properties
console.log(person.name); // Output: John
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
97
// Modifying properties
person.age = 26;
// Adding properties
person.gender = 'Male';
Object Properties:
Properties represent characteristics or attributes of an object. They can be
accessed using dot notation or square bracket notation.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
98
Using Dot Notation:
// Creating an object
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
zipCode: '12345'
}
};
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
99
Object Methods:
Methods are functions associated with objects. They can perform actions or
computations related to the object.
// Adding a method to the object
person.sayHello = function() {
console.log('Hello, my name is ' + this.firstName +
' ' + this.lastName);
};
In modern JavaScript, you can also use method shorthand when defining
methods:
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
zipCode: '12345'
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
100
},
sayHello() {
console.log('Hello, my name is ' +
this.firstName + ' ' + this.lastName);
}
};
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
101
Coding Exercise Object Person
Below is a coding exercise that focuses on creating objects and performing
operations on them.
// Coding Exercise: Working with Objects
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
102
console.log("Full Name:", person.firstName + ' ' +
person.lastName);
console.log("Age:", person.age);
console.log("Address:", person.address.street + ', ' +
person.address.city + ' ' + person.address.zipCode);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
103
// Task 8: Display the book object
console.log("Book Object:", book);
Sets:
A Set is a collection of unique values. It can be used to eliminate duplicate values
from an array or to store a unique set of values.
// Creating a set
let uniqueNumbers = new Set([1, 2, 3, 2, 4, 5]);
// Adding values
uniqueNumbers.add(6);
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
104
// Checking existence
console.log(uniqueNumbers.has(3)); // Output: true
Maps:
A Map is a collection of key-value pairs similar to an object, but with some key
differences, such as allowing any data type as a key.
// Creating a map
let fruitMap = new Map();
// Accessing values
console.log(fruitMap.get('apple')); // Output: 5
// Checking existence
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
105
console.log(fruitMap.has('orange')); // Output: false
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
106
this.head = null;
}
addNode(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
displayList() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
107
}
// Usage
let linkedList = new LinkedList();
linkedList.addNode(1);
linkedList.addNode(2);
linkedList.addNode(3);
linkedList.displayList();
Understanding and effectively using these data structures is crucial for writing
efficient and organized JavaScript code. Depending on the task at hand, choosing
the right data structure can significantly improve the performance and readability
of your programs.
Javascript Object-oriented
Object-oriented programming (OOP) is a programming paradigm that uses objects
and classes for organizing and structuring code. In JavaScript, while the language
itself is prototype-based, it supports OOP principles through the use of
constructor functions and prototypes. Let's explore key concepts related to
object-oriented programming in JavaScript:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
108
Creating Objects:
// Method
this.sayHello = function() {
console.log('Hello, my name is ' +
this.firstName + ' ' + this.lastName);
};
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
109
let john = new Person('John', 'Doe');
john.sayHello(); // Output: Hello, my name is John Doe
Prototypes:
Prototypes allow objects to inherit properties and methods from other objects.
This is a fundamental aspect of JavaScript's prototype-based inheritance.
// Adding a method to the prototype
Person.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
Inheritance:
JavaScript supports inheritance through prototype chaining. Objects can inherit
properties and methods from other objects.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
110
this.studentId = studentId;
}
Encapsulation:
Encapsulation involves bundling the data (properties) and methods that operate
on the data within a single unit (object). This helps in organizing and protecting
the internal state of an object.
function BankAccount(accountNumber, balance) {
// Private properties
let _accountNumber = accountNumber;
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
111
let _balance = balance;
// Public methods
this.getBalance = function() {
return _balance;
};
this.deposit = function(amount) {
_balance += amount;
};
this.withdraw = function(amount) {
if (amount <= _balance) {
_balance -= amount;
} else {
console.log('Insufficient funds.');
}
};
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
112
console.log(account.getBalance()); // Output: 1500
account.withdraw(700);
console.log(account.getBalance()); // Output: 800
Conclusion:
JavaScript's approach to OOP involves constructor functions, prototypes, and
prototype-based inheritance. While the language doesn't have traditional classes,
these concepts allow for the creation of reusable and organized code in an
object-oriented manner. Modern JavaScript (ES6 and later) introduced the class
syntax, which provides a more familiar class-based syntax for OOP. However,
under the hood, it still relies on prototypes for inheritance.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
113
this.year = year;
this.speed = 0;
}
accelerate() {
this.speed += 10;
console.log(`${this.year} ${this.make}
${this.model} is accelerating. Current speed:
${this.speed} mph`);
}
brake() {
this.speed -= 5;
console.log(`${this.year} ${this.make}
${this.model} is braking. Current speed: ${this.speed}
mph`);
}
honk() {
console.log(`${this.year} ${this.make}
${this.model} says honk honk!`);
}
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
114
// Derived class representing an Electric Car,
inheriting from the Car class
class ElectricCar extends Car {
constructor(make, model, year, batteryCapacity) {
// Call the constructor of the base class (Car)
super(make, model, year);
this.batteryCapacity = batteryCapacity;
this.currentCharge = 100; // Assuming fully
charged initially
}
charge() {
this.currentCharge = 100;
console.log(`${this.year} ${this.make}
${this.model} is fully charged.`);
}
accelerate() {
if (this.currentCharge > 0) {
// Call the accelerate method of the base
class (Car)
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
115
super.accelerate();
this.currentCharge -= 5; // Simulate
battery usage
} else {
console.log(`${this.year} ${this.make}
${this.model} is out of charge. Please recharge.`);
}
}
}
// Test cases
const regularCar = new Car('Toyota', 'Camry', 2022);
regularCar.accelerate();
regularCar.brake();
regularCar.honk();
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
116
electricCar.accelerate(); // Accelerate again after
charging
1. We define a base class Car with properties (make, model, year, speed) and
methods (accelerate, brake, honk).
2. We create a derived class ElectricCar that extends the functionality of the
base Car class, adding properties (batteryCapacity, currentCharge) and
methods (charge, overridden accelerate).
3. We create instances of both Car and ElectricCar and demonstrate their
methods.
Arrays:
What is the primary purpose of arrays in JavaScript?
A) Storing only strings
B) Organizing and storing multiple values
C) Defining functions
D) Creating loops
Answer: B) Organizing and storing multiple values
Which array method adds one or more elements to the end of an array?
A) push()
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
117
B) pop()
C) shift()
D) unshift()
Answer: A) push()
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
118
D) Concatenates two arrays
Answer: C) Creates a shallow copy of the array
Objects:
In JavaScript objects, what is the role of dot notation?
A) Multiplication
B) Division
C) Accessing properties
D) Creating loops
Answer: C) Accessing properties
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
119
What are object methods in JavaScript?
A) Mathematical operations
B) Functions stored as properties
C) Conditional statements
D) Loops
Answer: B) Functions stored as properties
Sets:
What is the primary characteristic of sets in JavaScript?
A) They allow duplicate values
B) They automatically sort elements
C) They only store strings
D) They do not allow duplicate values
Answer: D) They do not allow duplicate values
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
120
Maps:
What is a key feature of maps in JavaScript?
A) They allow duplicate keys
B) They automatically sort keys
C) They store data in a random order
D) They associate unique keys with values
Answer: D) They associate unique keys with values
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
121
A) A template for creating objects
B) A mathematical equation
C) A conditional statement
D) A type of loop
Answer: A) A template for creating objects
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
122
Prototypes:
What is the role of prototypes in JavaScript objects?
A) Storing data
B) Defining methods
C) Providing a template for creating objects
D) Sorting arrays
Answer: C) Providing a template for creating objects
Encapsulation:
What is encapsulation in the context of object-oriented programming?
A) The removal of duplicate values
B) The organization of code into objects
C) The use of arithmetic operations
D) The bundling of data and methods within an object
Answer: D) The bundling of data and methods within an object
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
123
Chapter 5 Mastering Strings and Advanced String
Methods
Dive into the intricacies of string manipulation in JavaScript with a focus on Line
Breaks, Template Literals, and Advanced String Methods. Uncover the versatility of
Template Literals, exploring their benefits and the art of escaping backticks. The
chapter ventures into an array of advanced string methods, providing a
comprehensive understanding of their applications and use cases. From basic
operations like calculating string length to more complex tasks such as substring
extraction, the chapter equips you with the tools to wield strings effectively in
your code. Here are the key topics awaiting exploration:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
124
○ Witness the power of slice(startIndex, endIndex), indexOf(searchStr,
startIndex), replace(searchStr, replaceStr), split(separator), and trim().
● JavaScript Substring:
○ Implement and understand the substring() method.
○ Delve into considerations, including case-sensitive searches and
handling multiple occurrences.
● NaN and Type Conversion:
○ Grasp the concept of NaN (Not a Number) in JavaScript.
○ Explore examples of NaN and scenarios involving failed conversions.
○ Learn techniques for checking and handling NaN.
● Type Conversion with JavaScript Number and String:
○ Master the art of converting strings to numbers using parseInt() and
parseFloat().
○ Explore the reverse process of converting numbers to strings using
the toString() method.
○ Understand the significance of radix in parseInt().
● Math Object in JavaScript:
○ Explore constants like Math.PI and basic mathematical operations.
○ Navigate through exponentiation, logarithms, and advanced
mathematical operations with the Math object.
● JavaScript Hoisting:
○ Uncover the concept of hoisting for variables and functions.
○ Explore scenarios involving hoisting with function expressions.
○ Gain insights into considerations and best practices.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
125
Embark on this chapter to elevate your proficiency in handling strings, harnessing
the power of advanced string methods, and unraveling the complexities of NaN,
type conversion, and JavaScript's Math object. Whether you're a novice or an
experienced coder, these topics will deepen your understanding and enhance your
capabilities in JavaScript string manipulation.
Template Literals:
Template literals, introduced in ECMAScript 6 (ES6), provide a more convenient
way to create strings with line breaks and include variables.
let name = "John";
let greeting = `Hello, ${name}!
How are you today?`;
console.log(greeting);
In this example:
● The backticks (`) are used to define a template literal.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
126
● ${name} is used for string interpolation, allowing the inclusion of variables
within the string.
● Line breaks are included directly within the template literal without the
need for the \n character.
Escaping Backticks:
If you need to include an actual backtick within a template literal, you can escape
it using a backslash:
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
127
strings in JavaScript. They are especially useful when dealing with multiline strings,
dynamic content, and complex string formatting.
length:
Description: Returns the length of a string.
const message = "Hello, World!";
const length = message.length; // Result: 13
charAt(index):
Description: Returns the character at the specified index in a string.
const message = "Hello, World!";
const charAtIndex = message.charAt(7); // Result: "W"
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
128
const fullName = firstName.concat(" ", lastName); //
Result: "John Doe"
In JavaScript, the toLowerCase() and toUpperCase() string methods are used to
convert strings to lowercase and uppercase, respectively. These methods are
useful for standardizing the case of strings, making comparisons or manipulations
more consistent.
toLowerCase() Method:
The toLowerCase() method converts all the characters in a string to lowercase.
let originalString = "Hello, World!";
let lowercaseString = originalString.toLowerCase();
toUpperCase() Method:
The toUpperCase() method converts all the characters in a string to uppercase.
let originalString = "Hello, World!";
let uppercaseString = originalString.toUpperCase();
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
129
Using These Methods with Variables:
let mixedCaseString = "JaVaScRiPt Is FuN!";
// Convert to lowercase
let lowercaseResult = mixedCaseString.toLowerCase();
console.log(lowercaseResult); // Output: "javascript is
fun!"
// Convert to uppercase
let uppercaseResult = mixedCaseString.toUpperCase();
console.log(uppercaseResult); // Output: "JAVASCRIPT IS
FUN!"
Use Cases:
● Standardizing Input: These methods are often used when dealing with user
input to ensure consistency in case.
● String Comparisons: When comparing strings, converting them to the same
case using these methods can be useful to avoid case-sensitive mismatches.
● Display Formatting: Formatting strings for display purposes, such as
converting titles or headings to a consistent case.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
130
Remember that these methods do not modify the original string but instead
return a new string with the desired case. If you need to change the original
string, you should assign the result back to the variable:
let originalString = "Hello, World!";
originalString = originalString.toLowerCase(); //
Update the original string to lowercase
console.log(originalString); // Output: "hello, world!"
These string methods provide a simple and effective way to manipulate the case
of strings in JavaScript.
toUpperCase():
Description: Converts a string to uppercase.
const message = "Hello, World!";
const uppercased = message.toUpperCase(); // Result:
"HELLO, WORLD!"
toLowerCase():
Description: Converts a string to lowercase.
const message = "Hello, World!";
const lowercased = message.toLowerCase(); // Result:
"hello, world!"
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
131
slice(startIndex, endIndex):
Description: Extracts a portion of a string from startIndex to endIndex (endIndex is
optional).
const message = "Hello, World!";
const sliced = message.slice(7, 12); // Result: "World"
indexOf(searchStr, startIndex):
Description: Returns the index of the first occurrence of searchStr in a string,
starting from startIndex.
const message = "Hello, World!";
const index = message.indexOf("World"); // Result: 7
replace(searchStr, replaceStr):
Description: Replaces the first occurrence of searchStr with replaceStr in a string.
const message = "Hello, World!";
const newMessage = message.replace("World",
"Universe"); // Result: "Hello, Universe!"
split(separator):
Description: Splits a string into an array of substrings based on the specified
separator.
const message = "Hello, World!";
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
132
const parts = message.split(", "); // Result: ["Hello",
"World!"]
trim():
Description: Removes whitespace from both ends of a string.
Example:
const paddedString = " Trim me! ";
const trimmedString = paddedString.trim(); // Result:
"Trim me!"
JavaScript Substring
The substring() method in JavaScript is used to extract a portion of a string. It
takes two parameters: the starting index and the ending index (optional). The
extracted substring includes characters from the starting index up to, but not
including, the character at the ending index. If the ending index is omitted, the
substring includes characters from the starting index to the end of the string.
Example of substring():
let originalString = "JavaScript is amazing!";
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
133
let substringResult = originalString.substring(0, 10);
return firstName;
}
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
134
let fullName = "John Doe";
let firstName = extractFirstName(fullName);
console.log(`The first name is: ${firstName}`);
Explanation:
The extractFirstName function takes a fullName as its parameter.
indexOf(" ") is used to find the index of the space character, separating the first
and last names.
substring(0, spaceIndex) is used to extract the characters from the beginning of
the string up to (but not including) the space character, representing the first
name.
The extracted first name is then returned by the function.
Additional Considerations:
If the ending index is omitted, the substring includes characters from the starting
index to the end of the string.
let exampleString = "Hello, World!";
let substringWithoutEndIndex =
exampleString.substring(7);
console.log(substringWithoutEndIndex); // Output:
"World!"
In this example, substring(7) extracts the substring from index 7 to the end of the
string.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
135
The substring() method is a useful tool for extracting specific portions of a string in
JavaScript. Understanding its behavior and using it appropriately can enhance
your ability to manipulate strings in various scenarios
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
136
console.log(`"${searchTerm}" found at index
${indexOfTerm}.`);
} else {
console.log(`"${searchTerm}" not found.`);
}
In this example, we check if the substring "fun" exists in the string. If it does, we
log its index; otherwise, we log that it was not found.
Using startIndex:
You can specify a starting index to begin the search:
let exampleString = "This is a sample sentence.";
let indexOfIs = exampleString.indexOf("is", 3);
console.log(indexOfIs); // Output: 5
Here, indexOf("is", 3) starts the search from index 3, and the result is 5 because it
finds the second occurrence of "is" starting from index 3.
Case-Sensitive Search:
let caseSensitiveString = "JavaScript is
case-sensitive.";
let searchTerm = "javascript";
let indexOfTerm =
caseSensitiveString.indexOf(searchTerm);
console.log(indexOfTerm); // Output: -1
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
137
By default, indexOf() performs a case-sensitive search. In this example, the search
term "javascript" is not found because of the case difference.
Multiple Occurrences:
let multipleOccurrences = "JavaScript is amazing.
JavaScript is powerful.";
let searchTerm = "JavaScript";
let firstIndexOfTerm =
multipleOccurrences.indexOf(searchTerm);
let secondIndexOfTerm =
multipleOccurrences.indexOf(searchTerm,
firstIndexOfTerm + 1);
console.log(firstIndexOfTerm); // Output: 0
console.log(secondIndexOfTerm); // Output: 22
Here, we find the first occurrence of "JavaScript" and then find the second
occurrence starting from the index after the first occurrence.
Summary:
indexOf() is used to find the index of the first occurrence of a substring in a string.
It returns -1 if the substring is not found.
You can specify a starting index for the search.
The search is case-sensitive by default.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
138
It is commonly used for substring search and checking the existence of specific
values in a string.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
139
// 2. Add three fruits to the array
fruits.push("Apple", "Banana", "Orange");
// 3. Output the contents of the array
console.log(fruits); // Output: ["Apple", "Banana",
"Orange"]
Explanation:
We start by declaring an empty array using let fruits = [];.
The push() method is then used to add elements to the end of the array. In this
case, we add "Apple," "Banana," and "Orange."
Finally, we use console.log() to output the contents of the array, which should now
contain the three fruits.
This exercise demonstrates how to declare an empty array and modify its contents
using the push() method.
Remember that arrays in JavaScript are dynamic, meaning you can add or remove
elements at any time, and they can hold a mix of different data types.
What is NaN
NaN in JavaScript stands for "Not-a-Number." It is a special value that represents
the result of an operation that cannot produce a meaningful numeric result. NaN
is often returned when attempting to perform arithmetic operations with
non-numeric values or when an operation is undefined for a given input.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
140
Examples of NaN:
Failed Conversion:
let failedConversion = parseInt("Hello");
console.log(failedConversion); // Output: NaN
The parseInt() function returns NaN when it cannot parse a valid integer from the
given string.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
141
console.log(isNaN(result)); // Output: true
Handling NaN:
Check for NaN: Use isNaN() to check if a value is NaN before performing
operations.
let userInput = prompt("Enter a number:");
let parsedInput = parseFloat(userInput);
if (isNaN(parsedInput)) {
console.log("Invalid input. Please enter a number.");
} else {
console.log("You entered a valid number.");
}
Default Values: Provide default values when dealing with operations that may
result in NaN.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
142
let userInput = prompt("Enter a number:");
let parsedInput = parseFloat(userInput) || 0;
Using parseInt():
Using parseFloat():
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
143
let floatValue = parseFloat(floatString);
console.log(floatValue); // Output: 3.14
The parseFloat() function parses a string and returns a floating-point number.
In this example, the string "3.14" is converted to the number 3.14.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
144
console.log(binaryToDecimal); // Output: 10
In this example, parseInt(binaryString, 2) converts the binary string "1010" to the
decimal number 10.
Summary:
parseInt() and parseFloat() are used to convert strings to numbers.
The toString() method is used to convert numbers to strings.
Be cautious about the possibility of NaN when using parseInt() or parseFloat().
Radix can be specified in parseInt() for non-decimal conversions.
Math Constants:
Math.PI
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
145
Basic Mathematical Operations:
Math.abs(x)
Math.round(x)
Math.floor(x)
Math.ceil(x)
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
146
console.log(ceilNumber); // Output: 5
Math.random()
Math.pow(x, y)
Math.sqrt(x)
Math.log(x)
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
147
Example:
let logValue = Math.log(Math.E); // Math.E represents
Euler's number (e)
console.log(logValue); // Output: 1
These are just a few examples of the capabilities of the Math object in JavaScript.
It offers a wide range of mathematical functions, allowing developers to perform
complex mathematical operations in a convenient and efficient manner.
JavaScript Hoisting
Hoisting is a JavaScript behavior where variable and function declarations are
moved to the top of their containing scope during the compilation phase. This
means you can use a variable or call a function before it's declared in your code.
However, it's essential to understand the nuances and potential pitfalls associated
with hoisting.
Variable Hoisting:
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
In the example above, the variable x is hoisted to the top of the scope during
compilation. So, when console.log(x) is encountered before the actual declaration
(var x = 5;), it doesn't result in an error. Instead, it logs undefined because the
variable has been declared but not assigned a value at that point.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
148
Function Hoisting:
greet(); // Output: "Hello, World!"
function greet() {
console.log("Hello, World!");
}
In this example, the function greet is hoisted to the top of the scope. Therefore, it
can be called before its actual declaration in the code without causing an error.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
149
initialized, its value will be undefined until the assignment is reached in the
code.
2. Function Declarations vs. Expressions: Function declarations are hoisted,
but function expressions are not hoisted in the same way. Be aware of the
differences, especially when using function expressions assigned to
variables.
3. Order of Declaration: Hoisting occurs at the top of the scope, so variables
and functions are hoisted in the order in which they appear in the code.
4. Best Practice: Declare Before Use: To avoid confusion and potential issues,
it's a best practice to declare variables and functions at the top of their
scope before using them.
5. Understanding hoisting is essential for writing predictable and error-free
JavaScript code. While it can be a powerful feature, it's important to be
aware of its implications and to follow best practices to ensure code clarity
and maintainability.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
150
Answer: B) Simplified syntax
How can you include a line break within a string using Template Literals?
A) Using the \n escape sequence
B) Adding an extra space
C) Inserting a backslash
D) Using the lineBreak() function
Answer: A) Using the \n escape sequence
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
151
What does the charAt(index) method in JavaScript return?
A) The entire string
B) The character at the specified index
C) The index of the first occurrence of a character
D) The length of the string
Answer: B) The character at the specified index
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
152
C) toUpperCase()
D) caseToUpper()
Answer: C) toUpperCase()
JavaScript Substring:
What is the correct syntax for using the substring() method in JavaScript?
A) substring(startIndex, endIndex)
B) substring(index)
C) getSubstring(startIndex, endIndex)
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
153
D) getSubstring(index)
Answer: A) substring(startIndex, endIndex)
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
154
Answer: B) Whether a value is not a number
How can you convert a number to a string in JavaScript using the toString()
method?
A) convertToString(number)
B) toText(number)
C) numberToString(number)
D) number.toString()
Answer: D) number.toString()
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
155
What does the radix parameter represent in the parseInt() method?
A) The base of the number system
B) The index of the starting position
C) The length of the substring
D) The type of conversion to perform
Answer: A) The base of the number system
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
156
Chapter 6 Test your JavaScript Knowledge
Overview of JavaScript
What is JavaScript primarily used for in web development?
A. Styling web pages
B. Enhancing user interfaces
C. Managing databases
D. Creating server-side applications
Answer: B
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
157
Who developed JavaScript?
A. Microsoft
B. Apple
C. Mozilla
D. Netscape
Answer: D
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
158
First Steps with JavaScript
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
159
What is the result of the expression 5 + "5" in JavaScript?
A. 10
B. "55"
C. 55
D. Error
Answer: B
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
160
C. string1 & string2
D. concat(string1, string2)
Answer: A
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
161
What does the term "syntax" refer to in the context of JavaScript?
A. The rules for organizing code
B. The visual appearance of a web page
C. The speed at which code is executed
D. The process of fixing bugs in code
Answer: A
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
162
A. const x = 10;
B. let x = 10;
C. var x = 10;
D. constant x = 10;
Answer: A
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
163
D. # comment
Answer: A
Which of the following is used to check if a variable is not equal to a specific value
in JavaScript?
A. ==
B. ===
C. !=
D. !==
Answer: D
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
164
What does the term "hoisting" refer to in JavaScript?
A. Elevating a variable's scope to the top of its containing function or script
B. Running code in an infinite loop
C. Converting strings to numbers
D. Hiding variables from the global scope
Answer: A
Which of the following statements is true about the === operator in JavaScript?
A. It only checks value equality.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
165
B. It only checks type equality.
C. It checks both value and type equality.
D. It is not a valid operator in JavaScript.
Answer: C
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
166
Answer: A
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
167
A. Removing elements from an array
B. Adding elements to the end of an array
C. Concatenating two arrays
D. Reversing the elements of an array
Answer: A
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
168
D. Both B and C
Answer: D
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
169