1. Flashcards

1
Q

What is scope in JS?

A

Scope determines the accessibility (visibility) of variables. In JavaScript there are two types of scope: Local scope, Global scope. Variables defined inside a function are not accessible (visible) from outside the function. Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

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

What is the Difference Between Scope and Context in JavaScript?

A

Scope pertains to the visibility of variables, and context refers to the object to which a function belongs.

The value of ‘this’ depends on where it is being invoked. Invoking ‘this’ in the global space will return the entire window object. because the window object is the starting point of all the code we write. If we invoke this in the context of a new object, it will return that object, ‘this’ will refer to that object.

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

What is “this”? (context)

A

Context tells us where we are within the object.
“this” refers to the object that the function is a property of. The value of “this” will always depend on the object that is invoking the function.

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

Since the function is invoked in the global context, the function is a property of the global object.

var obj = {
    name:  "vivek",
    getName: function(){
    console.log(this.name);
  }
}   
obj.getName();

In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, the this keyword will refer to the object obj , and hence the output will be “vivek”.

var obj = {
    name:  "vivek",
    getName: function(){
    console.log(this.name);
  }     
}   
var getName = obj.getName;
var obj2 = {name:"akshay", getName };
obj2.getName();

The output will be “akshay”. Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .

var obj1 = {
    address : "Mumbai,India",
    getAddress: function(){
    console.log(this.address); 
  }
}
var getAddress = obj1.getAddress;
var obj2 = {name:"akshay"};
obj2.getAddress();    

The output will be an error. Although in the code above, the this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.

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

What are JavaScript Data Types?

A

Following are the JavaScript Data types:

Number
String
Boolean
Object
Undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the use of isNaN function?

A

isNan function returns true if the argument is not a number; otherwise, it is false.

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

What is negative Infinity?

A

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

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

Which company developed JavaScript?

A

Netscape is the software company that developed JavaScript.

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

What are undeclared and undefined variables?

A

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

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

Write the code for adding new elements dynamically?

A

t1

    function addNode () { var newP = document. createElement("p"); 
    var textNode = document.createTextNode(" This is a new text node"); 
    newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } 

<p>firstP</p>

<p>
</p>

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

What are global variables? How are these variable declared?

A

Global variables are available throughout the length of the code so that it has no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

Example:

// Declare a global: globalVariable = “Test”;

The problems faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

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

What is ‘this’ keyword in JavaScript?

A

‘This’ keyword refers to the object from where it was called.

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

What is === operator?

A

=== is called a strict equality operator, which returns true when the two operands have the same value without conversion.

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

Does JavaScript support automatic type conversion?

A

Yes, JavaScript does support automatic type conversion.

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

How can the style/class of an element be changed?

A

document.getElementById(“myText”). style. fontSize = “20”;
or
document. getElementById (“myText”). className = “anyclass”;

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

What is a Closure?

A

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. In JavaScript, closures are created every time a function is created, at function creation time.

(To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function.)

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

const test = function (counterName) {
    let counter = 0;
    return function () {
        console.log(counterName, ++counter);
    }
}
const counterA = test('Counter A')
const counterB = test('Counter B')

counterA();
counterA();
counterA();
counterB();

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

What is a callback function? (EdX)

A

Callback is a function passed into another function as an argument to be executed later.

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

Why does Function Expression have a semicolon “;” at the end, but Function Declaration does not?

function sayHi() {
  // ...
}
let sayHi = function() {
  // ...
};
A

The answer is simple:

  • There’s no need for ; at the end of code blocks and syntax structures that use them like if { … }, for { }, function f { } etc.
  • A Function Expression is used inside the statement: let sayHi = …;, as a value. It’s not a code block, but rather an assignment. The semicolon ; is recommended at the end of statements, no matter what the value is.

So the semicolon here is not related to the Function Expression itself, it just terminates the statement.

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

What is Function expression?

A

This is when we create a function and assign it to the variable, like any other value. No matter how the function is defined, it’s just a value stored in the variable. Note: the semicolon “;” is recommended at the end of statements, since we assign the function to the variable (it is not a code block).

let sayHi = function() {
  alert( "Hello" );
};

The function above is actually an anonymous function (a function without a name). Arrow functions provide syntactic sugar for Function Expressions.

let sayHi = () => {
  alert( "Hello" );
};

Unlike function declarations, function expressions are NOT hoisted. These functions are only available when the JavaScript interpreter processes that line of code.

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

What is Function declaration?

A

Function Declarations begin with the function keyword, followed by the name of the function and any arguments it may take.

function showMessage() {
  alert( 'Hello everyone!' );
}

When defining a function using function declarations, the function is hoisted. A hoisted function or variable is placed at the top of their functional scope when JavaScript is executing code.

Note: Functional Scope refers to where a function was defined. For example, if a function foo() contained a function bar() inside of it, we would say that the functional scope of bar() is foo(). If foo() was not defined within a function, then foo() belongs to the global scope. JavaScript functions in the global scope are accessible to all the code that runs with it.

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

What is Immediately-Invoked Function Expressions (IIFE)?

A

IIFEs are functions that are executed immediately after being defined. The parentheses surrounding the function definition lets JavaScript know that it will process a function expression. The last pair of parentheses invoke the function.

(function() {
    // Code that runs in your function
})()
(function(arg1, arg2) {
    // Code that runs in your function
})("hello", "world");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When to Use an IIFE?

A

The most common use cases for IIFEs are:

  • Adjustment global variables,
  • Creating private variables or functions,
  • Asynchronous functions in loops
  1. Aliasing Global Variables
    If you have 2 libraries that export an object with the same name, you can use IIFEs to ensure they don’t conflict in your code. For example, the jQuery and Cash JavaScript libraries both export $ as their main object. Let’s say, we want to ensure that $ refers to the jQuery object, and not the cash alternative:
(function($) {
    // Code that runs in your function
})(jQuery);
  1. Creating Private Variables and Functions
    We can use IIFEs to create private variables and functions within the global scope, or any other function scope. Functions and variables added to the global scope are available to ALL scripts that are loaded on a page. If we load other JavaScript files in our browser, they also gain access to our function and variable. To prevent them from using or editing them, we encase (wrap/pack) our code in an IIFE:
(function () {
    function generateMagicNumber() {
        return Math.floor(Math.random() * 100) + 900;
    }
console.log("This is your magic number: " + generateMagicNumber());
    var favoriteNumber = 5;
    console.log("Twice your favorite number is " + favoriteNumber * 2);
})();

It runs the same, but now generateMagicNumber() and favoriteNumber are only accessible in our script.

  1. Asynchronous Functions in Loops.
    When JavaScript meets asynchronous code, JS postpones execution of the callback function until the asynchronous task will be completed. In this example, the console.log() statement will run only after the timeout has expired/done.
for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
        console.log('I reached step ' + i);
    }, 1000 * i);
}
I reached step 6
I reached step 6
I reached step 6
I reached step 6
I reached step 6

This problem can be solved with an IIFE:

for (var i = 1; i <= 5; i++) {
    (function (step) {
        setTimeout(function() {
            console.log('I reached step ' + step);
        }, 1000 * i);
    })(i);
}

By using an IIFE, we create a new scope for our callback function. Our IIFE takes a parameter step. Every time our IIFE is called, we give it the current value of i as its argument. Now, when the callback is ready to be executed, its closure will have the correct value of step.

I reached step 1
I reached step 2
I reached step 3
I reached step 4
I reached step 5

https://stackabuse.com/javascripts-immediately-invoked-function-expressions/

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

What typeof returns for a null value?

A

It returns “object”.

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

Give an example of closure?

A

Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −

function create() {
   var counter = 0;
   return {
      increment: function() {
         counter++;
      },
  print: function() {
     console.log(counter);
  }    } } var c = create(); c.increment(); c.print();     // ==> 1
24
Q

Which type of variable among global and local, takes priority over other if names are same?

A

A local variable takes priority over a global variable with the same name.

25
Q

What are the valid scopes of a variable in JavaScript?

A

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.

Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

26
Q

What is arguments object in JavaScript?

A

JavaScript variable arguments represents the arguments passed to a function.

27
Q

What are disadvantages of using JavaScript?

A

We can not treat JavaScript as a full fledged programming language. It lacks the following important features −

Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.

JavaScript can not be used for Networking applications because there is no such support available.

JavaScript doesn’t have any multithreading or multiprocess capabilities.

28
Q

What are the advantages of using JavaScript?

A

Following are the advantages of using JavaScript −

Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.

Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.

Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.

Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

29
Q

Name some of the JavaScript features.

A

Following are the features of JavaScript −

JavaScript is a lightweight, interpreted programming language.

JavaScript is designed for creating network-centric applications.

JavaScript is complementary to and integrated with Java.

JavaScript is is complementary to and integrated with HTML.

JavaScript is open and cross-platform.

30
Q

What is JavaScript?

A

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

31
Q

What is Functional programming?

A

Functional programming is a style of writing code that involves a pattern of passing functions as arguments and the ability to return functions without causing side effects.

32
Q

What Is Currying?

A

Currying is a function that takes one argument at a time and returns a new function expecting the next argument. It is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).

We’re talking about the process where a function takes multiple arguments one at a time.

So rather than having a function that looks like this:
fakeFunction(‘param1’, ‘param2’, ‘param3’);

You end up with something like this:
fakeFunction(‘param1’)(‘param2’)(‘param3’);

When you curry your code, your first argument returns an expected outcome that proceeds to process your next argument, and so on and so forth.

A curried function can look something like this:

function fakeFunction(param1){ 
   //do something 
   return (param2) => { 
     //do something   
     return (param3) => { 
        return finalResult;    
     }  
   }
}

The final function in the chain has access to all the arguments in the chain. The fun part with curried functions is that you still have access to the functions inside the curried function.

let someParam = fakeFunction(param1);
let anotherParam = someParam(param2);
//and then when you call it...
console.log(anotherParam(param3));

Where Would You Use Currying? when you have a bunch of functions that need to perform in a particular order.

https://www.dottedsquirrel.com/currying-javascript/

33
Q

What is hoisting?

A

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution, regardless of whether their scope is global or local.

Note that the hoisting mechanism only moves the declaration. The assignments are left in place.

34
Q

What is Strict Mode?

A

It is a restricted variant of JavaScript that will not tolerate the usage of variables before they are declare. Use strict has stopped you by throwing a Reference error.

‘use strict’;
console.log(hoist); // Output: ReferenceError: hoist is not defined
hoist = ‘Hoisted’;

35
Q

When declaring JavaScript functions and variables: what is order of precedence?

A

Variable assignment takes precedence over function declaration.
Function declarations take precedence over variable declarations.

Variable assignment over function declaration:

var double = 22;
function double(num) {
  return (num*2);
}
console.log(typeof double); // Output: number

Function declarations over variable declarations:

var double;
function double(num) {
  return (num*2);
}
console.log(typeof double); // Output: function
36
Q

What is Memoization?

A

It is an optimization technique that increases performance by caching results of function calls. It stores the previous results and then, it retrieves the results whenever needed in your program. This reduces execution time and increases CPU performance.

A memoized function should be a pure function. This means the function execution does not mutate. When called with a certain input, it should always returns the same value regardless of how many times the function will be called.

Assuming you have a function that executes not one, not two-times, but several times, why not memorize the result of that function. This way, you only execute this function once. This makes your program more performance efficient.

When to use Memoization:

When a function is pure. A pure function always returns the same value when called. If a function is impure, it returns different values whenever executed. Caching such values may result in unexpected return values.

Heavy computing functions. Whenever a program has expensive computation, caching the results will significantly increase your program performance. With Memoization, the function doesn’t have to recalculate its values, yet it returns the same results whenever called.

Remote API calls. When making an API call repeatedly, using Memoization will save you from making repetitive calls to the server. You already know the result when you made the first call, and thus there is no need to make the same call to get the same results.

A function that recalls itself with recurring input values, i.e., recursive functions.

https://www.section.io/engineering-education/an-introduction-to-memoization-in-javascript/

37
Q

How error handling works in JS?

A

“throw” statement is used to throw an exception, and “try … catch” statement is used to handle it.

…} else {
throw “InvalidMonthNo”; //throw keyword is used here
}…

try { 
  monthName = getMonthName(myMonth); 
}
catch (e) {
  monthName = "unknown";
  logMyErrors(e); 
}
38
Q

When GC removes an object from memory?

A

Garbage collector monitors all objects and removes those that have become unreachable. “Reachable” values are those that are accessible or usable somehow. They are guaranteed to be stored in memory.

let user = {
  name: "John"
};

user = null;

Now John becomes unreachable. There’s no way to access it, no references to it. Garbage collector will junk the data and free the memory.

39
Q

If the array is declared as ‘const’, I can add a new value? … And what can I not do?

A

Yes. But you cannot assign a new array to a variable.

40
Q

Module systems, what they are for and what problem do they help us solve?

A

A module is just a file. One script is one module.

Modules can load each other and use special directives ‘export’ and ‘import’ to interchange functionality, call functions of one module from another one:

  • export keyword labels variables and functions that should be accessible from outside the current module.
  • import allows the import of functionality from other modules.

By using modules, it is easier to maintain the code, makes it easier to test the program and find bugs.

41
Q

What is Template string/Template Literals?

A

This is when you use back-ticks ( ).
By using the backticks, you can freely use the single or double quotes in the template literal without escaping.

The big difference between a template literal and a normal string is substitutions. The substitutions allow you to pass variables and expressions in a string. To instruct JavaScript to substitute a variable and expression, you place the variable and expression in a special block as follows:

${variable_name}

42
Q

What are default function parameters and what problem do they help to solve?

A

This is a function parameter that has a default value. If the user does not pass a value for the parameter to the function, then the default value is used. If the user passes a value, then the passed value is used instead of the default. This way we can override the value or not, but function anyway get value.

If you pass ‘null’ as a parameter, the default value will not be assigned. The ‘default value’ is triggered when nothing was passed to the function, or when ‘undefined’ was passed explicitly (в явном виде).

43
Q

How does an arrow function works with context?

A

it takes ‘this’ from the top context. (? see again)

44
Q

Do I have to write ‘return’ in an arrow function?

A

if after arrow there sre {} - it is mandatory, since you are declaring the body of the function, and ‘return’ must be written.

If there are no brackets - no need to write, it returns by default what comes after the arrow.

45
Q

What is destructuring for?

A

This is a way to retrieve data, to access the elements of an object (array).

const {name, surname} = object

(for example, when destructuring the received data from the server)

46
Q

What is paradigm?

A

It is style of programming, it’s how you write the program. There are imperative and declarative programming. Imperative - when you write a list of instructions to tell the computer what to do step by step. And then get result. In an imperative programming paradigm, the order of the steps is crucial. Declarative - we focuse on what needs to be achieved instead of instructing how to achieve it. So the main differences are that imperative tells youhow to do somethingand declarative tells youwhat to do.

47
Q

What is a Function?

A

A function is a block of code that can be called any number of times to get the functionality done and sometimes the result returned.

48
Q

How does a Generator function work?

A
  1. Calling a Generator function does not execute the function completely as soon as its called. It will return an iterator object that can be used to use the function.
  2. So this function can be executed part by part, where these parts are decided by the yield expression. ( Code explanation below, don’t worry ).
  3. To execute these parts, the .next() method is used on the iterator. When the .next() method is called, the function resumes execution until the next yield is found, or the function completes or a return statement is executed.
  4. Everytime you execute the .next() method, the generator function returns you with an object that looks like this:

{
value: ‘some-value’,
done: false
}

The value here is the value sent by the yield and the doneindicates if the generator function has run completely.

https://dev.to/developertharun/4-ways-to-use-generator-functions-in-javascript-examples-advantages-2ohd

49
Q

What are Generator Functions?

A

A Generator function returns us an iterator, which can be used to stop the function in the middle, do something, and then resume it whenever. A normal function starts executing and returns when the function completes, but a Generator function can be stopped any number of times and resumed later.

Generator functions are defined using the * asterisk either immediately after the function keyword or right before the function name.

The .next() method is used on the iterator. When the .next() method is called, the function resumes execution until the next yield is found, or the function completes or a return statement is executed. Everytime you execute the .next() method, the generator function returns you with an object that looks like this:

{
value: ‘some-value’,
done: false
}

The value here is the value sent by the yield and the done indicates if the generator function has run completely.

The below example creates an infinite number of natural numbers, which can be used when needed.

    function* naturalNumbers() {
        let number=1;
        while (true)
            yield number++;
    }
var naturalNumberIterator = naturalNumbers();

console. log(naturalNumberIterator.next().value);
console. log(naturalNumberIterator.next().value);
console. log(naturalNumberIterator.next().value);
console. log(naturalNumberIterator.next().value);

The output for the above code:

1
2
3
4

https://dev.to/developertharun/4-ways-to-use-generator-functions-in-javascript-examples-advantages-2ohd

50
Q

Advantages of using Generators? Why Should you use them?

A
  1. Lazy Evaluation - Run only when you need

Say there is an Infinite Stream of data, we cannot spend our whole life evaluating that data. Hence we can use Generator function to evaluate as and when required.

  1. Memory Efficient

As the Lazy Evaluation method is used, only those data and those computations that are necessary, are used.

https://dev.to/developertharun/4-ways-to-use-generator-functions-in-javascript-examples-advantages-2ohd

51
Q

Which variable is an implicit parameter in javascript?

A
  1. Implicit Parameter - this
    The this parameter refers to the object that invoked the function. This is why this parameter is also known as function context.
  2. The arguments parameter is an implicit parameter for every function in JavaScript.
52
Q

What is ‘async’ attribute?

A

The async attribute means that a script is completely independent. The ‘async’ scripts load in the background and run when ready. The DOM and other scripts don’t wait for them, and they don’t wait for anything. A fully independent script that runs when loaded.

Here’s an example: two scripts long.js and small.js

They don’t wait for each other. Whatever loads first – runs first:

<p>...content before scripts...</p>

document.addEventListener(‘DOMContentLoaded’, () => alert(“DOM ready!”));

<p>...content after scripts...</p>

Async scripts are great when we integrate an independent third-party script into the page: counters, ads and so on, as they don’t depend on our scripts, and our scripts shouldn’t wait for them.

53
Q

What is ‘defer’ attribute?

A

The ‘defer’ attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built.

Here’s the example:

<p>...content before script...</p>

<p>...content after script...</p>

In other words:

Scripts with ‘defer’ never block the page. Scripts with ‘defer’ always execute when the DOM is ready (but before DOMContentLoaded event).

Deferred scripts keep their relative order, just like regular scripts. Let’s say, we have two deferred scripts: the long.js and then small.js

Browsers scan the page for scripts and download them in parallel, to improve performance …But the defer attribute, besides telling the browser “not to block”, ensures that the relative order is kept. So even though small.js loads first, it still waits and runs after long.js executes.

That may be important for cases when we need to load a JavaScript library and then a script that depends on it.

The defer attribute is only for external scripts. The defer attribute is ignored if the tag has no src.

54
Q

What is Set?

A

Set – is a collection of unique values.

Methods and properties:

new Set([iterable]) – creates the set, with optional iterable (e.g. array) of values for initialization.

set. add(value) – adds a value (does nothing if value exists), returns the set itself.
set. delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
set. has(value) – returns true if the value exists in the set, otherwise false.

set. clear() – removes everything from the set.
set. size – is the elements count.

Iteration over Set is always in the insertion order, so we can’t say that these collections are unordered, but we can’t reorder elements or directly get an element by its number.

55
Q

Typescript: What is generics?

A

When you able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types.

56
Q

Typescript: What is tuples?

A

A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.

type StringNumberPair = [string, number];