JavaScript for Beginners Questions and Answers
JavaScript for Beginners Questions and Answers
StevenCodeCraft.com
Questions
1) What is JavaScript?
2) What is Node?
2
Section 1: Answers
It can be used for creating front end applications, backend API services,
mobile applications, and desktop applications.
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.
3
2) Answer to: What is Node?
4
Section 2: JavaScript Variables
8) What is the difference between a primitive data type and a reference data
type?
5
Section 2: Answers
3) Answer to: What are variables? How would you create one?
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?)
6
5) Answer to: How many primitive data types are there in JavaScript?
7
The BigInt data type:
let veryLargeNumber = 543543634843634n;
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.
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.
8
10) Answer to: What is the const keyword?
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.
They are created using curly braces, { }, to define key-value pairs, where
keys represent properties and values represent data or functions.
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?
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.
They are defined with parameters and can be invoked with arguments to
execute the enclosed statements.
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
20) What does the single equal sign stand for in JavaScript?
12
Section 3: Answers
To increment the variable num, initialized to 1, you can use one of four
methods.
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.
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?
Strict equality compares both values and types following these steps:
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.
25) Answer to: What is the value stored in the variable, customerType?
let points = 110;
const customerType = points > 100 ? 100 ? ‘gold’ : ‘silver’;
15
These include:
27) Answer to: Are the results of logical expressions always true or false?
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?
● 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
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?
18
Section 4: Answers
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?
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?
19
it is structured as follows
33) Answer to: What is a while loop and what is the syntax for it?
It’s ideal when the number of iterations is not predetermined but instead
depends on dynamic conditions during runtime.
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:
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?
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.
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.
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.
Syntax:
Example:
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:
Example:
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?
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
46) What are primitive values and what are they passed by?
47) What are object values and what are they passed by?
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?
26
Section 5: Answers
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.
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:
43) Answer to: Explain in your own words, how are objects dynamic?
Key Points:
28
● Modifying Properties: Similarly, existing properties can be modified
with new values, allowing for dynamic changes to an object’s state.
Key Aspects:
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:
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.
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?
1. Object.keys()
2. Object.values()
3. Object.entries()
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()
const original = { a: 1, b: 2 };
const clone = Object.assign({ }, original);
console.log(clone); // Outputs: { a: 1, b: 2 }
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?
32
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
console.log(clone); // Outputs: { a: 1, b: { c: 2 } }
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?
Math.round(4.7); // Returns 5
Math.ceil(4.1); // Returns 5
Math.floor(4.9); // Returns 4
33
4. Math.sqrt(): Returns the square root of a number
Math.sqrt(16); // Returns 4
52) Answer to: How would you generate a random number between 1 and
100?
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?
35
5. .toLowerCase() and .toUpperCase(): Returns the string in lower or
upper case, respectively
These methods are very useful for various text processing tasks in web
development, data manipulation, and many other applications where string
manipulation is required.
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
59) How can you determine if an array contains a specific primitive value?
61) How would you use an arrow function as the argument for the .find() array
method?
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?
69) What is the spread operator and what benefits does it provide?
38
71) How do you convert an array to a string in JavaScript?
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?
80) What is the best approach to condense an array into a single value?
39
Section 6: Answers
Key Features:
56) Answer to: How can you add elements to the beginning of an array?
This method modifies the original array by inserting the specified elements
at the start and returns the new length of the array.
Example:
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.
● The first argument specifies the start index where new elements
should be added
Example:
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:
In this example, push(4) adds the number 4 to the end of the numbers
array.
59) Answer to: How can you determine if an array contains a specific
primitive value?
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?
42
you would need a different approach, such as using the some() method,
which can check based on a condition.
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:
// 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.
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:
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:
44
66) Answer to: How can you empty the contents of an array?
You can combine JavaScript arrays using the concat() method or the
spread operator. Here are examples of both:
1. Using concat()
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:
69) Answer to: What is the spread operator and what benefits does it
provide?
Benefits:
2. Merging Arrays
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.
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”
You can convert a string to an array in JavaScript using the split() method.
For example:
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.
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.
You can reverse the elements of an array using the reverse() method.
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.
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?
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.
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.
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.
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
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?
89) How do the get and set keywords work in JavaScript object literals?
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
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 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.
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.
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?
85) Answer to: What happens if a function is called with fewer arguments
than it expects to receive?
86) Answer to: How can you allow a function to accept a varying number of
arguments?
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.
function myFunction(...args) {
console.log(args);
}
55
Here, args will be an array containing all the arguments passed to
myFunction.
For example:
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?
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.
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.
57
let globalVar = “I am global”;
function example() {
console.log(globalVar); // Can access globalVar here
}
function example() {
let localVar = “I am local”;
console.log(localVar); // Can access localVar here
}
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;
}
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.
function greet() {
console.log(`Hello ${this.name}`);
}
function greet(greeting) {
59
console.log(`${greeting} ${this.name}`);
}
● bind: Creates a new function with a given this value, which can be
called later
function greet() {
console.log(`Hello ${this.name}`);
}
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