- 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.
Write Code To Convert An Array Of Strings To An Array Of The Lengths Of Those Strings
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.
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
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"
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:
Here is an anonymous function thats assigned to a variable:
const myFunction = function
And heres an anonymous function used as a callback:
Learn more about callbacks and the map function here.
You May Like: How To Write An Email After A Job Interview
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.
- 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 ===
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.
"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.
// 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.
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.
const person = function greet $. $` }let result = greet.apply console.log
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
- 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
The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.
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
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.
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
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
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.
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}
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
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.
- 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.
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
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.
Don’t Miss: How To Do A Telephone Interview