Javascript Flashcards

Javascript interview questions

1
Q

Can you differentiate between let and var in JavaScript?

A

let and var are used for variable declaration in JavaScript, but they have key differences:
let:
Block-scoped: Variables declared with let are block-scoped, meaning they are limited to the block, statement, or expression where they are defined.
Temporal Dead Zone (TDZ): Variables declared with let are hoisted to the top of their block but remain in the TDZ until the declaration statement is encountered.
Cannot be re-declared in the same scope.
Typically used for modern JavaScript to enhance predictability and avoid unintended variable hoisting issues.
var:
Function-scoped: Variables declared with var are function-scoped, meaning they are limited to the function where they are defined. If declared outside any function, they become global variables.
Variables declared with var are hoisted to the top of their function or global scope.
Can be re-declared within the same scope.
var was traditionally used for variable declaration but has certain pitfalls related to hoisting and scoping.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain a self-invoking function.

A

A self-invoking function, also known as an Immediately Invoked Function Expression (IIFE), is a JavaScript function that is defined and invoked immediately after its creation. It is typically wrapped in parentheses and followed by another pair of parentheses to trigger its execution. The primary purposes of self-invoking functions are:
Encapsulation: They create a private scope, isolating variables and functions from the global scope, which helps prevent naming conflicts and enhances code modularity.
Initialization: They can be used to initialize variables or execute code before the rest of the program runs.
Optional:
Self-invoking functions are commonly used in scenarios where you want to create a one-time execution context or hide implementation details.
They are often used in JavaScript libraries and frameworks to create modular and encapsulated code.
Parameters can be passed to self-invoking functions by placing them inside the first set of parentheses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain NEGATIVE_INFINITY in JavaScript.

A

NEGATIVE_INFINITY is a special value in JavaScript that represents negative infinity. It is typically used to denote a value that is smaller or “less than” any other numeric value, including regular negative numbers. For example, Number.NEGATIVE_INFINITY is often the result of arithmetic operations that exceed the lower limit of representable numbers in JavaScript, indicating an unbounded, infinitely small quantity.

Optional:
NEGATIVE_INFINITY is accessible as a property of the global Number object: Number.NEGATIVE_INFINITY.
It can be used in comparisons to check if a numeric value is smaller than negative infinity.
Positive infinity is represented as POSITIVE_INFINITY (or simply Infinity) in JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the Prototype Design Pattern.

A

The Prototype Design Pattern in JavaScript is a creational design pattern that enables the creation of objects by copying an existing object, known as the prototype. It provides a blueprint for creating objects with shared behavior and properties, reducing the need for multiple class instantiations. This pattern is often used when creating similar objects with a common structure to improve efficiency and memory management.

Optional:
The prototype object serves as a template, and new objects are created by cloning this template.
It is commonly used to create objects with shared methods and properties, such as for implementing inheritance in JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Explain the use of a debugger in JavaScript?

A

A debugger in JavaScript is a tool used for inspecting and troubleshooting code during development. It helps developers identify and fix errors or bugs in their JavaScript programs. Here’s how a debugger is used:
Setting Breakpoints: Developers can place breakpoints in their code by specifying certain lines or conditions where they want the program’s execution to pause. This allows them to inspect the program’s state at that specific point.
Inspecting Variables: While the program is paused at a breakpoint, developers can examine the values of variables, objects, and expressions in the current scope. This helps in understanding how the program is behaving.
Stepping Through Code: Developers can step through the code one line at a time, either forwards or backwards, to trace the execution flow and identify the source of issues.
Watching Expressions: Developers can set up watches for specific expressions, which allows them to monitor the values of those expressions as the program executes.
Console Output: Debuggers often provide a console for developers to log messages and output, helping them understand what’s happening in the code.
Call Stack and Call Hierarchy: Debuggers can display the call stack, showing the sequence of function calls leading to the current point in the code. This helps identify how the program reached the current state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does TypeOf Operator works in JavaScript?

A

“number” for numbers.
“string” for strings.
“boolean” for booleans.
“object” for objects and arrays.
“function” for functions.
“undefined” for undefined values.
“symbol” for symbols (ES6).
Optional:
The typeof operator is useful for runtime type checking and handling values differently based on their types.
It can help prevent unexpected type-related errors in JavaScript code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How is JavaScript different from Java?

A

JavaScript and Java are two distinct programming languages with several key differences:
Type: JavaScript is a dynamically-typed language, meaning you don’t need to declare variable types. Java, on the other hand, is statically-typed, requiring variable type declarations.
Platform: JavaScript is primarily used for web development and runs in web browsers. Java is a versatile, general-purpose language used for various applications, including desktop and mobile applications.
Syntax: The syntax of JavaScript is more similar to C and C++, while Java’s syntax resembles C++.
Compilation: JavaScript is an interpreted language, executed by web browsers. Java is a compiled language, first compiled to bytecode and then executed by the Java Virtual Machine (JVM).
Inheritance: JavaScript uses prototypal inheritance, where objects can inherit properties from other objects directly. Java uses class-based inheritance with strict class hierarchies.
Usage: JavaScript is commonly used for front-end web development, whereas Java is often used in enterprise-level applications, Android app development, and server-side applications (Java EE).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

In how many ways can you create an array in JavaScript?

A

There are several ways to create an array in JavaScript:
Array Literal: By using square brackets, like const myArray = [].
Array Constructor: Using the Array constructor, such as const myArray = new Array().
Array.from(): Converting an array-like or iterable object into an array, e.g., const myArray = Array.from(iterable).
Spread Operator: Using the spread operator to create a new array by spreading elements, e.g., const myArray = […elements].
Array.of(): Creating an array from individual elements, like const myArray = Array.of(element1, element2).
Using Array Methods: Methods like map, filter, or reduce can also be used to create new arrays based on existing data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

List out the ways to get access to HTML elements through JavaScript.

A

getElementById(): By element ID.
getElementsByClassName(): By class name.
getElementsByTagName(): By HTML tag name.
querySelector(): Using CSS-style selectors.
querySelectorAll(): Selecting multiple elements with CSS-style selectors.
getElementByName(): By the name attribute (primarily for form elements).
Optional:
These methods provide powerful ways to interact with and manipulate HTML elements in the Document Object Model (DOM) using JavaScript.
Modern development often leverages the use of querySelector() and querySelectorAll() for their flexibility and compatibility with CSS selectors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are ways to define a variable in JavaScript?

A

var: Declares a variable with function or global scope (ES5).
let: Declares a variable with block scope (ES6+).
const: Declares a constant variable with block scope (ES6+).
function: Declares a function (also a variable) with function scope.
class: Declares a class with block scope (ES6+).
Optional:
The choice of declaration keyword depends on the variable’s scope and whether it will change over time.
let and const are preferred over var in modern JavaScript development due to their better scoping behavior and other advantages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What do you understand by closures in JavaScript?

A

Closures in JavaScript refer to the ability of a function to “remember” and access variables and functions from its containing scope, even after that containing scope has finished executing. They are a crucial concept in JavaScript that enables data encapsulation, private variables, and the creation of factory functions, callbacks, and more.

Optional:
Closures allow for maintaining state and preserving the scope of variables, which is essential for functions like event handlers and asynchronous operations.
They are created when a function is defined within another function, and the inner function has access to the outer function’s variables and parameters.
Closures are a powerful and versatile feature used extensively in JavaScript for various programming patterns and paradigms.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What do you understand by Cookies?

A

User Authentication: Cookies can be used to track user sessions and store authentication tokens to remember a user’s login status.
Data Persistence: They can store user preferences, such as language settings or theme choices, to provide a personalized experience.
Tracking and Analytics: Cookies can track user behavior on websites for analytics and marketing purposes.
Shopping Carts: E-commerce sites use cookies to maintain and remember the contents of a user’s shopping cart.
Session Management: Cookies help manage state and data between server and client, such as in web applications.
It’s important to note that cookies have limitations, such as size constraints and potential security concerns, which have led to the development of more advanced storage mechanisms like Web Storage and IndexedDB.

Optional:
Cookies have attributes like expiration date, domain, and path that can be set for customization.
Secure and HttpOnly flags can enhance the security of cookies.
JavaScript provides the document.cookie API for reading and writing cookies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What do you understand by JavaScript?

A

JavaScript is a versatile and widely-used programming language that is primarily used for front-end web development. It allows you to add interactivity, manipulate the Document Object Model (DOM), and create dynamic content on websites. JavaScript is an essential component of modern web development, enabling developers to build responsive and interactive web applications. It can also be used on the server-side (Node.js) to create full-stack applications.

Optional:
JavaScript is often referred to as a “client-side” scripting language because it runs in the user’s web browser.
It is an interpreted language, meaning it doesn’t require compilation before execution.
JavaScript is compatible with most web browsers, making it a cross-platform language.
Key uses of JavaScript include form validation, animation, handling user events, and making asynchronous requests to web servers (AJAX).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does the term “Transpiling” stand for in JavaScript?

A

Transpiling in JavaScript refers to the process of transforming source code from one version of JavaScript (typically newer or with additional features) into an older version or a more widely supported version. This transformation is necessary to ensure compatibility with various web browsers and runtime environments.

Optional:
Popular transpilers in JavaScript include Babel, which is commonly used to convert modern ES6+ code into ES5 for broader browser compatibility.
Transpilers are essential tools in modern web development to leverage the latest language features while supporting older browsers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a Callback in JavaScript?

A

A callback in JavaScript is a function that is passed as an argument to another function and is intended to be executed at a later time. Callbacks are commonly used for asynchronous operations, event handling, and functions that need to respond to an event or a completed task. They enable non-blocking code execution and can be used to handle tasks like data retrieval, animations, and user interactions.

Optional:
Callbacks are a fundamental concept in JavaScript and are crucial for dealing with asynchronous tasks like AJAX requests or timeouts.
Callbacks can be named functions or anonymous functions defined on the spot, offering flexibility in their usage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Hoisting in JavaScript?

A

Hoisting in JavaScript is a behavior in which variable and function declarations are moved to the top of their containing scope during the compilation phase. While the declarations are hoisted, the initializations are not. This means that you can use variables or functions before they are declared in your code, but they will only be defined at runtime where they appear in the code.
Variable declarations are hoisted with the var keyword, and function declarations are hoisted entirely.
Understanding hoisting is important to avoid unexpected behaviors and errors in your JavaScript code.

17
Q

What is NaN in JavaScript?

A

NaN stands for “Not-a-Number” in JavaScript. It is a special value that represents the result of an operation that should return a number but doesn’t. NaN is often encountered in situations like performing mathematical operations on non-numeric values or when a mathematical operation has no meaningful result.

Optional:
You can check for NaN using the isNaN() function.
When NaN is used in further mathematical operations, the result will also be NaN.
Avoiding NaN errors is important in JavaScript to ensure that numeric operations produce meaningful results.

18
Q

What is the difference between attributes and properties in JavaScript?

A

Attributes and properties in JavaScript refer to two aspects of HTML elements:
Attributes are defined in the HTML markup and represent the initial, static values of an element. They are typically set using HTML tags or attributes and do not change unless explicitly modified.
Properties are the dynamic, current values of elements as accessed and manipulated via JavaScript. They represent the real-time state of an element and can change during interactions or script execution.
Optional:
When dealing with elements in JavaScript, it’s often recommended to work with properties rather than attributes to reflect real-time changes.
Properties and attributes can have the same name for certain elements (e.g., the value of an input), but they may have different values due to JavaScript manipulation.

19
Q

What is the purpose of the ‘this’ operator in JavaScript?

A

The this operator in JavaScript is used to refer to the current object or context within which a function or method is called. It allows you to access and manipulate object properties and behavior dynamically. The specific value of this depends on how a function is invoked, whether it’s a method of an object, a standalone function, or within an event handler.

Optional:
Understanding this is crucial for working with objects, constructors, and event handling in JavaScript.
The value of this can vary and is determined at runtime based on the execution context.

20
Q

What is the reason for wrapping the entire content of a JavaScript source file in a function?

A

Wrapping the entire content of a JavaScript source file in a function is a common practice known as the “module pattern” or an “IIFE” (Immediately Invoked Function Expression). It serves several important purposes:
Encapsulation: It creates a private scope, preventing variables and functions from polluting the global scope and avoiding naming conflicts with other scripts.
Isolation: It allows for the creation of self-contained modules, making code more maintainable and reusable.
Protection: It safeguards code by minimizing external access, reducing the risk of unintended modifications.
Dependency Management: It facilitates dependency injection and enables better organization of code dependencies.
Optional:
The module pattern is a fundamental concept in JavaScript development and is widely used in various programming paradigms, such as CommonJS and ES6 Modules.
This practice can also enhance code performance by minimizing global variable lookups.

21
Q

What’s the difference between null and undefined in JavaScript?

A

null is explicitly set by a programmer to represent the absence of a value or object.
undefined typically indicates the lack of assignment or initialization.
null is a deliberate absence, while undefined is often unintentional.
For example, you might set a variable to null when you want to indicate that it should have no value.
Optional:
null is often used to release references to objects, while undefined commonly occurs when accessing nonexistent properties or missing function arguments.
Both null and undefined are falsy values in JavaScript
You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.