Wednesday, April 17, 2024

Cracking The Coding Interview In Javascript

Don't Miss

Understand Javascript Scope Well

CTCI – 1.6 – String Compression (JAVASCRIPT ES6 SOLUTION VIDEO)

JavaScript scope is a pandora box. Hundreds of tough interview questions can be framed from this single concept. There are three kinds of scopes:

  • Global scope

Execution goes in this way!

var mygenerator = generator mygenerator.next // returns "o"mygenerator = generator mygenerator.next  // returns "t"

Here, the scope is playing an important role. A closure is a function that returns another function and wraps data. The above string generator qualifies for a closure. The index value is preserved between multiple function calls. The internal function defined can access the variables defined in the parent function. This is a different scope. If you defined one more function in the second level function, that can access all parents variables.

JavaScript Scope can throw a lot of problems at you! understand it thoroughly

Write Code To Convert An Array Of Strings To An Array Of The Lengths Of Those Strings

This should be a relatively easy exercise for someone familiar with Javascript to complete. An ideal solution to this problem should look something like this:

var words =  var wordLengths = words.map // wordLengths =   

Another version might use forEach:

var wordLengths2 =  words.forEach)  

Finally, using an old-fashioned for loop will do the trick:

var wordLengths3 =   var i  for   

The last two should be considered a bit of a red flag as it shows that the candidate is not very familiar with the most common of higher-order functions: map.

What Are The Types Of Errors In Javascript

There are two types of errors in javascript.

  • Syntax error: Syntax errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.
  • Logical error: Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults.
  • You May Like: What Are Some Questions To Ask After An Interview

    What Is Object Destructuring

    Object destructuring is a way to extract properties from an object .

    Before ES6 you would have needed to do this to extract the properties of an object:

    const PersonDetails = const name = PersonDetails.name const age = PersonDetails.age const married = PersonDetails.married console.log console.log console.log 

    But since ES6 you could do that with one line of code by utilizing object destructuring:

    const PersonDetails = const  = PersonDetails console.log console.log console.log 

    What Is Recursion In A Programming Language

    35 Cracking The Coding Interview Javascript Solutions

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

    function add  else }add =>  3 + add          3 + 2 + add          3 + 2 + 1 + add          3 + 2 + 1 + 0 = 6  

    Example of a recursive function:The following function calculates the sum of all the elements in an array by using recursion:

    function computeSum  else}computeSum  // Returns 123

    You May Like: What Should I Ask In A Job Interview

    What Is The Temporal Dead Zone

    Temporal Dead Zone means unreachability of a variable, even though its already in the scope.

    Lets first take a look at what happens when you try to log a variable to the console when its not initialized:

    console.log var x = "Yay" 
    undefined

    You probably expected this to result in an error, but it prints undefined.

    This happens because of hoisting, which means all the declarations are moved to the top of the scope. Due to hoisting, the above code behaves like this under the hood:

    var x console.log x = "Yay" 

    Here undefined is assigned to the variable at the top automatically. This makes it possible to use it before defining it.

    But lets then take a look at what happens when we do the same using let instead of var:

    console.log let x = 10 
    error: Uncaught ReferenceError: Cannot access 'x' before initialization

    This happens because let is hoisted differently than var.

    When a let variable is hoisted it doesnt become undefined. Instead, its unreachable, or in the Temporal Dead Zone until its assigned a value.

    What Is An Anonymous Function

    An anonymous function is a function that does not have a name.

    Anonymous functions are commonly assigned to a variable name or used as a callback function.

    Here is a function with a name for a reference:

    function example 

    Here is an anonymous function thats assigned to a variable:

    const myFunction = function  

    And heres an anonymous function used as a callback:

    .map ) 

    Learn more about callbacks and the map function here.

    You May Like: How To Write An Email After A Job Interview

    What Is Meant By Scope In Javascript

    The scope defines the visibility of your code.

    More formally, the scope describes where variables, functions, and other objects are accessible in the code. Scopes are created in your code during the runtime.

    For example, a block scope means the area between curly braces:

    if console.log  // ERROR OCCURS

    Here, the variable word is not accessible from anywhere else but in the if-statement.

    Q25 What Are The Ways To Define A Variable In Javascript

    CTCI – 1.4 – Palindrome Permutation (JAVASCRIPT ES6 SOLUTION VIDEO)

    The three possible ways of defining a variable in JavaScript are:

    • Var The JavaScript variables statement is used to declare a variable and, optionally, we can initialize the value of that variable. Example: var a =10 Variable declarations are processed before the execution of the code.
    • Const The idea of const functions is not allow them to modify the object on which they are called. When a function is declared as const, it can be called on any type of object.
    • Let It is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block its defined in.

    Recommended Reading: How To Prepare For A Sales Interview

    What Is The Difference Between == And ===

    The answer to this question is rather simple but an incorrect answer by a candidate should be considered a red flag. The answer is that == performs any necessary type conversions before doing the comparison whereas === does not. The Javascript equality table is rather infamous and its considered a good practice to always use === when comparing values for equality.

    What Is A Strict Mode In Javascript

    Strict mode allows you to set your program to operate in a strict context.

    The strict mode prevents certain actions from being taken. Also, more exceptions are thrown.

    The expression “use strict” tells the browser to enable the strict mode.

    For example:

    "use strict" number = 1000 

    This causes an error because strict mode prevents you from assigning a value to an undeclared variable.

    Recommended Reading: How To Thank You For An Interview

    Build Composable Web Applications

    Dont build web monoliths. Use Bit to create and compose decoupled software components in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

    Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components.

    What Are Classes In Javascript

    35 Cracking The Coding Interview Javascript Solutions

    Introduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions. They provide a new way of declaring constructor functions in javascript. Below are the examples of how classes are declared and used:

    // Before ES6 version, using constructor functionsfunctionStudent// Way to add methods to a constructor functionStudent.prototype.getDetails = function, Roll no: $, Grade: $, Section:$' }let student1 = new Student student1.getDetails // Returns Name: Vivek, Roll no:354, Grade: 6th, Section:A// ES6 version classesclassStudent// Methods can be directly added inside the classgetDetails, Roll no: $, Grade:$, Section:$'   }}let student2 = new Student student2.getDetails // Returns Name: Garry, Roll no:673, Grade: 7th, Section:C

    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 of javascript. An error will be thrown if the strict mode rules are not followed.

    Also Check: What To Say In A Customer Service Interview

    What Is The Apply Method

    The apply method does the same as the call method. The difference is that apply method accepts the arguments as an array.

    For example:

    const person = function greet  $. $` }let result = greet.apply console.log 

    Output:

    Hello John. How are you?

    In the line:

    let result = greet.apply 

    Hello is assigned to greeting and How are you? is assigned to message in the greet function.

    What Are Object Prototypes

    All javascript objects inherit properties from a prototype. For example,

    • Date objects inherit properties from the Date prototype
    • Math objects inherit properties from the Math prototype
    • Array 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. The prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

    Lets see prototypes help us use methods and properties:

    var arr =  arr.push console.log  // Outputs 

    In the code above, as one can see, we have not defined any property or method called push on the array arr but the javascript engine does not throw an error.

    The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

    The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.

    Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype’s prototype and so on.

    Recommended Reading: How To Do A Group Interview

    How To Sort Elements Of An Array

    Use the sort to sort the items of an array. This does not create a new array but sorts the original array in-place, that is, modifies it directly.

    let months =  months.sort console.log 

    Output:

    TypeScript is JavaScript with types. Its a superset of JavaScript created by Microsoft.

    TypeScript adds types such as optional types, classes, async/await, and so on to plain JavaScript.

    Here is a simple example of a TypeScript function:

    function greet: string 

    The type information is explicitly expressed in the functions parameter type and return type.

    Prototypes And Prototypal Inheritance In Javascript

    CTCI – 1.7 – Rotate Matrix (JAVASCRIPT ES6 SOLUTION VIDEO)

    Whenever we create anything in JavaScript, the JS Engine automatically attaches that thing with some properties and methods.

    All this comes via prototypes.

    __proto__ is the object where JS is putting it all.

    Let’s see some examples. Fire up your consoles!

    let arr = console.logconsole.log // same as Array.prototypeconsole.log // same as Object.prototypeconsole.log // null

    All this is called a prototype chain.

    We can do the same with objects and functions as well.

    We will always find Object.prototype behind the scenes. That’s why you may have heard that everything in JS is an object.

    Read Also: What To Do In An Exit Interview

    What Is The Distinction Between Client

    Client-side JavaScript is made up of two parts, a fundamental language and predefined objects for performing JavaScript in a browser. JavaScript for the client is automatically included in the HTML pages. At runtime, the browser understands this script.

    Client-side JavaScript is similar to server-side JavaScript. It includes JavaScript that will execute on a server. Only after processing is the server-side JavaScript deployed.

    Why Use Strict Mode In Javascript

    Strict mode helps writing secure JavaScript code. This means bad syntax practices are converted into real errors.

    For example, strict mode prevents creating global variables.

    To declare strict mode, add use strict statement before the statements which you want to be under strict mode:

    'use strict' const sentence = "Hello, this is very strict" 

    Don’t Miss: How To Prepare For Business Analyst Interview

    Understand Error Handling Patterns

    This is the least cared piece of JavaScript by many developers. I see a very handful of developers talking about error handling. A good development approach always carefully wrap JS code around try/catch blocks.

    Nicholas C. Zakas, a UI engineer at Yahoo, said back in 2008 Always assume your code will fail. Events may not be handled properly! Log them to the server. Throw your own errors.

    In JavaScript whenever we code casually, things may fail. For Ex:

    $.click}) }) 

    Here, we are falling into the trap saying results always will be a JSON object. Sometimes the server can crash and null will be returned instead of the result. In that case, null will throw an error. The proper handling could be this!

    $.click    }}) }) 

    The logError function is intended to report the error back to the server. The second function flashInfoMessage is the function that displays a user-friendly message like Service unavailable currently etc.

    Nicholas says manually throw errors whenever you feel something unexpected is going to happen. Differentiate between fatal and non-fatal errors. The above error is related to the backend server going down which is fatal. There, you should inform the customer that the service is down due to some reason. In some cases, it may not be fatal but better to notify sever about this. In order to create such code, first, throw an error, catch it with error event at window objectlevel, then make an API call to log that message to the server.

        throw new Error}

    Advantages Of Closures In Javascript

    cracking
    • Currying
    let add = function  }let addByTwo = addaddByTwo
    • Data Hiding/Encapsulation

    Suppose you want to create a counter application. Every time you call it, the count increases by 1. But you don’t want to expose the variable outside the function. How to do it?

    You guessed it closures!

    function Counter }console.log // Error: count is not definedvar adder = new Counteradder.incrementCount // 1

    Don’t worry about this and new. We have a whole section devoted to them down below.

    Recommended Reading: Aws Cloud Infrastructure Architect Interview Questions

    Functional Programming In Javascript

    We have already used functions above. Let’s cover them in more detail now.

    Just like how we used variables to store values, we can use functions to store a piece of code which we can reuse.

    You can make function in two ways:

    function aconst b =  =>  // They are essentially the same but with a few differences which we will cover as we go along this tutorial. // We can pass variables as argumentsconst c =  =>  `)}// `` template literal are a new addition to the language. Very useful for string formatting. Values are accessed using $ inside them.// We can even pass functions as arguments to a function. Will see more on this when we try to understand closures.const greet =  =>    $, welcome!`)    }}console.log)

    Now, let’s cover some important concepts related to functions.

    Disadvantages Of Closures In Javascript

    • Overconsumption of memory or memory leaks can happen.

    For example, the closed-over-variable will not be garbage collected. This is because, even if the outer function has run, the returned inner function still has a reference to the closed-over-variable.

    Note: Garbage collection basically removes unused variables from the memory automatically.

    You May Like: How To Correctly Answer Interview Questions

    What Are The Async / Await Keywords Used For

    Promises have been successful at alleviating the problems associated with a strictly callback solution to asynchronous programming but they can be difficult to use when lots of Promises are involved and must be sequenced with then as well as having to handle errors associated with all that chaining.

    The async / await keywords are used to allow developers to write code that feels very much like old-fashioned imperative code -or sequential code- but that is still asynchronous.

    Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.

    What Is A Callback Function In Javascript

    Google JavaScript Interview With A Frontend Engineer

    A callback function is a function that is passed as an argument to another function. This function is executed inside the function to which its passed as to call back when some action has been completed.

    Lets see an example of this:

    function greetName function askName askName 

    This code prompts you a name, and when youve entered the name, it says Hello to that name. So the callback function, which in this case, is the greetName, executes only after youve entered a name.

    You May Like: Servicenow Cmdb Interview Questions And Answers

    It Has Become Common To Wrap The Contents Of A Javascript File In A Function Why Is This Done

    This technique has been used to create a kind of namespace for a module so that variables defined in the module are private and therefore will not clash with variables in the global namespace or in other modules.

    Here is an example:

    var queue =  ,      dequeue: function   else       }    }   })    

    In the above implementation of a queue data structure the variable items is private to the implementation and is not viewable or modifiable by clients of a queue.

    This technique is known as Immediately Invoked Function Expression or IIFE. You can read more about it on the Mozilla Developer Network and on Wikipedia.

    This technique can be generally useful for data hiding and namespacing but modern Javascript bundlers like webpack have become popular for achieving the same effect.

    Top 100 Javascript Interview Questions And Answers For 2022

    To build a JavaScript programming career, candidates need to crack the interview. They are asked for variousJavaScript interview questions and answers.

    Following is a list of JavaScript interview questions and answers, which are likely to be asked during the interview. Candidates are likely to be asked basic JavaScriptinterview questions to advance JS interviewquestions depending on their experience and various other factors.

    The below list covers all the JavaScriptquestions for freshers and JavaScriptinterviewquestions for professional-level candidates. This JS interviewquestions guide will help you crack the interview and help you get your dream job for JavaScript Programming.

    Don’t Miss: How To Do A Telephone Interview

    More articles

    Popular Articles