Javascript Flashcards
Javascript interview questions
Can you differentiate between let and var in JavaScript?
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.
Explain a self-invoking function.
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.
Explain NEGATIVE_INFINITY in JavaScript.
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.
Explain the Prototype Design Pattern.
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.
Explain the use of a debugger in JavaScript?
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 does TypeOf Operator works in JavaScript?
“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 is JavaScript different from Java?
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).
In how many ways can you create an array in JavaScript?
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.
List out the ways to get access to HTML elements through JavaScript.
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.
What are ways to define a variable in JavaScript?
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.
What do you understand by closures in JavaScript?
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.
What do you understand by Cookies?
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.
What do you understand by JavaScript?
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).
What does the term “Transpiling” stand for in JavaScript?
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.
What is a Callback in JavaScript?
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.