javascript questions

Ace your homework & exams now with Quizwiz!

What are callbacks?

Functions that are used as an argument to another function are called callback functions.

What is Object Destructuring?

Object destructuring is a new way to extract elements from an object or an array.

What is recursion in a programming language?

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. function higherOrder(fn) { fn(); } higherOrder(function() { console.log("Hello world") });

static vs dynamic programming

static --> no type coercion, you cant have different variable name with diff data type dynamic --> assign variables to which ever datatype for the most part

ES6 introduced?

arrow functions, spread operators, let/const

What is npm?

npm stands for Node Package Manager. npm provides following two main functionalities: Online repositories for node.js packages/modules which are searchable on search.nodejs.org Command line utility to install packages, do version management and dependency management of Node.js packages.

What is the difference between slice and splice

slice --> doesnt modify the original array returns the subset of original array used to pick the elements from array splice --> modifies the original arrray returns the detected elements array used to insert or delete elements to/from array

Can you differentiate between let and var?

Both let and var are used for variable and method declaration in JavaScript. However, the most important difference between the two JS keywords is that while the var keyword is function scoped, the let keyword is block scoped.

How will you empty an array in JavaScript?

By assigning an empty array By assigning array length to 0 By popping the elements of the array By using the splice array function

Describe the main properties of a binary search tree

A binary search tree consists of a root node with a left and a right subtree. The left subtree only contains elements smaller than the root, and the right only contains elements higher.

What are object prototypes

All javascript objects inherit properties from a prototype.For example,Date objects inherit properties from the Date prototypeMath objects inherit properties from the Math prototypeArray objects inherit properties from the Array prototype.On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.A prototype is a blueprint of an object. Prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

What are lambda or arrow functions

An arrow function is a shorter syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.

What is a Closure?

In other words, a closure gives you access to an outer function's scope from an inner function. Among other things, closures are commonly used to give objects data privacy. Data privacy is an essential property that helps us program to an interface, not an implementation. This is an important concept that helps us build more robust software because implementation details are more likely to change in breaking ways than interface contracts.

What is the rest parameter and spread operator

It provides an improved way of handling parameters of a function.Using the rest parameter syntax, we can create functions that can take a variable number of arguments.Any number of arguments will be converted into an array using the rest parameter.It also helps in extracting all or some parts of the arguments.Rest parameter can be used by applying three dots (...) before the parameters.

What kind of data structure would you use to hold an arbitrary amount of objects in which retrieval is not an issue? what are the advantages and disadvantages of using a linked list over a dynamic array structure?

It's a List, though, more specifically an ArrayList, because retrieval is O(1). O(1) append vs ArrayList's O(n) in the worst case. May use less space in common implementations of ArrayList -- most ArrayLists use arrays with sizes that are multiples of 2. Disadvantages: O(n) retrieval. About the same: O(n) remove for both linked-list and arraylist in the worst-case.

You need to update your local repos. What git commands will you use?

It's a two steps process. First you fetch the changes from a remote named origin: git fetch origin Then you merge a branch master to local: git merge origin/master Or simply: git pull origin master If origin is a default remote and 'master' is default branch, you can drop it eg. git pull.

Can you name two programming paradigms important for JavaScript app developers?

JavaScript is a multi-paradigm language, supporting imperative/procedural programming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance.

classes

Key points to remember about classes: Unlike functions, classes are not hoisted. A class cannot be used before it is declared. A class can inherit properties and methods from other classes by using the extend keyword. All the syntaxes inside the class must follow the strict mode('use strict') of javascript. Error will be thrown if the strict mode rules are not followed.

What is the main difference between localStorage and sessionStorage

LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.

Could you name some built-in methods in JavaScript?

anchor() - Creates an HTML anchor to be used as a hypertext target ceil() - returns the smallest integer that is greater than or equal to the given number concat() - Combines two strings and returns the newer string constructor() - Returns the function that created the corresponding instance of the object Date() - Returns the present date and time Date.parse() - Parses a string representation of a date and time and then returns the internal millisecond representation for the same exec() - Searches for a match in the string parameter filter() - Creates a new array with all the elements of the array for which the filtering function returns true font color () - Displays a string in the specified color link() - Creates an HTML hypertext link that requests another URL localeCompare() - Returns a number that indicates whether a reference string comes before, after, or is the same as the given string in the sort order match() - Used for matching a regular expression against a string pop() - Removes and returns the last element from an array reduce() - Applies a function simultaneously for two values of the array to reduce them to a single value round() - Rounds off the value of the given number to the nearest integer and returns the same slice() - Extracts a certain section of a string and returns the remaining string some() - returns true if at least one element of the array satisfies the provided testing function toLocaleString() - Return a string value of the current number in a format that depends on the browser's locale settings sup() - Displays a string as a superscript toSource() - Returns a string containing the source of the Boolean object toUpperCase() - Converts a text to uppercase valueOf() - Returns the primitive value of the specified object

Explain "this" keyword.

function doSomething() { console.log(this); } doSomething();

closure

function inside a function where variable that can be accessed from parent and child functions

What is an Immediately Invoked Function in JavaScript?

(function (){ //Do something; }) An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined. While executing javascript code, whenever the compiler sees the word "function", it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

Accessing Dom Elements

// Returns a reference to the element by its ID. document.getElementById('someid'); // Returns an array-like object of all child elements which have all of the given class names. document.getElementsByClassName('someclass'); // Returns an HTMLCollection of elements with the given tag name. document.getElementsByTagName('LI'); // Returns the first element within the document that matches the specified group of selectors. document.querySelector('.someclass'); // Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) // that match the specified group of selectors. document.querySelectorAll('div.note, div.alert');

Add Elements to the DOM

// grab element on page you want to add stuff to var firstHeading = document.getElementById('firstHeading'); // add both new elements to the page as children to the element we stored in firstHeading. firstHeading.appendChild(newHeading); firstHeading.appendChild(newParagraph); // get parent node of firstHeading var parent = firstHeading.parentNode; // insert newHeading before FirstHeading parent.insertBefore(newHeading, firstHeading);

Add/Remove/Toggle/Check Classes

// grab element on page you want to use var firstHeading = document.getElementById('firstHeading'); // will remove foo if it is a class of firstHeading firstHeading.classList.remove('foo'); // will add the class 'anotherClass' if one does not already exist firstHeading.classList.add('anotherclass'); // add or remove multiple classes firstHeading.classList.add('foo', 'bar'); firstHeading.classList.remove('foo', 'bar'); // if visible class is set remove it, otherwise add it firstHeading.classList.toggle('visible'); // will return true if it has class of 'foo' or false if it does not firstHeading.classList.contains('foo');

Create New DOM Elements

//create new elements var newHeading = document.createElement('h1'); var newParagraph = document.createElement('p'); // create text nodes for new elements var h1Text= document.createTextNode('This is a nice header text!'); var pText= document.createTextNode('This is a nice paragraph text!'); // attach new text nodes to new elements newHeading.appendChild(h1Text); newParagraph.appendChild(pText);

closure

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What are the pros and cons of monolithic vs microservice architectures?

A monolithic architecture means that your app is written as one cohesive unit of code whose components are designed to work together, sharing the same memory space and resources. A microservice architecture means that your app is made up of lots of smaller, independent applications capable of running in their own memory space and scaling independently from each other across potentially many separate machines. Monolithic Pros: The major advantage of the monolithic architecture is that most apps typically have a large number of cross-cutting concerns, such as logging, rate limiting, and security features such audit trails and DOS protection. When everything is running through the same app, it's easy to hook up components to those cross-cutting concerns. There can also be performance advantages, since shared-memory access is faster than inter-process communication (IPC). Monolithic cons: Monolithic app services tend to get tightly coupled and entangled as the application evolves, making it difficult to isolate services for purposes such as independent scaling or code maintainability. Monolithic architectures are also much harder to understand, because there may be dependencies, side-effects, and magic which are not obvious when you're looking at a particular service or controller. Microservice pros: Microservice architectures are typically better organized, since each microservice has a very specific job, and is not concerned with the jobs of other components. Decoupled services are also easier to recompose and reconfigure to serve the purposes of different apps (for example, serving both the web clients and public API). They can also have performance advantages depending on how they're organized because it's possible to isolate hot services and scale them independent of the rest of the app. Microservice cons: As you're building a new microservice architecture, you're likely to discover lots of cross-cutting concerns that you did not anticipate at design time. A monolithic app could establish shared magic helpers or middleware to handle such cross-cutting concerns without much effort. In a microservice architecture, you'll either need to incur the overhead of separate modules for each cross-cutting concern, or encapsulate cross-cutting concerns in another service layer that all traffic gets routed through. Eventually, even monolthic architectures tend to route traffic through an outer service layer for cross-cutting concerns, but with a monolithic architecture, it's possible to delay the cost of that work until the project is much more mature. Microservices are frequently deployed on their own virtual machines or containers, causing a proliferation of VM wrangling work. These tasks are frequently automated with container fleet management tools.

Please explain the various JavaScript data types?

Boolean - Represents true and false values. Null - Represents empty, nothing, and unknown type of values Number - Represents both integer and floating-point values. Object - Used for storing collections of data or more complex entities String - Represents single-character, multi-character, and alphanumeric values. Symbol - Used for creating unique identifiers for objects Undefined - Represents value not assigned. If a variable is only declared and not assigned in JS, it represents the undefined data type.

Is javascript a statically typed or a dynamically typed language

JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to statically typed language, where the type of a variable is checked during compile-time. variables in JS are not associated with any type

What is the difference between classical inheritance and prototypal inheritance?

Class Inheritance: instances inherit from classes (like a blueprint — a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the `new` keyword. Class inheritance may or may not use the `class` keyword from ES6. Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or `Object.create()`. Instances may be composed from many different objects, allowing for easy selective inheritance.

What do you understand by Closures in JavaScript?

Closures provide a better, concise, creative, and expressive writing code for JavaScript developers and programmers. Technically speaking, closures are a combination of lexical environment and function. In other words, a closure is a locally declared variable that is related to a function and stays in the memory when the related function has returned. The closure contains all local variables that were in-scope at the time of the closure creation. The following code snippet demonstrates using a normal function in JavaScript:

Explain Implicit Type Coercion in javascript

Implicit type coercion in javascript is automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types. String coercion String coercion takes place while using the ' + ' operator. When a number is added to a string, the number type is always converted to the string type. Boolean Coercion Boolean coercion takes place when using logical operators, ternary operators, if statements and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values.

What is the use of a constructor function in javascript

Constructor functions are used to create objects in javascript.

What is meant by Continuous Integration

Continuous Integration (CI) is a development practice that requires developers to integrate code into a shared repository several times a day. Each check-in is then verified by an automated build, allowing teams to detect problems early.

What is DOM?

DOM stands for Document Object Model.DOM is a programming interface for HTML and XML documents.When the browser tries to render a HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.

What are the three tenets of OOP?

Encapsulation, Data Abstraction, Polymorphism and inheritance Encapsulation is the mechanism of hiding of data implementation by restricting access to public methods. Instance variables are kept private and accessor methods are made public to achieve this. Inheritances expresses "is-a" and/or "has-a" relationship between two objects. Using Inheritance, In derived classes we can reuse the code of existing super classes It means one name many forms. It is further of two types — static and dynamic. Static polymorphism is achieved using method overloading and dynamic polymorphism using method overriding. It is closely related to inheritance. We can write a code that works on the superclass, and it will work with any subclass type as well. Abstract means a concept or an Idea which is not associated with any particular instance. Using abstract class/Interface we express the intent of the class rather than the actual implementation. In a way, one class should not know the inner details of another in order to use it, just knowing the interfaces should be good enough.

how to approach design systems questions?

Functional - what functionalities or features can the system or app use? High availability: Most of the systems must be highly available. Consistency: The systems with high availability will have eventual consistency. Any banking system favours consistency over availability as there cannot be discrepancies in data (account balance). Reliability: No loss of user data. Latency: Response time of a user action such as loading a web page, liking a post etc. Storage estimation: Based on the data modality: A rough estimate of how much data must be stored — To know what type of database can be used and file storage for storing images/videos. Number of requests to the service — To know how to scale the services. A service that is read-heavy can be scaled to handle high traffic of requests. Read Write ratio — Determines whether the system is read-heavy or not. Database design--> SQL -- relational non-SQL --> key-value/mongoDB A relational (SQL) database is ideal for handling data models that are well-understood, may not change often, require adherence to strict international standards, and for businesses that value data consistency over transaction speed. A non-relational (NoSQL) database is ideal for companies facing changing data requirements, those that can adapt to rapidly-evolving vendor-driven standards and APIs, and those who need to deal with multiple types of data and high traffic volumes. High-level system design --> Initially start with a very basic design Client Application server Database Isolating the services — for easier scaling and traffic control components

What is functional programming?

Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data. Lisp (specified in 1958) was among the first languages to support functional programming, and was heavily inspired by lambda calculus. Lisp and many Lisp family languages are still in common use today. Functional programming is an essential concept in JavaScript (one of the two pillars of JavaScript). Several common functional utilities were added to JavaScript in ES5. Good to hear: Pure functions / function purity. Avoid side-effects. Simple function composition. Examples of functional languages: Lisp, ML, Haskell, Erlang, Clojure, Elm, F Sharp, OCaml, etc... Mention of features that support FP: first-class functions, higher order functions, functions as arguments/values.

HTTP stands for

Hypertext Transfer Protocol HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser.

What is JSON and its common operations

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. It is useful when you want to transmit data across a network and it is basically just a text file with an extension of .json, and a MIME type of application/json Parsing: Converting a string to a native object JSON.parse(text) Stringification: **converting a native object to a string so it can be transmitted across the network JSON.stringify(object)

Could you explain the Gitflow workflow?

Master - is always ready to be released on LIVE, with everything fully tested and approved (production-ready). Hotfix - Maintenance or "hotfix" branches are used to quickly patch production releases. Hotfix branches are a lot like release branches and feature branches except they're based on master instead of develop. Develop - is the branch to which all feature branches are merged and where all tests are performed. Only when everything's been thoroughly checked and fixed it can be merged to the master. Feature - Each new feature should reside in its own branch, which can be pushed to the develop branch as their parent one.

What is NaN property in JavaScript?

NaN property represents "Not-a-Number" value. It indicates a value which is not a legal number.typeof of a NaN will return a Number .To check if a value is NaN, we use the isNaN() function,

What are the javascript data types

Number String Boolean Object Undefined

What are the pros and cons of functional programming vs object-oriented programming?

OOP Pros: It's easy to understand the basic concept of objects and easy to interpret the meaning of method calls. OOP tends to use an imperative style rather than a declarative style, which reads like a straight-forward set of instructions for the computer to follow. OOP Cons: OOP Typically depends on shared state. Objects and behaviors are typically tacked together on the same entity, which may be accessed at random by any number of functions with non-deterministic order, which may lead to undesirable behavior such as race conditions. FP Pros: Using the functional paradigm, programmers avoid any shared state or side-effects, which eliminates bugs caused by multiple functions competing for the same resources. With features such as the availability of point-free style (aka tacit programming), functions tend to be radically simplified and easily recomposed for more generally reusable code compared to OOP. FP also tends to favor declarative and denotational styles, which do not spell out step-by-step instructions for operations, but instead concentrate on what to do, letting the underlying functions take care of the how. This leaves tremendous latitude for refactoring and performance optimization, even allowing you to replace entire algorithms with more efficient ones with very little code change. (e.g., memoize, or use lazy evaluation in place of eager evaluation.) Computation that makes use of pure functions is also easy to scale across multiple processors, or across distributed computing clusters without fear of threading resource conflicts, race conditions, etc... FP Cons: Over exploitation of FP features such as point-free style and large compositions can potentially reduce readability because the resulting code is often more abstractly specified, more terse, and less concrete. More people are familiar with OO and imperative programming than functional programming, so even common idioms in functional programming can be confusing to new team members. FP has a much steeper learning curve than OOP because the broad popularity of OOP has allowed the language and learning materials of OOP to become more conversational, whereas the language of FP tends to be much more academic and formal. FP concepts are frequently written about using idioms and notations from lambda calculus, algebras, and category theory, all of which requires a prior knowledge foundation in those domains to be understood.

What is the use of promises in javascript

Promises are used to handle asynchronous operations in javascript.Before promises, callbacks were used to handle asynchronous operations. But due to limited functionality of callback, using multiple callbacks to handle asynchronous code can lead to unmanageable code. Promise object has four states - Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state. Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed. Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed. Settled - This state represents that the promise has been either rejected or fulfilled. A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.

Properties vs attributes

Props --> JS DOM objects have props, ID, classname attributes--> in HTML iteself rather than in the DOM, only a string, set a custom attribute, where not one is et

What is asynchronous programming, and why is it important in JavaScript?

Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O. Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations. User interfaces are asynchronous by nature, and spend most of their time waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default, meaning that the server works in much the same way, waiting in a loop for a network request, and accepting more incoming requests while the first one is being handled. This is important in JavaScript, because it is a very natural fit for user interface code, and very beneficial to performance on the server.

What is DOM (Document Object Model)

The Document Object Model (DOM) is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure wherein each node is an object representing a part of the document. With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. The DOM specifies interfaces which may be used to manage XML or HTML documents.

Could you tell us about the various types of error constructors supported by JavaScript?

The Error constructor is responsible for creating an error object. Instances of the error objects are thrown when runtime errors occur. Moreover, the Error object can also be used as a base object for user-defined exceptions. Other than the generic Error constructor, JS provides support for 7 error constructors that are: EvalError - Creates an error instance regarding the global function eval(). InternalError - Creates an error instance regarding an internal error in the JS engine. RangeError - Creates an error instance regarding a numeric variable or parameter that is outside of its valid range. ReferenceError - Creates an error instance regarding de-referencing an invalid reference. SyntaxError - Creates an error instance regarding a syntax error occurring while parsing code in eval(). TypeError - Creates an error instance regarding a parameter or variable not of a valid type. URIError - Creates an error instance regarding when invalid parameters are passed to the decode URI() or encodeURI()

When is classical inheritance an appropriate choice

The answer is never, or almost never. Certainly never more than one level. Multi-level class hierarchies are an anti-pattern. I've been issuing this challenge for years, and the only answers I've ever heard fall into one of several common misconceptions. More frequently, the challenge is met with silence.

What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?

The short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice. Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source. Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.

What are two-way data binding and one-way data flow, and how are they different?

Two way data binding means that UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa. One way data flow means that the model is the single source of truth. Changes in the UI trigger messages that signal user intent to the model (or "store" in React). Only the model has the access to change the app's state. The effect is that data always flows in a single direction, which makes it easier to understand. One way data flows are deterministic, whereas two-way binding can cause side-effects which are harder to follow and understand. Good to hear: React is the new canonical example of one-way data flow, so mentions of React are a good signal. Cycle.js is another popular implementation of uni-directional data flow. Angular is a popular framework which uses two-way binding.

Design a weather app system

features/functionality: User can view the weather in his/her current location. User can toggle the temperature unit (Celsius or Fahrenheit). Weather icon or background image will change depending on weather conditions. database: weather API design: show only the temperature and weather description in addition to the local time.

Explain Scope and Scope Chain in javascript.

the scope will let us know at a given part of code, what are the variables and functions that we can or cannot access. Global Scope Local or Function Scope Block Scope Block ScopeBlock scope is related to the variables declared using let and const. Variables declared with var do not have block scope.Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.

What are the differences between undeclared and undefined variables

undeclared --> These variables do not exist in a program and are not declared If you try to read the value of an undeclared variable, then a runtime error is encountered undefined--> These variables declared in the program but have not assigned any value If you try to read the value of an undefined variable, an undefined value is returned.

Explain passed by value and passed by reference.

var x = 2; In the above example, we created a variable x and assigned it a value "2". In the background, the "=" (assign operator) allocates some space in the memory, stores the value "2" and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly

hoisting

we can declare a variable after it has been used because variable declarations that use var are hoisted to the top of their functional scope at compile time. This means that a variable can be initialized before it is declared. Only the declarations get hoisted to the top, not the initializations.

What is the difference between window and document

window--> It is the root level element in any web page By default window object is available implicitly in the page It has methods like alert(), confirm() and properties like document, location Document --> It is the direct child of the window object. This is also known as Document Object Model(DOM) You can access it via window.document or document. It provides methods like getElementById, getElementByTagName, createElement etc


Related study sets

Public Speaking Midterm Study Practice

View Set

Lecture Exam #2 Study - CJ Stats.

View Set

Risk Management, Insurance Planning, and Employee Benefits

View Set

A Taste Of Honey - Key Quotes: Jo and Geof

View Set

California Real Estate Principles- Chapter 3

View Set