JavaScript Unlocked Mastering the Language of the Web Free PDF Guide answering top JavaScript Questions

LEARN JAVASCRIPT

🚀 Elevate Your JavaScript Skills! 💻🔁

Common JavaScript Questions with Answers explained

JavaScript QuickStarter Guide

Variables and Scoping

What does the let keyword in JavaScript signify?

The let keyword in JavaScript is used to declare a block-scoped local variable, optionally initializing it to a value. This is different from the var keyword, which declares a variable globally or locally to an entire function regardless of block scope.

Example:

let x = 10;

if (true) {

  let x = 20;  // Here x is 20

  console.log(x);

}

console.log(x);  // Here x is 10

Tips:

Use let for variables that are intended to be re-assigned.

let provides block scoping, which can prevent several common bugs in JavaScript.

Not a primitive data type in JavaScript

JavaScript has several primitive data types: String, Number, BigInt, Boolean, Undefined, Symbol, and Null. Any type that is not among these is not considered a primitive. For example, Object is not a primitive data type.

Tips:

Primitive types in JavaScript are immutable and passed by value.

Understand the difference between primitives and objects (non-primitives), as this affects how you manipulate these types in your code.

What is the correct syntax to create an array in JavaScript?

Arrays in JavaScript can be created using the array literal notation or the Array constructor.

Example:

let arrayLiteral = [1, 2, 3];

let arrayConstructor = new Array(1, 2, 3);

Tips:

Prefer the array literal syntax as it is more concise and less error-prone.

Remember that arrays in JavaScript are dynamic and can store elements of different types.

How do you declare a JavaScript variable that cannot be reassigned?

The const keyword in JavaScript is used to declare a variable that cannot be reassigned. However, note that if the variable is an object or array, its properties or elements can still be modified.

Example:

const x = 10;

// x = 20; // This will throw an error

const obj = { key: ‘value’ };

obj.key = ‘newValue’; // This is allowed

Tips:

Use const for variables that you know will not need to be re-assigned.

const also provides block scoping similar to let.

What is the correct way to write a JavaScript array?

As mentioned earlier, the correct way to write an array in JavaScript is using array literals or the Array constructor. The array literal notation is preferred for its simplicity and readability.

Example:

let fruits = [“Apple”, “Banana”, “Cherry”];

Tips:

Arrays can be modified after creation: you can add, remove, or change elements.

Arrays are zero-indexed in JavaScript, meaning the first element is at index 0.

Operator is used to assign a value to a variable

The assignment operator (=) in JavaScript is used to assign values to variables.

Example:

let myVar;

myVar = 5;

Tips:

Be aware of the difference between the assignment operator (=) and the equality operators (== and ===).

JavaScript also provides compound assignment operators like +=, -=, etc., which combine arithmetic operations with assignment.

Functions and Arrow Functions

JavaScript’s arrow functions

Arrow functions, introduced in ES6, offer a concise syntax and lexically bind the this value. Key properties include:

No own this, arguments, super, or new.target bindings. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

Cannot be used as constructors (you cannot use new with arrow functions).

They don’t have a prototype property.

Suitable for non-method functions.

Example:

const add = (a, b) => a + b;

console.log(add(2, 3)); // Output: 5

Tips:

Use arrow functions for simple operations or when you need to maintain the lexical value of this.

Avoid using them as methods in objects where you need to access other properties of the object using this.

Not a valid way to declare a function in JavaScript

Invalid ways to declare a function might involve syntax errors or using reserved keywords. The standard ways to declare functions are:

Function Declaration: function myFunction() {}

Function Expression: const myFunction = function() {};

Arrow Function Expression: const myFunction = () => {};

Example of invalid declaration:

function const() {}  // ‘const’ is a reserved keyword

How can you get the total number of arguments passed to a function in JavaScript?

Use the arguments object, an array-like object, accessible inside functions that provides the number of arguments passed to the function.

Example:

function countArguments() {

  return arguments.length;

}

console.log(countArguments(1, 2, 3)); // Output: 3

Tips:

arguments works with traditional function expressions and declarations, not with arrow functions.

For arrow functions, you can use rest parameters (…args) to achieve similar functionality.

In JavaScript, what is a Callback Function?

A callback function is a function passed into another function as an argument and is expected to be executed at some point during the execution of that function.

Example:

function greeting(name, callback) {

  console.log(‘Hello ‘ + name);

  callback();

}

greeting(‘Alice’, function() {

  console.log(‘Callback invoked’);

});

Tips:

Callbacks provide a way to ensure certain code doesn’t execute until other code has already finished execution (asynchronous operations).

What is the primary use of the bind method in JavaScript?

The bind method creates a new function that, when called, has its this keyword set to the provided value. It is used to pass a specific object to a function that expects a certain context for this.

Example:

const obj = {

  value: 20,

  getValue: function() {

    return this.value;

  }

};

const getValueCopy = obj.getValue.bind(obj);

console.log(getValueCopy()); // Output: 20

Tips:

bind is particularly useful for event handlers and callbacks involving this.

Declare a class in JavaScript

Classes in JavaScript are declared using the class keyword. Classes are syntactic sugar over JavaScript’s existing prototype-based inheritance.

Example:

class MyClass {

  constructor(name) {

    this.name = name;

  }

  greet() {

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

  }

}

const obj = new MyClass(‘Alice’);

obj.greet(); // Output: Hello, Alice!

Tips:

Use classes to create objects with shared behavior (methods) and internal state (properties).

keyword is used to declare a function in JavaScript

The function keyword is used to declare a function in JavaScript.

Example:

function myFunction() {

  // Function body

}

Not a valid way to declare a function in JavaScript

As mentioned earlier, using reserved keywords or incorrect syntax results in invalid function declarations. Examples of valid declarations have been provided above.

Declare a JavaScript function

Valid ways include function declarations, function expressions, and arrow function expressions. Each has its use cases and behavior, especially regarding hoisting and this binding.

Understanding these nuances of functions and arrow functions in JavaScript is crucial for effective coding, particularly in scenarios involving callbacks, asynchronous operations, and when dealing with this within various contexts.

Array Methods and Operations

What does the unshift method do in an array?

The unshift method adds one or more elements to the beginning of an array and returns the new length of the array.

Example:

let array = [2, 3, 4];

array.unshift(1); // Returns 4

console.log(array); // [1, 2, 3, 4]

Tips:

Remember, unshift modifies the original array.

It can take multiple arguments to add multiple elements at once.

Correct method to create a new and empty array in JavaScript

The most common way to create a new and empty array is using array literals.

Example:

let newArray = [];

Tips:

Prefer array literals over new Array() due to simplicity and readability.

How can you remove a specific element from an array in JavaScript?

To remove a specific element, you can use the splice method or filter method. splice changes the original array, while filter returns a new array.

Example using splice:

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

array.splice(2, 1); // Removes the element at index 2

console.log(array); // [1, 2, 4]

Example using filter:

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

array = array.filter(element => element !== 3);

console.log(array); // [1, 2, 4]

Tips:

Use splice for in-place removal or when you need to remove items by index.

Use filter when you need to remove items by value and want to avoid modifying the original array.

What is the purpose of the Array.prototype.every() method in JavaScript?

The every method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Example:

let isBelowThreshold = (currentValue) => currentValue < 40;

let array = [1, 30, 39, 29, 10, 13];

console.log(array.every(isBelowThreshold)); // true

Tips:

every does not mutate the array and is great for validation checks.

What is the purpose of the Array.prototype.reduce() method?

The reduce method executes a reducer function on each element of the array, resulting in a single output value.

Example:

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

let sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // 10

Tips:

The reducer function takes an accumulator and a currentValue as arguments.

reduce is extremely versatile and can be used for operations like summing values or merging arrays.

Method is used to combine two or more arrays in JavaScript

The concat method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.

Example:

let array1 = [‘a’, ‘b’, ‘c’];

let array2 = [‘d’, ‘e’, ‘f’];

let newArray = array1.concat(array2);

console.log(newArray); // [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

Tips:

Use concat to merge arrays without modifying the original arrays.

What is the purpose of the Array.prototype.map() method in JavaScript?

The map method creates a new array populated with the results of calling a provided function on every element in the calling array.

Example:

let array = [1, 4, 9, 16];

let map1 = array.map(x => x * 2);

console.log(map1); // [2, 8, 18, 32]

Tips:

map is a non-mutating method and used for transforming each element in an array.

What is the purpose of the Array.prototype.filter() method in JavaScript?

The filter method creates a new array with all elements that pass the test implemented by the provided function.

Example:

let words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];

const result = words.filter(word => word.length > 6);

console.log(result); // [“exuberant”, “destruction”, “present”]

Tips:

Use filter to get a subset of the array based on a condition.

What is the purpose of the Array.prototype.indexOf() method in JavaScript?

The indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Example:

let beasts = [‘ant’, ‘bison’, ‘camel’, ‘duck’, ‘bison’];

console.log(beasts.indexOf(‘bison’)); // 1

Tips:

indexOf is useful for finding the index of an item in an array.

If the item is not found, it returns -1.

What is the purpose of the Array.prototype.includes() method in JavaScript?

The includes method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Example:

let array = [1, 2, 3];

console.log(array.includes(2)); // true

Tips:

includes is an easy way to check if an array contains a specific item.

What is the purpose of the Array.prototype.concat() method in JavaScript?

As mentioned earlier, concat is used to merge two or more arrays. This method does not change the existing arrays but returns a new array.

What is the purpose of the Array.prototype.slice() method in JavaScript?

The slice method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).

Example:

let animals = [‘ant’, ‘bison’, ‘camel’, ‘duck’, ‘elephant’];

console.log(animals.slice(2)); // [“camel”, “duck”, “elephant”]

console.log(animals.slice(2, 4)); // [“camel”, “duck”]

Tips:

slice is non-destructive and a great way to copy or extract portions of an array.

What is the purpose of the Array.prototype.reverse() method in JavaScript?

The reverse method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

Example:

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

array.reverse();

console.log(array); // [5, 4, 3, 2, 1]

Tips:

Remember, reverse modifies the array in place.

What is the purpose of the Array.prototype.every() method in JavaScript?

This was covered in an earlier explanation. It checks if all elements in the array pass a certain test.

What is the purpose of the Array.prototype.unshift() method in JavaScript?

This was also covered earlier. unshift adds one or more elements to the beginning of an array and returns the new length of the array.

These array methods are essential for effective JavaScript programming, allowing for efficient manipulation, transformation, and evaluation of array data. Understanding and using these methods properly can greatly enhance the functionality and readability of your code.

Object Manipulation and JSON

How do you create a read-only property in an object in JavaScript?

Use Object.defineProperty() to create a read-only property by setting the writable attribute to false.

Example:

const obj = {};

Object.defineProperty(obj, ‘readOnlyProperty’, {

  value: 42,

  writable: false

});

obj.readOnlyProperty = 100;

console.log(obj.readOnlyProperty); // 42

Tips:

Remember that using Object.defineProperty() allows you to control many property characteristics, such as enumerability and configurability.

Send JSON data to the server

You can use the fetch API with POST method to send JSON data to the server.

Example:

fetch(‘https://example.com/api/data’, {

  method: ‘POST’,

  headers: {

    ‘Content-Type’: ‘application/json’

  },

  body: JSON.stringify({ key: ‘value’ })

});

Tips:

Ensure the content type header is set to application/json.

Use JSON.stringify() to convert JavaScript objects to JSON strings.

Method converts a JavaScript object to a JSON string

JSON.stringify() is used to convert a JavaScript object into a JSON string.

Example:

const obj = { name: “John”, age: 30 };

const jsonString = JSON.stringify(obj);

console.log(jsonString); // ‘{“name”:”John”,”age”:30}’

How can you add a key-value pair to a JavaScript object after it has been created?

Simply use the dot notation or bracket notation to add a new key-value pair to an existing object.

Example:

const obj = { name: “John” };

obj.age = 30; // Using dot notation

obj[“country”] = “USA”; // Using bracket notation

Creating a new object in JavaScript

There are several ways to create a new object:

Using object literal: const obj = {};

Using the new Object() constructor: const obj = new Object();

Example:

const objLiteral = {};

const objConstructor = new Object();

How can you convert a JSON object to a string in JavaScript?

Use JSON.stringify() to convert an object to a JSON-formatted string.

Example:

const obj = { name: “Alice”, age: 25 };

const jsonString = JSON.stringify(obj);

Method is used to serialize an object into a JSON string in JavaScript

JSON.stringify() is used for serialization of a JavaScript object into a JSON string.

Define an object in JavaScript

The common ways to define an object in JavaScript are:

Using object literals: const obj = {};

Using the new Object() constructor.

Example:

const objLiteral = { name: “Alice”, age: 25 };

const objConstructor = new Object();

objConstructor.name = “Alice”;

objConstructor.age = 25;

How to Create a new object with the same prototype as an existing object

Use Object.create() to create a new object with the same prototype as an existing object.

Example:

const person = { isHuman: true };

const me = Object.create(person);

Tips:

Object.create() is useful for implementing inheritance in JavaScript.

Correct syntax for creating a new object in JavaScript

Both the object literal method and new Object() constructor are correct syntaxes for creating a new object in JavaScript.

These concepts are foundational for working with objects and JSON data in JavaScript, enabling you to effectively manipulate, transfer, and store complex data structures. Understanding these techniques is essential for many common web development tasks, such as API interactions and dynamic data handling.

Asynchronous Programming and Promises

What is the purpose of the async keyword in JavaScript?

The async keyword is used to declare an asynchronous function, which returns a Promise. It allows you to write promise-based code as if it were synchronous, but without blocking the execution thread.

Example:

async function fetchData() {

  return “Data fetched”;

}

fetchData().then(data => console.log(data)); // “Data fetched”

Tips:

async functions can contain zero or more await expressions.

Execution within an async function is paused until a promise is resolved or rejected.

Asynchronous requests in JavaScript

A true statement about asynchronous requests in JavaScript is that they allow the program to continue running while waiting for a response, preventing any blocking of subsequent code execution.

Example:

console.log(‘Before request’);

fetch(‘https://api.example.com/data’)

  .then(response => response.json())

  .then(data => console.log(data));

console.log(‘After request’);

Tips:

Common use cases for asynchronous requests include fetching data from a server, file operations, and timers.

JavaScript uses an event loop for handling asynchronous code execution.

What is the primary use of the async keyword before a function in JavaScript?

The primary use of the async keyword is to simplify the way we write promises. It enables the use of await within functions to pause in a non-blocking way until the promise is settled. The function execution pauses at the await expression and resumes with the resolved value of the promise.

Example:

async function getUser(userId) {

  let response = await fetch(`https://api.example.com/users/${userId}`);

  let data = await response.json();

  return data;

}

getUser(1).then(user => console.log(user));

Tips:

Use async functions to handle sequences of asynchronous operations more intuitively.

How do you create a Promise in JavaScript?

A Promise in JavaScript is created using the Promise constructor, which takes an executor function with two arguments: resolve and reject.

Example:

let promise = new Promise((resolve, reject) => {

  setTimeout(() => {

    resolve(‘Promise resolved’);

  }, 1000);

});

promise.then(result => console.log(result));

Tips:

Use promises to handle asynchronous operations like API calls, file reads, etc.

Promises have three states: pending, fulfilled, and rejected.

In JavaScript, how can you catch errors thrown during asynchronous operations?

Errors in asynchronous operations can be caught using .catch() with promises or try-catch blocks in async/await.

Example using .catch():

fetch(‘https://api.example.com/data’)

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(error => console.error(‘Error:’, error));

Example using async/await:

async function fetchData() {

  try {

    let response = await fetch(‘https://api.example.com/data’);

    let data = await response.json();

    console.log(data);

  } catch (error) {

    console.error(‘Error:’, error);

  }

}

fetchData();

Tips:

It’s important to always handle errors in asynchronous operations to prevent runtime exceptions and improve code reliability.

In async/await, try-catch provides a synchronous feel to asynchronous error handling.

Understanding these aspects of asynchronous programming and Promises is vital for developing responsive and efficient JavaScript applications, especially in environments like web browsers and Node.js where I/O operations are often non-blocking and handled asynchronously.

Event Handling and DOM Interaction

What is event bubbling in JavaScript?

Event bubbling is a mechanism where an event triggered on a DOM element propagates up the DOM tree. It means that an event on a child element will bubble up to its parent elements.

Example:

<div id=”parent”>

  <button id=”child”>Click me</button>

</div>

<script>

  document.getElementById(‘parent’).addEventListener(‘click’, () => {

    console.log(‘Parent clicked’);

  });

  document.getElementById(‘child’).addEventListener(‘click’, () => {

    console.log(‘Child clicked’);

  });

</script>

When the button is clicked, you will see logs for both the child and parent due to bubbling.

Tips:

Bubbling is the default behavior for most events in the DOM.

It allows you to implement event delegation.

What is event delegation in JavaScript?

Event delegation is a technique where instead of adding an event listener to individual elements, you add it to a parent element and use event bubbling to handle events on child elements. It’s useful for handling events on dynamically added elements or for optimizing performance by reducing the number of event listeners.

Example:

<ul id=”myList”>

  <li>Item 1</li>

  <li>Item 2</li>

  <li>Item 3</li>

</ul>

<script>

  document.getElementById(‘myList’).addEventListener(‘click’, function(e) {

    if (e.target.tagName === ‘LI’) {

      console.log(‘List item clicked:’, e.target.textContent);

    }

  });

</script>

This listens for clicks on the ul element but can respond to clicks on individual li elements.

Tips:

Use e.target to get the element that triggered the event.

Method is used to add an event listener in modern JavaScript

The addEventListener method is used to attach an event handler to a specific element.

Example:

document.getElementById(‘myButton’).addEventListener(‘click’, () => {

  console.log(‘Button clicked’);

});

Tips:

addEventListener is preferred over the older onclick method as it allows multiple event handlers on a single element and more control over event handling.

Event occurs when the user clicks on an HTML element

The click event occurs when a user clicks on an HTML element. It’s one of the most commonly used events in web applications.

Example:

<button id=”myButton”>Click me</button>

<script>

  document.getElementById(‘myButton’).addEventListener(‘click’, () => {

    alert(‘Button clicked!’);

  });

</script>

How can you stop the propagation of an event in JavaScript?

To stop the propagation of an event, use the stopPropagation method on the event object. This prevents further propagation of the current event in the capturing and bubbling phases.

Example:

<div id=”parent”>

  <button id=”child”>Click me</button>

</div>

<script>

  document.getElementById(‘parent’).addEventListener(‘click’, () => {

    console.log(‘Parent clicked’);

  });

  document.getElementById(‘child’).addEventListener(‘click’, (e) => {

    console.log(‘Child clicked’);

    e.stopPropagation(); // Stops the event from bubbling up

  });

</script>

Tips:

Use stopPropagation judiciously, as it can prevent other intended event handlers from executing.

It’s useful in scenarios where you don’t want a parent handler to be triggered after a specific action on a child element.

Understanding these concepts is crucial for handling user interactions in web applications, allowing you to create more engaging and responsive interfaces. Remember, effective event handling is key to manipulating the DOM in response to user actions.

JavaScript Syntax and Operators

How can you add a comment in a JavaScript file?

In JavaScript, you can add comments using either single-line (//) or multi-line (/* */) comment syntax.

Example:

// This is a single-line comment

let x = 5; // This comment is inline with code

/* This is a 

   multi-line comment */

let y = 10;

What does the spread operator do in JavaScript?

The spread operator (…) allows an iterable such as an array or string to be expanded in places where zero or more arguments or elements are expected. It is commonly used for array or object cloning and concatenation.

Example:

let arr1 = [1, 2, 3];

let arr2 = […arr1, 4, 5]; // [1, 2, 3, 4, 5]

How to correctly round the number 7.25 to the nearest integer in JavaScript

The Math.round() method correctly rounds a number to the nearest integer.

Example:

console.log(Math.round(7.25)); // 7

What does the !! (double exclamation point) operator do in JavaScript?

The !! operator is used to convert a value to its equivalent boolean representation.

Example:

let truthyValue = !!1; // true

let falsyValue = !!0; // false

What does the || operator represent in JavaScript?

The || operator is a logical OR. It returns the value of its first operand if it is truthy; otherwise, it returns the value of the second operand.

Example:

let result = false || ‘default’; // ‘default’

In JavaScript, what will this code typeof NaN return?

The typeof NaN returns “number”, as NaN (Not-a-Number) is a special numeric value.

Example:

console.log(typeof NaN); // “number”

What is console.log(typeof null); going to output in JavaScript?

It outputs “object”. This is a well-known quirk in JavaScript, as null is not actually an object but a primitive value.

How do you write an if statement in JavaScript?

The if statement is used to execute a block of code conditionally.

Example:

let x = 10;

if (x > 5) {

  console.log(‘x is greater than 5’);

}

What is the correct syntax for referring to an external script called script.js?

You can reference an external JavaScript file using the <script> tag with the src attribute in HTML.

Example:

<script src=”script.js”></script>

What does the === operator check in JavaScript?

The === operator is a strict equality comparison operator that checks both the value and the type of two operands.

Example:

console.log(1 === ‘1’); // false, because the type is different

How can a for loop be stopped in JavaScript?

A for loop can be stopped using the break statement.

Example:

for (let i = 0; i < 10; i++) {

  if (i === 5) {

    break; // Stops the loop

  }

  console.log(i);

}

In JavaScript, which operator is used to test if a specific property exists in an object?

The in operator checks if a property exists within an object.

Example:

let obj = { key: ‘value’ };

console.log(‘key’ in obj); // true

What is the result of “1” + 2 + 3 in JavaScript?

The result is “123”. JavaScript performs string concatenation because the first operand is a string.

JavaScript’s null value

null in JavaScript represents the intentional absence of any object value. It is often used to signify ‘nothing’, ’empty’, or ‘value unknown’.

Understanding these JavaScript syntax and operators is fundamental to effective coding, as they are the building blocks for writing any script in JavaScript. Remember, proper usage of these elements can greatly influence the readability, efficiency, and functionality of your code.

Advanced Concepts and Miscellaneous

In JavaScript, what is a truthy value?

Truthy values are those that convert to true when evaluated in a boolean context. Except for false, 0, -0, 0n, “”, null, undefined, and NaN (which are falsy), all other values are truthy.

Away to define an arrow function that returns the square of its input in JavaScript

const square = x => x * x;

How do you define a constant in JavaScript?

Use the const keyword to define a constant. The value of a constant can’t be changed through reassignment.

const PI = 3.14;

JavaScript closures 

A closure is a function that remembers its outer variables and can access them.

Default behavior of the this keyword in JavaScript functions

In a regular function, this refers to the global object (window in browsers). In a method (function within an object), this refers to the object.

Statement is used to handle exceptions in JavaScript

try…catch statements are used to handle exceptions.

try {

  // code that may throw an error

} catch (error) {

  // code to handle the error

}

Correct way to define an async function in JavaScript

async function fetchData() {

    // asynchronous code

}

One of these is a way to define a variable in JavaScript that restricts its scope to the block in which it is defined

Use let or const to define block-scoped variables.

JavaScript package manager

npm (Node Package Manager) and yarn are popular JavaScript package managers.

Method to create a deep copy of an object in JavaScript

const newObj = JSON.parse(JSON.stringify(originalObj));

Method can be used to round a number to the nearest integer in JavaScript

Math.round(7.25); // returns 7

Statement about null in JavaScript?

null is an assignment value representing “no value” or “nothing”. It’s not an object, despite what typeof returns.

How do you find the length of a string str in JavaScript?

let length = str.length;

How can you check if a variable a is less than 10 in JavaScript?

if (a < 10) {

    // do something

}

What is the correct syntax for importing a module in modern JavaScript?

import moduleName from ‘module’;

What does the static keyword do in JavaScript classes?

static defines a static method or property for a class. Static members are not accessible through class instances.

Not a valid JavaScript variable name

Names like 2name (starting with a digit) or keywords like let are invalid.

How do you stop an interval timer in JavaScript?

let timerId = setInterval(() => console.log(‘Hello’), 1000);

clearInterval(timerId);

What is the main difference between the == and === operators in JavaScript?

== is the equality operator with type coercion, while === is the strict equality operator without type coercion.

Methods can be used to send a request to a server in JavaScript

XMLHttpRequest and fetch API are commonly used.

JavaScript method can be used to check if an object is an array

Array.isArray(obj);

What will the following code return: Boolean(10 > 9)?

It will return true, as the expression 10 > 9 is true.

What is a closure in JavaScript?

A closure is a function that retains access to the outer scope in which it was created.

setTimeout() function in JavaScript

setTimeout() is used to execute a function once after a specified time interval.

How can you detect if a variable is an array in JavaScript?

Array.isArray(variable);

Method is used to remove the first element from an array and return that element

array.shift();

What is the main difference between let and const in JavaScript?

let allows reassignment, while const doesn’t. Both are block-scoped.

Not a reserved word in JavaScript

Check against the list of JavaScript reserved words. For instance, async is reserved, but myVariable is not.

Statement will correctly call a function named myFunction

myFunction();

Create an object in JavaScript

let obj = {}; // Object literal syntax

What does the delete operator in JavaScript do?

It removes a property from an object.

What is the purpose of template literals in JavaScript?

Template literals provide an easy way to create strings with embedded expressions.

What does the ?. operator signify in JavaScript?

The optional chaining operator (?.) allows you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Statements will create a copy of an object

Shallow copy: let newObj = {…oldObj};

Deep copy: let newObj = JSON.parse(JSON.stringify(oldObj));

JavaScript method is used for parsing a string to an integer

parseInt(string);

What does the map() method do in JavaScript?

map() creates a new array with the results of calling a provided function on every element in the calling array.

What is a typical use case for an anonymous function in JavaScript?

Common use cases include callbacks and IIFE (Immediately Invoked Function Expressions).

Correct method to clone an array in JavaScript

let newArray = oldArray.slice();

How do you find the character at a specific position in a string in JavaScript?

let char = str.charAt(index);

What is the use of the new keyword in JavaScript?

It creates a new instance of a user-defined object type or built-in object type.

How can you detect if a variable is an array in JavaScript?

Use Array.isArray() to check if a variable is an array.

Example:

let arr = [1, 2, 3];

console.log(Array.isArray(arr)); // true

JavaScript’s switch statement is correct

The switch statement evaluates an expression and executes code as per the case clause that matches the expression’s value.

Example:

let fruit = “apple”;

switch (fruit) {

  case “apple”:

    console.log(“Apple case”);

    break;

  default:

    console.log(“Default case”);

}

What does the finally block do in a try-catch statement?

The finally block executes after the try and catch blocks, regardless of whether an exception was thrown or caught.

Example:

try {

  // Code that may throw an error

} catch (error) {

  // Code to handle the error

} finally {

  console.log(“This will run regardless of the try / catch outcome”);

}

In JavaScript, how is a while loop started?

A while loop in JavaScript starts with the while keyword followed by a condition. The loop executes as long as the condition is true.

Example:

let i = 0;

while (i < 5) {

  console.log(i);

  i++;

}