0% found this document useful (0 votes)
0 views

JavaScript for Beginners Questions and Answers

The document is a comprehensive guide for beginners learning JavaScript, covering fundamental concepts such as variables, operators, control flow, and functions. It includes sections with questions and detailed answers to help users understand key topics like primitive and reference data types, the use of Node.js, and the structure of JavaScript objects and arrays. Each section is well-organized, providing a clear path for learners to follow as they build their programming skills.

Uploaded by

morrismachaa9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

JavaScript for Beginners Questions and Answers

The document is a comprehensive guide for beginners learning JavaScript, covering fundamental concepts such as variables, operators, control flow, and functions. It includes sections with questions and detailed answers to help users understand key topics like primitive and reference data types, the use of Node.js, and the structure of JavaScript objects and arrays. Each section is well-organized, providing a clear path for learners to follow as they build their programming skills.

Uploaded by

morrismachaa9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

JavaScript for Beginners

StevenCodeCraft.com

Section 1: Getting Started...........................................................................................................2


Section 1: Answers......................................................................................................................3
Section 2: JavaScript Variables..................................................................................................5
Section 2: Answers......................................................................................................................6
Section 3: JavaScript Operators.............................................................................................. 12
Section 3: Answers....................................................................................................................13
Section 4: Control Flow.............................................................................................................18
Section 4: Answers....................................................................................................................19
Section 5: JavaScript Objects.................................................................................................. 26
Section 5: Answers....................................................................................................................27
Section 6: JavaScript Arrays.................................................................................................... 38
Section 6: Answers....................................................................................................................40
Section 7: JavaScript Functions.............................................................................................. 52
Section 7: Answers....................................................................................................................54
1
Section 1: Getting Started

Questions

1) What is JavaScript?

2) What is Node?

2
Section 1: Answers

1) Answer to: What is JavaScript?

In simple terms, JavaScript is a dynamic programming language.

It can be used for creating front end applications, backend API services,
mobile applications, and desktop applications.

JavaScript is a multi-paradigm, general-purpose programming language


with dynamic typing.

It’s multi-paradigm in that JavaScript is not opinionated or strict in how you


write your code. So you can implement your code using various
programming styles.

These styles include object-oriented, imperative, functional, event-driven,


and declarative. (Note if you don’t know these terms yet, they are covered
in the JavaScript Pro course on StevenCodeCraft.com)

General-purpose means that JavaScript can be used for various


applications and platforms.

It’s dynamic in the sense that you can assign a variable to a particular data
type and then assign to another value of a totally different data type.
This is different compared to statically typed languages such as C# or Java
which does not have this level of flexibility.

To better demonstrate the concept of dynamic typing refer to the code


below.

let favoriteNumber = 42; // number data type


favoriteNumber = “My favorite number is 42.”; // string data type

3
2) Answer to: What is Node?

Node is a runtime environment for executing JavaScript outside of a web


browser.

So web browsers, such as Google Chrome, Firebox, Safari, Microsoft


Edge, and Internet Explorer all have a built in JavaScript engine which
executes your JavaScript code.

However in order to execute JavaScript outside of the browser, we will


utilize Node.js.

You can download Node.js for free at their website, https://nodejs.org/en.

4
Section 2: JavaScript Variables

3) What are variables? How would you create one?

4) What are the common operations that are needed in an application?


(Hint: Think of what operations we perform with data?)

5) How many primitive data types are there in JavaScript?

6) What are the primitive data types in JavaScript?

7) What are reference data types?

8) What is the difference between a primitive data type and a reference data
type?

9) What is the assignment operator?

10) What is the const keyword?

11) What are objects?

12) Are objects a reference type or a primitive type?

13) What are arrays?

14) What are functions?

15) What is a parameter variable?

16) What are the two reasons to create a function?

5
Section 2: Answers

3) Answer to: What are variables? How would you create one?

Variables in JavaScript are identifiers assigned to values.

They act as placeholders or references to the data stored in memory.

By using variables, we can manage and manipulate data dynamically


throughout our programs.

They allow us to label data with a descriptive name, making our code more
readable and maintainable.

You would create a variable by using the let keyword and assigning it to a
value.

The process of using the let keyword and assigning it to an initial value is
called initialization.

4) Answer to: What are the common operations that are needed in an
application?
(Hint: Think of what operations we perform with data?)

The common operations include creating data, reading data, updating


data, and deleting data.

These operations are commonly referred to by their acronym, C.R.U.D.


which stand for Create, Read, Update, and Delete.

Data is commonly referred to as “resources” and these resources must


support these four common operations.

6
5) Answer to: How many primitive data types are there in JavaScript?

There are 7 primitive data types in JavaScript.

6) Answer to: What are the primitive data types in JavaScript?

The 7 primitive data types are:


● string
● Symbol
● number
● boolean
● undefined
● null
● BigInt

To demonstrate an example of each of these data types.

The string data type:


let firstName = “Steven”;

The Symbol data type:


const uniqueKey = Symbol();

The number data type:


let favoriteNumber = 42; // number data type (integer)
favoriteNumber = 3.14; // number data type (float/decimal)

The boolean data type:


let lovesCoding = true;

The undefined data type:


let favoriteColor; // it’s value is undefined
favoriteColor = undefined;

The null data type:


let favoriteFruit = null;

7
The BigInt data type:
let veryLargeNumber = 543543634843634n;

7) Answer to: What are reference data types?

Reference data types in programming refer to complex structures known


as objects, which store data as key-value pairs.

This category of data includes not only objects but also arrays, which are
ordered collections of data indexed from zero.

Unlike primitive data types that store their data directly, reference types
store a reference to the memory location on the heap where the actual
data is held.

Consequently, when reference types are passed to functions or assigned


to other variables, it is the reference to the data, not the actual data, that is
passed or assigned.

8) Answer to: What is the difference between a primitive data type and a
reference data type?

Primitive data types store their data directly and operate independently of
other variables. Examples include integers, booleans, and strings.

In contrast, reference data types store a reference to their data, not the
data itself. This means operations on reference data, such as objects and
arrays, can affect their original instances since they point to the same
memory location.

9) Answer to: What is the assignment operator?

The assignment operator, represented by a single equal sign, is used in


programming to assign a specific value to a variable. It sets or updates the
variable’s value.

8
10) Answer to: What is the const keyword?

The const keyword in JavaScript is used to declare variables with values


that cannot be reassigned after their initial assignment.

This ensures the value remains constant throughout the program, which
can enhance security and predictability.

Use const when you know the value should not change, making your code
easier to understand and maintain.

11. Answer to: What are objects?

Objects in JavaScript are used to model real-world nouns, such as people,


places, or things, by encapsulating related data and behavior.

They are created using curly braces, { }, to define key-value pairs, where
keys represent properties and values represent data or functions.

This structure allows objects to maintain state and expose behavior


through methods.

12) Answer to: Are objects a reference type or a primitive type?

Objects in JavaScript are reference types, not primitive types.

Primitive types, like numbers, strings, and booleans, store singular values
directly.
In contrast, objects handle more complex data, storing collections of
key-value pairs. This allows objects to represent structured data and
functionality with the actual data stored in a memory location that the
variable references.

9
13) Answer to: What are arrays?

In JavaScript, arrays are objects that store collections of data in an indexed


format, starting from zero.

Each element in an array is a key-value pair, where the key is the index
and the value is the data stored at that index. Typically, arrays hold
elements of the same data type, allowing for efficient management and
retrieval of data.

14) Answer to: What are functions?

In JavaScript, functions are fundamental building blocks that encapsulate


code for performing specific tasks or calculating values.

They are defined with parameters and can be invoked with arguments to
execute the enclosed statements.

Functions help organize code into manageable, reusable segments,


enhancing modularity and readability of applications.

15) Answer to: What is a parameter variable?

A parameter variable in JavaScript is defined within the parentheses of a


function declaration. It acts as a placeholder for the values that are passed
to the function when it is called. These values allow customization of the
function’s execution based on different inputs.

16) Answer to: What are the two reasons to create a function?

10
There are two primary reasons to create a function in JavaScript: to
perform a specific action or to calculate and return a value.

If a function does not explicitly return a value using the return keyword,
JavaScript automatically returns undefined by default.

11
Section 3: JavaScript Operators

17) What is an expression in JavaScript?

18) What arithmetic operators are available in JavaScript?

19) How would I increment the following variable?


let num = 1;

20) What does the single equal sign stand for in JavaScript?

21) What are the comparison operators in JavaScript?

22) What is loose equality?

23) What is strict equality?

24) What is the ternary operator?

25) What is the value stored in the variable, customerType?


let points = 110;
const customerType = points > 100 ? 100 ? ‘gold’ : ‘silver’;

26) What are the logical operators?

27) Are the results of logical expressions always true or false?

28) What are the falsy values?

29) Consider the expression, what will be stored in the constant?


let name = ‘test’;
const result = false || name;

12
Section 3: Answers

17) Answer to: What is an expression in JavaScript?

An expression in JavaScript is something that produces a value. An


expression goes on the right side of a variable assignment.

18) Answer to: What arithmetic operators are available in JavaScript?

In JavaScript, arithmetic operators perform common mathematical


operations. These include addition (+), subtraction (-), multiplication (*),
division (/), and modulo (%) which calculates the remainder of a division.

Additionally the exponentiation operator (**) raises numbers to a power, as


in 2**2.

JavaScript also supports shorthand syntax for incrementing or modifying


values such as num += 1, for adding, num++ for post-increment (returns
value before incrementing) and ++num for pre-increment (increments
before returning the value).

19) Answer to: How would I increment the following variable?


let num = 1;

To increment the variable num, initialized to 1, you can use one of four
methods.

1. num = num + 1; // explicitly adds 1 to num


2. num += 1; // shorthand for adding 1 to num
3. num++; // post-increment, which returns num before adding 1
4. ++num; // pre-increment, which adds 1 to num before returning it

13
20) Answer to: What does the single equal sign stand for in JavaScript?

In JavaScript, the single equal sign (=) is used as the assignment operator.
It assigns a value to a variable and should not be confused with operators
that check for equality.

21) Answer to: What are the comparison operators in JavaScript?

In JavaScript, comparison operators are used to compare two operands,


whether values or variables, and they return a boolean value.

The main comparison operators include:

● > (greater than)


● >= (greater than or equal to)
● < (less than)
● <= (less than or equal to)

22) Answer to: What is loose equality?


Loose equality (==) compares values regardless of types following these
steps:

1. If both values are either null or undefined, return true


2. Convert all booleans to numbers
true converts to 1 and false converts to 0
3. If comparing a number to a string, convert the string to a number
4. If comparing an object to a string, convert the object using its
toString() or valueof() methods
5. If the types are the same, follow the same rules as strict equality.

In general strict equality (===) should be preferred due to it being easier to


predict.

However loose equality can be useful for checking against null and
undefined at once with the value == null.

14
23) Answer to: What is strict equality?

A JavaScript equality operator using ===.

Strict equality compares both values and types following these steps:

1. If either value is NaN, return false


2. If the values have different types, return false
3. If both values are null, or both values are undefined, return true
4. If both values are objects, return true if they are the same object.
False otherwise.
5. If both values are of the same primitive type, return true if the values
are the same. False otherwise.

24) Answer to: What is the ternary operator?

The ternary operator in JavaScript is a shorthand for conditional


statements. It uses a question mark (?) to separate the condition from the
outcomes.

Following the condition, two values are provided: the first is returned if the
condition is true, and the second (after a colon) is returned if the condition
is false.

It’s structured as: condition ? valueIfTrue : valueIfFalse

25) Answer to: What is the value stored in the variable, customerType?
let points = 110;
const customerType = points > 100 ? 100 ? ‘gold’ : ‘silver’;

The constant value, customerType, would hold the value of ‘gold’.

26) Answer to: What are the logical operators?

In JavaScript, logical operators are used to evaluate multiple conditions or


manipulate boolean values.

15
These include:

● || (OR operator) which returns true if at least one operand is true


● && (AND operator) which returns true only if all operands are true
● ! (NOT operator) which negates the truth value of its operand
● ?? (Null Coalescing operator) which returns its right-hand operand
when the left-hand operand is null or undefined

27) Answer to: Are the results of logical expressions always true or false?

In JavaScript, the results of logical expressions are not always strictly


boolean. Instead the language uses ‘truthy’ and ‘falsy’ values to determine
outcomes.

Falsy values include:


● undefined
● null
● 0
● false
● “” (the empty string)
● NaN

All other values are considered truthy.

JavaScript employs short-circuit evaluation:

With the OR (||) operator, it returns the first truthy operand it encounters.

With the AND (&&) operator, it returns the last operand if all are truthy
or the first falsy value it encounters.

This means the returned value may not be a boolean but the actual
operand evaluated.

16
28) Answer to: What are the falsy values?

The falsy values include:

● undefined
● null
● 0
● false
● “” (the empty string)
● NaN

29) Answer to: Consider the expression, what will be stored in the constant?
let name = ‘test’;
const result = false || name;

The value stored in the constant result would be the string, ‘test’

17
Section 4: Control Flow

Questions

30) What is the if-else statement?

31) What is a switch-case statement and when would you use it?

32) What is a for loop and what is the syntax for it?

33) What is a while loop and what is the syntax for it?

34) What are the similarities and differences between the for loop and the while
loop?

35) What is a do-while loop?

36) What are infinite loops?

37) What is the for-in loop?

38) What is the for-of loop?

39) What is the break statement? What is the continue statement?

18
Section 4: Answers

30) Answer to: What is the if-else statement?

An if-else statement in JavaScript is a control flow construct used to


execute different blocks of code based on certain conditions. It checks a
specified condition: if the condition is true, it executes the block of code
following the “if”.

If the condition is false, it executes the code after the else (if present). This
allows for conditional execution of code segments within applications.

31) Answer to: What is a switch-case statement and when would you use it?

A switch-case statement in JavaScript offers a streamlined method for


performing multiple equality comparisons. It’s used as an alternative to
multiple if-else statements when decisions are based solely on a single
variable’s equality to different values.

In a switch-case, the variable is compared against several ‘case’ values


and the code block under the matching case is executed.

This structure makes the code more readable and organized, especially
when dealing with many conditions.

32) Answer to: What is a for loop and what is the syntax for it?

A for loop in JavaScript is a control structure used to repeatedly execute a


block of code a specific number of times.

The syntax includes three parts:


● initialization (where you set your loop counter)
● a condition (which must be true for the loop to continue)
● increment or decrement statement (which updates the loop counter
after each iteration)

19
it is structured as follows

for (initialization; condition; increment/decrement) {


// code block to be executed
}

33) Answer to: What is a while loop and what is the syntax for it?

A while loop in JavaScript continuously executes a block of code as long


as a specified condition remains true.

It’s ideal when the number of iterations is not predetermined but instead
depends on dynamic conditions during runtime.

The syntax is simple:

while (condition) {
// code block to execute
}

To avoid infinite loops, ensure that the condition eventually becomes false.

For example:

let sum = 0;
while (sum < 50) {
console.log(sum);
sum += 5;
}

In this example, the loop executes until sum reaches 50, incrementing sum
by 5 in each iteration.

20
34) Answer to: What are the similarities and differences between the for loop
and the while loop?

Similarities:
1. Purpose: Both loops are used to repeat a block of code multiple
times.
2. Control Structure: They both require a condition to continue
execution; the loop runs as long as the condition remains true.

Differences:

1. Initialization and Incrementing:

● For Loop: Typically includes initialization, condition, and


incrementing/decrementing all in one one, making it suitable for
cases where the number of iterations is known beforehand.

● While Loop: Does not inherently include initialization or


incrementing/decrementing. These must be handled manually,
making it more flexible for situations where the number of iterations
is not determined in advance.

2. Use Case

● For Loop: Ideal for iterating over arrays or executing a block of code
a specific number of times when the counter is explicitly needed.

● While Loop: Better suited for scenarios where the loop needs to
continue until a certain condition changes, often used in situations
involving event listeners or waiting for a specific state.

In summary, while both loops serve the purpose of repeating code, the for
loop is generally preferred when the number of iterations is known and
involves straightforward incrementing, while the while loop is chosen for
less predictable looping conditions.

21
35) Answer to: What is a do-while loop?

A do-while loop in JavaScript is a control structure that ensures the code


inside the loop runs at least once before the condition is tested. Unlike a
regular while loop, which tests the condition before executing the block of
code, a do-while loop checks the condition after the code has executed. If
the condition is true, the loop continues, if false, it stops.

Syntax:

do {
// code block to execute
} while (condition);

This setup is particularly useful when you need the loop to run at least
once, regardless of whether the condition is initially true or not.

36) Answer to: What are infinite loops?

An infinite loop occurs when the terminating condition of a loop is never


met, causing the loop to execute indefinitely.

This can happen in any type of loop, such as a for, while, or do-while loop,
if the condition to exit the loop is not properly configured or updated during
the iterations.

Example of an infinite loop in JavaScript:

while (true) {
console.log(“This loop will run forever.”);
}

In this example, the loop will continue endless because the condition (true)
never changes to false.

22
Infinite loops can cause programs to freeze or crash, so they’re usually
avoided unless intentionally used for specific reasons, like waiting for
external input to terminate the loop.

37) Answer to: What is the for-in loop?

The for-in loop in JavaScript is specifically designed to iterate over the


properties of an object.

It provides a simple way to traverse through all enumerable properties of


an object, which are those properties whose internal ‘enumerable’ flag is
set to true.

Syntax:

for (const key in object) {


console.log(key, object[key]);
}

Example:

const person = { name: ‘Alice’, favoriteColor: ‘blue’ };


for (const key in person)
console.log(key, person[key]); // outputs each property and value

In this example, the for-in loop iterates over each property in the person
object, logging the property name, key, and its corresponding value,
person[key].

This loop is particularly useful for objects where you need to examine each
property but do not need to work with the actual structure or order of the
properties.

23
38) Answer to: What is the for-of loop?

The for-of loop in JavaScript is used to iterate over iterable objects such as
arrays, strings, Maps, NodeLists, and more. It provides a straightforward
way to access each item in these iterables directly.

Syntax:

for (const item of iterable) {


console.log(item);
}

Example:

const colors = [“red”, “blue”, “green”];


for (const color of colors) {
console.log(color); // outputs each color in the array
}

In this example, the for-of loop iterates through each element in the colors
array, making it ideal for cases where you need to loop through elements
of an array or other iterable objects without accessing their indices.

This loop is particularly useful for its readability and ease of use when
processing collections of data.

39) Answer to: What is the break statement? What is the continue
statement?

The break statement is used to immediately exit a loop, such as a for,


while, or do-while loop or to exit a switch case before it completes its
normal execution.

When a break is encountered inside a loop, the loop stops running and the
flow of control moves to the statement immediately following the loop.

24
The continue statement skips the current iteration of the loop and proceeds
with the next iteration. It is used when you want to skip certain conditions
within the loop but continue looping over other elements.

In summary, break exists the loop entirely, while continue skips to the next
iteration of the loop, both helping to control the flow of loops based on
specific conditions.

25
Section 5: JavaScript Objects

Questions

40) What is the purpose of JavaScript objects?

41) What are factory functions?

42) What are constructor functions?

43) Explain in your own words, how are objects dynamic?

44) What is the constructor property?

45) Explain how functions are objects in JavaScript?

46) What are primitive values and what are they passed by?

47) What are object values and what are they passed by?

48) How can you enumerate over the properties of an object?

49) How would you make a clone of an object?

50) How would you make a deep clone of a nested object?

51) What are some of the methods that the built-in Math class has?

52) How would you generate a random number between 1 and 100?

53) Name some of the methods in the string class?

54) What are template literals?

26
Section 5: Answers

40) Answer to: What is the purpose of JavaScript objects?

JavaScript objects store key-value pairs. Their purpose is to store state


and behavior.

State is represented by properties and behavior is represented by


functions within the objects. When we specify a function within an object,
we call it a method.

41) Answer to: What are factory functions?

Factory functions are functions in JavaScript that are used to create and
return new objects.

These functions do not require the use of the new keyword, unlike
constructor functions.

Instead they simply create an object, set its properties based on the
arguments passed and then return the value.

Key Features:
● Customization: You can pass arguments to factory functions,
allowing you to customize the properties of the new object.

● Simplicity: They directly return an object literal, making them easy


to write and use.

● Naming Conventions: Factory functions are usually named using


camelCase notation

42) Answer to: What are constructor functions?

27
Constructor functions in JavaScript are special functions designed to
create and initialize objects.

They are typically used with the new keyword, which creates a new object
and sets its context, this to that object, allowing the function to define
properties and methods on it.

Key Features:

● Initialization: Constructor functions can take parameters and use


them to set the properties of the new object.

● Use of the ‘new’ keyword: When calling a constructor function, the


new keyword is used to create an instance of the object, which
inherits properties from the function’s prototype.

● Naming convention: Constructor functions are usually named using


PascalCase (uppercase first letter) to distinguish them from regular
functions.

43) Answer to: Explain in your own words, how are objects dynamic?

In JavaScript, objects are dynamic because they allow developers to add,


modify, and delete properties and methods at runtime.

This flexibility is a fundamental aspect of JavaScript’s object model.

Key Points:

● Adding Properties: You can add new properties to an object using


dot notation or square brackets after the object has been created.
This allows you to expand the object’s structure on the fly.
(dynamically)

28
● Modifying Properties: Similarly, existing properties can be modified
with new values, allowing for dynamic changes to an object’s state.

● Deleting Properties: Properties can also be removed using the


delete operator, reflecting changes in the object’s structure and
behavior as the program executes.

44) Answer to: What is the constructor property?

The constructor property in JavaScript is a property that exists on all


objects and points to the constructor function that created the instance.

It allows you to access the constructor of an object through dot notation or


square brackets, enabling you to identify or utilize the constructor function
that was used to create that specific object.

This property is particularly useful when creating new instances from


existing ones or when creating the constructor of an object dynamically.

45) Answer to: Explain how functions are objects in JavaScript?

In JavaScript, functions are a special type of object known as “function


objects.” This means that while they can be invoked or called like typical
functions, they also have properties and methods like any other object.

Key Aspects:

● Object Features: Functions can have properties added to them, can


be assigned to variables and can be passed as arguments to other
functions.

● Methods: Since functions are objects, they come with built-in


methods like: .apply(), .call(), and .bind(), which are used to control
the function’s execution context.

● First-Class Citizens: In JavaScript, functions are considered


“first-class citizens” meaning they can be treated like any other

29
value. This includes being returned from other functions and being
stored in arrays or objects.

46) Answer to: What are primitive values and what are they passed by?

In JavaScript, primitive values are the basic types of data that are not
objects and have no methods. These include types such as string, number,
boolean, null, undefined, symbol, and BigInt.

Key Characteristics:

● Immutability: Primitive values are immutable, meaning that any


operations on them result in new primitive values being created,
rather than altering the original value.

● Passed by Value: When primitive values are used as function


arguments or assigned to another variable, they are passed by
value. This means that a copy of the value is created and used,
ensuring that the original value remains unchanged.

47) Answer to: What are object values and what are they passed by?

Object values refer to instances of data structures that contain related data
and functionalities grouped together such as arrays, functions, or more
complex entities.

Unlike primitive values that are passed by value (where a copy of the value
is created and used), object values are passed by reference.

This means that when an object is passed to a function or assigned to


another variable, it’s the reference to the original object that is passed, not
a new copy.

Any changes made through this reference will affect the original object
because both the original and new variable point to the same underlying
data.

30
48) Answer to: How can you enumerate over the properties of an object?

In JavaScript, you can enumerate over the properties of an object using


several methods that provide different types of outputs:

1. Object.keys()

Returns an array of a given object’s own property names, in the


same order as we get with a normal loop.

2. Object.values()

Returns an array of a given object’s own enumerable property


values, in the order of the properties as they appear in the object.

3. Object.entries()

Returns an array of a given object’s own enumerable string-keyed


property [key, value] pairs, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).

These methods provide straightforward ways to iterate over the properties


of an object, whether you need the keys, values, or both.

49) Answer to: How would you make a clone of an object?

In JavaScript, you can clone an object using either the Object.assign()


method or the spread operator.

Both methods create a shallow clone of the original object, meaning they
copy the properties of the first level, but nested objects are still linked to
the original.

31
1. Using Object.assign()

● Object.assign() takes a target object and source objects, then copies


the properties from the source to the target and finally returns the
target object.

const original = { a: 1, b: 2 };
const clone = Object.assign({ }, original);
console.log(clone); // Outputs: { a: 1, b: 2 }

2. Using the spread operator

● The spread operator (...) provides a more concise syntax to achieve


the same result as Object.assign()

const original = { a: 1, b: 2 };
const clone = { ...original };
console.log(clone); // Outputs: { a: 1, b: 2 }

Both methods are effective for cloning objects that do not contain nested
objects. For deep cloning, where you need to clone nested objects as well,
you would need a different approach or a library like lodash that can
handle deep cloning.

50) Answer to: How would you make a deep clone of a nested object?

To create a deep clone of a nested object in JavaScript, where both the


top-level and nested objects are independently copied, you can use
several method:

1. Using JSON methods

● This approach involves converting the object to a JSON string


and then parsing that string back into a new object. It’s a
simple one-liner but has limitations such as not copying
functions, dates, or undefined values.

32
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
console.log(clone); // Outputs: { a: 1, b: { c: 2 } }

2. Using a utility library like Lodash

● Libraries like Lodash provide a cloneDeep method specifically


designed to handle deep cloning, including all types of values.

const _ = require(‘lodash’);
const original = { a: 1, b: { c: 2 } };
const clone = _.cloneDeep(original);
console.log(clone); // Outputs: { a: 1, b: { c: 2 } };

These methods are generally used because they handle various data
types and complexities within objets effectively, although the JSON
methods have some drawbacks in terms of data type compatibility.

51) Answer to: What are some of the methods that the built-in Math class
has?

The built-in Math class in JavaScript provides a variety of methods for


performing common mathematical operations. Here are some of the key
methods:

1. Math.round(): Rounds a number to the nearest integer

Math.round(4.7); // Returns 5

2. Math.ceil(): Rounds a number up to the nearest integer

Math.ceil(4.1); // Returns 5

3. Math.floor(): Rounds a number down to the nearest integer

Math.floor(4.9); // Returns 4

33
4. Math.sqrt(): Returns the square root of a number

Math.sqrt(16); // Returns 4

5. Math.pow(): Returns the base to the exponent power

Math.pow(2, 3); // Returns 8

6. Math.abs(): Returns the absolute value of a number

Math.abs(-4.7); // Returns 4.7

7. Math.random(): Generates a random number between 0 (inclusive)


and 1 (exclusive)

Math.random(); // Returns a random number

8. Math.max(): Returns the largest of zero or more numbers

Math.max(1, 3, 2); // Returns 3

9. Math.min(): Returns the smallest of zero or more numbers

Math.min(1, 3, 2); // Returns 1

These methods are useful for a wide range of mathematical operations


and can be easily incorporated into various types of calculations in your
JavaScript programs.

52) Answer to: How would you generate a random number between 1 and
100?

const randomNumber = Math.floor(Math.random() * 100) + 1;

Explanation:

34
● Math.random(): generates a floating-point number between 0
(inclusive) and 1 (exclusive)
● Multiplying this value by 100 scales it to the range 0 to just under
100
● Math.floor() then rounds this number down to the nearest whole
number, resulting in a number between 0 and 99
● Adding 1 shifts this range up to 1 to 100

This method ensures that you have an equal chance of generating every
integer between 1 and 100, which wouldn’t be perfectly guaranteed with
Math.round() as Math.round() could result in 0 and 101 under certain
circumstances if not adjusted correctly.

53) Answer to: Name some of the methods in the string class?

The string class in JavaScript provides numerous methods to manipulate


and handle text. Here are some commonly used string methods:

1. .charAt(index): Returns the character at the specified index

“hello”.charAt(1); // Returns ‘e’

2. .concat(string2, string3, ...): Concatenates one or more strings to


the original

“Hello”.concat(“ “, “World!”); // Returns ‘Hello World!’

3. .includes(searchString, position): Checks if the string contains the


specified substring, returning true or false

“hello world”.includes(“world”); // Returns true

4. .indexOf(searchValue, fromIndex): Returns the index of the first


occurrence of the specified value, starting the search at fromIndex.
Returns -1 if the value is not found.

“hello world”.indexOf(“world”); // Returns 6

35
5. .toLowerCase() and .toUpperCase(): Returns the string in lower or
upper case, respectively

“Hello World”.toLowerCase(); // Returns ‘hello world’


“hello world”.toUpperCase(); // Returns ‘HELLO WORLD’

6. .slice(startIndex, endIndex): Extracts a section of a string and


returns it as a new string

“hello world”.slice(0, 5); // Returns ‘hello’

7. .split(separator, limit): Splits a string into an array of substrings by


separating the string into substrings

“hello world”.split(“ “); // Returns [‘hello’, ‘world’];

8. .trim(): Removes whitespace from both ends of a string

“ hello world “.trim(); // Returns ‘hello world’

9. .replace(searchFor, replaceWith): Replaces the specified portion


of the string with another string

“hello world”.replace(“world”, “everyone”); // Returns ‘hello everyone’

These methods are very useful for various text processing tasks in web
development, data manipulation, and many other applications where string
manipulation is required.

54) Answer to: What are template literals?

Template literals are a feature in JavaScript that allow for easier string
creation. They provide a way to construct strings that can include
embedded expressions, which are evaluated and then turned into resulting
strings.

36
Unlike regular strings, which use single quotes or double quotes, template
literals use backticks `. This allows for multiline strings and string
interpolation.

Key Features:

● Multiline Strings: You can create strings that span multiple lines
without needing to use concatenation or special characters
● String Interpolation: You can embed expressions inside the string
using `${expression}` syntax, where the expression is evaluated
and its result is included in the string.

37
Section 6: JavaScript Arrays

Questions

55) What is an array?

56) How can you add elements to the beginning of an array?

57) How can you add elements to the middle of an array?

58) How can you add elements to the end of an array?

59) How can you determine if an array contains a specific primitive value?

60) How can you check if an array includes a specific object?

61) How would you use an arrow function as the argument for the .find() array
method?

62) What is an arrow function?

63) How would you remove elements from the beginning of an array?

64) How would you remove elements from the middle of an array?

65) How would you remove elements from the end of an array?

66) How can you empty the contents of an array?


67) How would you combine arrays?

68) How would you get a slice of an array?

69) What is the spread operator and what benefits does it provide?

70) How would you iterate through the elements of an array?

38
71) How do you convert an array to a string in JavaScript?

72) How do you convert a string to an array in JavaScript?

73) How do you sort the elements of an array in ascending order?

74) How do you sort the elements of an array in descending order?

75) How do you reverse the elements of an array?

76) How would you verify that all elements in an array meet a specific condition?

77) How would you determine if at least one element in an array meets a specific
condition?

78) How is the best way to filter elements in an array?

79) What is the best method to apply a transformation to each element in an


array and assign new values?

80) What is the best approach to condense an array into a single value?

39
Section 6: Answers

55) Answer to: What is an array?

An array is a data structure in programming that stores a collection of


elements.

These elements can be of any type, such as numbers, strings, or even


other arrays. Arrays are used to organize data into a list where each
element can be accessed by its index, with indexing starting from zero.

Key Features:

● Ordered: Elements in an array are stored in a specific order and can


be accessed using their position (index) in the array

● Accessible by Index: You can retrieve any element of an array by


referring to its index number

● Mutable: Arrays in many programming languages, including


JavaScript, are mutable, meaning that their elements can be
modified or replaced after the array is created.

56) Answer to: How can you add elements to the beginning of an array?

To add elements to the beginning of an array in JavaScript, you can use


the unshift() method.

This method modifies the original array by inserting the specified elements
at the start and returns the new length of the array.

Example:

let numbers = [2, 3, 4];


numbers.unshift(1); // Adds 1 at the beginning of the array
console.log(numbers); // Outputs: [1, 2, 3, 4]

40
So in this example, unshift(1) adds the number 1 to the beginning of the
numbers array. You can also add multiple elements at once by passing
more than one argument to unshift.

57) Answer to: How can you add elements to the middle of an array?

To add elements to the middle of an array in JavaScript, you can use the
splice() method. This versatile method allows you to insert elements at any
position within the array and it can also be used to remove elements if
needed.

How to use splice() to add elements:

● The first argument specifies the start index where new elements
should be added

● The second argument is the number of elements to remove (set this


to 0 if you don’t want to remove any elements)

● The subsequent arguments are the elements you want to add

Example:

let fruits = [‘Apple’, ‘Banana’, ‘Mango’];


// Adds ‘Orange’ and ‘Peach’ between ‘Apple’, and ‘Banana’
fruits.splice(1, 0, ‘Orange’, ‘Peach’);
console.log(fruits);

In this example, splice(1, 0, ‘Orange’, ‘Peach’) is called on the fruits array.

The method starts at index 1 (right after ‘Apple’, removes 0 elements, and
then adds ‘Orange’, and ‘Peach’ at that position.

This effectively inserts the new elements into the middle of the array
without removing any existing elements.

41
58) Answer to: How can you add elements to the end of an array?

To add elements to the end of an array in JavaScript, you can use the
.push() method. This method appends one or more elements to the end of
an array and returns the new length of the array.

Example:

let numbers = [1, 2, 3];


numbers.push(4); // Adds 4 to the end of the array
console.log(numbers); // Outputs: [1, 2, 3, 4]

In this example, push(4) adds the number 4 to the end of the numbers
array.

You can add multiple elements at once by passing more arguments to


push().

This method is straightforward and commonly used to expand arrays


dynamically.

59) Answer to: How can you determine if an array contains a specific
primitive value?

To determine if an array contains a primitive value in JavaScript, you can


use the includes() method. This method checks if the specified value exists
in the array and returns true if it does and false otherwise.

You could also use the .indexOf() method and ensure that the index is not
equal to -1 as a way to determine if the element is found.

60) Answer to: How can you check if an array includes a specific object?

To check if an array includes a specific object in JavaScript, you typically


use the includes() method for primitive values. However, since object
reference types, includes() will only find an object if the reference matches
exactly. For checking if an object with specific properties exists in an array,

42
you would need a different approach, such as using the some() method,
which can check based on a condition.

Example using some() for objects:

const objects = [{ id: 1, name: ‘Alice’ }, { id: 2, name: ‘Steven’ }];


const hasObject = objects.some(obj => obj.id === 1);
console.log(hasObject); // Outputs: true

In this example, some() iterates over the array and uses a function to
check if any object has an id of 1. This method returns true as soon as it
finds a matching object, making it efficient for this purpose.

61) Answer to: How would you use an arrow function as the argument for
the .find() array method?

You can use an arrow function as the argument for the .find() method by
passing it directly within the method call.

For example:

const array = [1, 2, 3, 4, 5];


const result = array.find(element => element > 3);
console.log(result); // Outputs: 4

62) Answer to: What is an arrow function?

A JavaScript arrow function is a concise syntax for writing function


expressions, using the => notation. It does not have its own ‘this’ context
and cannot be used as a constructor.

const add = (param1, param2) => {


return param1 + param2;
}

// Could simplify to be the following since the code block is just one line.
const add = (param1, param2) => param1 + param2;

43
63) Answer to: How would you remove elements from the beginning of an
array?

You can remove elements from the beginning of a JavaScript array using
the shift() method.

const array = [1, 2, 3];


array.shift(); // Removes the first element
console.log(array); // Outputs: [2, 3]

64) Answer to: How would you remove elements from the middle of an
array?

You can remove elements from the middle of a JavaScript array using the
slice() method. Here’s how it works:

1. The first argument specifies the starting index of the element you want to
remove.
2. The second argument specifies the number of elements to remove.
3. Any additional arguments represent elements you want to add to the array.

For example:

const array = [1, 2, 3, 4, 5];


array.splice(2, 1); // Removes one element at index 2
console.log(array); // Outputs: [1, 2, 3, 4, 5]

65) Answer to: How would you remove elements from the end of an array?

You can remove elements from the end of a JavaScript array using the
pop() method.

For example:

const array = [1, 2, 3];


array.pop(); // Removes the last element
console.log(array); // Outputs: [1, 2]

44
66) Answer to: How can you empty the contents of an array?

You can empty the contents of an array in several ways:

1. Assign it to a new empty array

let array = [1, 2, 3];


array = [];

2. Set its length property to 0

let array = [1, 2, 3];


array.length = 0;

3. Use the splice() method

let array = [1, 2, 3];


array.splice(0, array.length);

67) Answer to: How would you combine arrays?

You can combine JavaScript arrays using the concat() method or the
spread operator. Here are examples of both:

1. Using concat()

const array1 = [1, 2, 3];


const array2 = [4, 5, 6];
const combined = array1.concat(array2);
console.log(combined); // Outputs: [1, 2, 3, 4, 5, 6]

2. Using the spread operator


const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = [...array1, ...array2];
console.log(combined); // Outputs: [1, 2, 3, 4, 5, 6]

45
68) Answer to: How would you get a slice of an array?

You can get a slice of an array using the slice() method. This method takes
two arguments:
● the start index
● the end index (exclusive, not included in the slice)

For example:

const array = [1, 2, 3, 4, 5];


const slice = array.slice(1, 3);
console.log(slice); // Outputs: [2, 3]

69) Answer to: What is the spread operator and what benefits does it
provide?

The spread operator (...) in JavaScript allows you to expand elements of


an array or object. It makes it easy to copy, merge, or pass elements.

Benefits:

1. Copying Arrays or Objects

const array1 = [1, 2, 3];


const array2 = [...array1]; // Copies array1

2. Merging Arrays

const array1 = [1, 2];


const array2 = [3, 4];
const merged = [...array1, ...array2]; // Combines array1 and array2
// Can add elements in the middle
const mergedArrayWithMiddleElement = [...array1, 5, ...array2];

3. Passing Elements to functions

46
const elements = [1, 2, 3];
// Passes array elements are individual arguments
console.log(Math.max(...numbers));

The spread operator simplifies these tasks and makes the code more
readable.

70) Answer to: How would you iterate through the elements of an array?

You can iterate through the elements of an array using the for-of loop or
the .forEach() method.

1. Using for-of loop

const array = [1, 2, 3];


for (const element of array) {
console.log(element);
}
// Outputs: 1, 2, 3

2. Using .forEach() method

const array = [1, 2, 3];


array.forEach(element => {
console.log(element);
});
// Outputs: 1, 2, 3
Both methods will go through each element in the array and let you do
something with it, like logging it to the console.

71) Answer to: How do you convert an array to a string in JavaScript?

You can convert an array to a string in JavaScript using the join() method.
This method combines all the elements of an array into a single string,
separated by a specified separator.

For example:

47
const array = [1, 2, 3];
const string = array.join(“, “);
console.log(string); // Outputs: “1, 2, 3”

72) Answer to: How do you convert a string to an array in JavaScript?

You can convert a string to an array in JavaScript using the split() method.

This method splits the string into an array of substrings based on a


specified separator.

For example:

const string = “1, 2, 3”;


const array = string.split(“, “);
console.log(array); // Outputs: [“1”, “2”, “3”]

73) Answer to: How do you sort the elements of an array in ascending
order?

You can sort the elements of an array in ascending order using the sort(0
method.

const array = [3, 1, 4, 1, 5];


array.sort((a, b) => a - b);
console.log(array); // Outputs: [1, 1, 3, 4, 5]

The sort() method sorts the array in place.

The comparison function (a, b) => a - b


ensures the array is sorted in ascending order.

The sort() method sorts by ascending order by default so you can call
.sort() without any arguments to sort an array of primitive values in
ascending order.

48
74) Answer to: How do you sort the elements of an array in descending
order?

You can sort the elements of an array in descending order using the sort()
method with a comparison function.

const array = [3, 1, 4, 1, 5];


array.sort((a, b) => b - a);
console.log(array); // Outputs: [5, 4, 3, 1, 1]

75) Answer to: How do you reverse the elements of an array?

You can reverse the elements of an array using the reverse() method.

const array = [1, 2, 3];


array.reverse();
console.log(array); // Outputs: [3, 2, 1]

The reverse() method changes the order of the elements in the array into
the opposite direction.

76) Answer to: How would you verify that all elements in an array meet a
specific condition?

To verify that all elements in an array meet a specific condition, you can
use the every() method.

This method checks each element in the array and returns true only if all
elements satisfy the condition.

let array = [1, 2, 3, 4];


let conditionMet = array.every(element => element > 0);

In this example, conditionMet will be true because all elements in the array
are greater than 0.

49
77) Answer to: How would you determine if at least one element in an array
meets a specific condition?

To determine if at least one element in an array meets a specific condition,


you can use the some() method. This method checks each element in the
array and returns true if at least one element satisfies the condition.

let array = [1, 2, 3, 4];


let conditionMet = array.some(element => element > 2);

78) Answer to: How is the best way to filter elements in an array?

To filter elements in a JavaScript array, you can use the filter() method.
This method checks each element of the array with the function you
provide.

If the function returns true, the element is kept in the new array.

let elements = [1, 2, 3, 4, 5, 6];


let filteredNumbers = numbers.filter((number) => {
return number > 3;
});
console.log(filteredNumbers); // Output: [4, 5]

In the above code snippet, the filter() method kept only the numbers
greater than 3.

79) Answer to: What is the best method to apply a transformation to each
element in an array and assign new values?

To transform each element in a JavaScript array and assign new values, you can
use the map() method.

50
This method goes through each element of the array, applies a function to it, and
creates a new array with the results.

let numbers = [1, 2, 3, 4, 5, 6];


let squaredNumbers = numbers.map(number => number * number);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

80) Answer to: What is the best approach to condense an array into a single
value?

To condense an array into a single value, you can use the reduce() method
in JavaScript.

This method processes each element of the array along with an


accumulator, which holds the combined result as it iterates through the
array.

let numbers = [1, 2, 3, 4, 5, 6];


let sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Outputs: 15

In this code, the reduce() method adds up all the numbers in the array,
resulting in a single sum value. The 0 after the function is the starting value
for the accumulator.

51
Section 7: JavaScript Functions

Questions

81) What are function declarations?

82) What are function expressions?

83) What is hoisting?

84) If you don’t supply an argument for a function that expects a parameter, what
would the default value of that parameter variable be?

85) What happens if a function is called with fewer arguments than it expects to
receive?

86) How can you allow a function to accept a varying number of arguments?

87) What is the rest operator?

88) What are default parameters?

89) How do the get and set keywords work in JavaScript object literals?

90) What are try-catch blocks?

91) What is the difference between global scope and local scope?

92) What is the difference between the let keyword and the var keyword?

93) How would you explicitly set the value of the this keyword for a function or
method?

52
Section 7: Answers

81) Answer to: What are function declarations?

A function declaration in JavaScript is a way to define a function that


specifies the function’s name, any parameters it takes, and the code it
executes.

function nameOfFunction(parameter1, parameter2) {


// code to execute
}

When you declare a function this way, you can call it anywhere in your
script, even before the point at which it’s defined, due to JavaScript’s
hoisting features.

This means JavaScript moves function declarations to the top of their


containing scope before code execution.

82) Answer to: What are function expressions?

A function expression in JavaScript is a way to define a function by


assigning it to a variable.

Unlike function declarations, function expressions are not hoisted, which


means you can only use them after you’ve defined them.

const myFunction = function(parameter1, parameter2) {


// Code to execute
};

This creates a function that you can call using the variable name
myFunction.

You can also define function expressions using arrow syntax, which is a
shorter way to write functions.

53
const myFunction = (parameter1, parameter2) => {
// Code to execute
}

Both methods store the function in a variable, which you can then use to
execute the function.

83) Answer to: What is hoisting?

Hoisting in JavaScript is a behavior where variable and function


declarations are moved to the top of their containing scope during the
compilation phase.

This means you can use functions and variables before you declare them
in the code.

console.log(myVar); // undefined
var myVar = 5;

Here myVar is declared later in the code, but due to hoisting, the
declaration is moved to the top, making the variable available throughout
the scope.

However, the assignment (value) remains in its original place. So when


myVar is logged before its assignment, it shows undefined.

In the case of functions

myFunction(); // works fine


function myFunction() {
console.log(“Hello world!”);
}

The entire function declaration is hoisted, allowing it to be called before its


definition in the code.

54
84) Answer to: If you don’t supply an argument for a function that expects a
parameter, what would the default value of that parameter variable be?

If you don’t supply an argument for a function that expects a parameter,


the default value of that parameter will be undefined.

85) Answer to: What happens if a function is called with fewer arguments
than it expects to receive?

If a function is called with fewer arguments than it expects, the missing


arguments will have the value undefined.

86) Answer to: How can you allow a function to accept a varying number of
arguments?

You can allow a function to accept a varying number of arguments by using


the rest operator (...).

This lets you collect all the extra arguments into an array.

function myFunction(...args) {
console.log(args);
}

In this function, args will be an array containing all the arguments passed
to the function.

87) Answer to: What is the rest operator?

The rest operator (...) in JavaScript is used to collect multiple arguments


into an array.

This way, a function can accept any number of arguments.

function myFunction(...args) {
console.log(args);
}

55
Here, args will be an array containing all the arguments passed to
myFunction.

88) Answer to: What are default parameters?

Default parameters in JavaScript are values that a function uses if no


arguments are provided for those parameters.

For example:

function greet(name = “Guest”) {


console.log(`Hello ${name}`);
}

In this function, if you don’t provide a name, it will use “Guest” as the
default value.

89) Answer to: How do the get and set keywords work in JavaScript object
literals?

In JavaScript object literals, the get keyword is used to define a getter


method, which is a function that gets the value of a property.

The set keyword is used to define a setter method,. which is a function that
sets the value of a property

For example:

let person = {
firstName: “Steven”,
lastName: “Garcia”,
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(name) {
[this.firstName, this.lastName] = name.split(“ “);

56
}
}

Here fullName is a getter that returns the full name and a setter that splits
the full name and assigns the first and last names.

90) Answer to: What are try-catch blocks?

Try-catch blocks in JavaScript are used to handle errors in your code.

The try block contains the code that might throw an error and the catch
block contains the code that runs if an error occurs.

This way, your program can handle errors gracefully without crashing.

For example:

try {
// Code that might cause an error
let result = riskyFunction();
} catch (error) {
// Code to handle the error
console.log(“An error occurred: ”, error);
}

If riskyFunction throws an error, the catch block will run and display a
message.

91) Answer to: What is the difference between global scope and local
scope?

The difference between global scope and local scope is about where
variables are accessible in your code.

● Global scope: Variables declared outside of any function are in the


global scope. They can be accessed from anywhere in your code.

57
let globalVar = “I am global”;

function example() {
console.log(globalVar); // Can access globalVar here
}

● Local scope: Variables declared inside a function are in the local


scope. They can only be accessed within that function.

function example() {
let localVar = “I am local”;
console.log(localVar); // Can access localVar here
}

console.log(localVar); // Error, localVar is not defined

In summary, global scope is accessible everywhere, while local scope is


limited to the function where the variable is declared.

92) Answer to: What is the difference between the let keyword and the var
keyword?

The difference between the let keyword and the var keyword in JavaScript
is mainly about scope and hoisting.

● Scope
○ var is function-scoped, which means it is only limited to the
function where it’s declared
○ let is block-scoped,. which means it is limited to the block (like
inside an if statement or a loop) where it’s declared

if (true) {
var x = 10;
let y = 20;
}

console.log(x); // 10 (var is accessible here)

58
console.log(y); // Error (let is not accessible here)

● Hoisting
○ Variables declared with var are hoisted to the top of their
scope and initialized with undefined
○ Variables declared with let are also hoisted but not initialized
so accessing them before declaration causes an error

console.log(a); // undefined
var a = 5;

console.log(b); // Error
let b = 10;

In summary, let provides better control over variable scope and avoids
some issues that var can cause.

93) Answer to: How would you explicitly set the value of the this keyword for
a function or method?

You can explicitly set the value of the this keyword for a function or method
using call, apply, or bind.

● call: Calls a function with a given this value and individual


arguments.

function greet() {
console.log(`Hello ${this.name}`);
}

let person = { name: “Steven” };


greet.call(person); // “Hello Steven”

● apply: Similar to call but takes an array of arguments

function greet(greeting) {

59
console.log(`${greeting} ${this.name}`);
}

let person = { name: “Steven” };


greet.apply(person, [“Hi”]); // “Hi Steven”

● bind: Creates a new function with a given this value, which can be
called later

function greet() {
console.log(`Hello ${this.name}`);
}

let person = { name: “Steven” };


let greetPerson = greet.bind(person);
greetPerson(); // “Hello Steven”

In summary, call and apply invoke the function immediately with a specific
this value, while bind creates a new function that can be called later with
that this value.

60

You might also like