Javascript
Tags: javascript, programming, node, github
Published: 2022-05-10 15:19:10

 

   **Different Data Types in JavaScript**:
    •**Boolean**: a Boolean is a logical data type that can have only the values true or false.The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false. It is a special case of a more general logical data type.
    • **BigInt**: The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit for Numbers.
    • **String**: String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String.
    • **Symbol**: A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called "atoms".

•**Not A Number (NaN)**:  Not a Number is typically encountered when the result of an arithmetic operation cannot be expressed as a number. It is also the only value in JavaScript that is not equal to itself.

•**Hoisting In Javascript**: Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.
    

**Difference between “==” and “===” Operators**:
  The main difference between the **“==”** and **“===”** operator in javascript is that the **“==”** operator does the type conversion of the operands before comparison (coercion), whereas the **“===”** operator compares the values as well as the data types of the operands. 

    

**Implicit Type Coercion In Javascript**: Implicit coercion happens when JavaScript coerces the value type to the expected type under the hood. This type of coercion happens without the developer noticing.
    

**Is Javascript A Statically Typed Or A Dynamically Typed Language?**:
JavaScript is called a dynamic language because it doesn't just have a few dynamic aspects, pretty much everything is dynamic. All variables are dynamic (both in type and existence), and even the code is dynamic. You can create new variables at runtime, and the type of variables is determined at runtime.New functions can be created at any time and existing functions can also be replaced at any time
     

**NaN Property In JavaScript**:
NaN stands for Not a Number. It represents a value which is not a valid number. It can be used to check whether a number entered is a valid number or not a number.
    

**Passed By Value And Passed By Reference**: Pass by value refers to a mechanism of copying the function parameter value to another variable while the pass by reference refers to a mechanism of passing the actual parameters to the function. Thus, this is the main difference between pass by value and pass by reference.


**Changes**

In pass by value, the changes made inside the function are not reflected in the original value. On the other hand, in pass by reference, the changes made inside the function are reflected in the original value. Hence, this is another difference between pass by value and pass by reference.


**Actual Parameter**

Moreover, pass by value makes a copy of the actual parameter. However, in pass by reference, the address of the actual parameter passes to the function.


**Association with Function**

Another difference between pass by value and pass by reference is that, in pass by value, the function gets a copy of the actual content whereas, in pass by reference, the function accesses the original variable’s content.
**Memory Requirement**
Besides, the pass by value requires more memory than pass by reference.


**Time Requirement**

Time requirement is one other difference between pass by value and pass by reference. Pass by value requires more time as it involves copying values whereas pass by reference requires a less amount of time as there is no copying.

    

**Immediately Invoked Function In Javascript**: 
Immediately-Invoked Function Expressions (IIFE), pronounced "iffy", are a common JavaScript pattern that executes a function instantly after it's defined. Developers primarily use this pattern to ensure variables are only accessible within the scope of the defined function. Immediately-Invoked Function Expressions are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.
    

**Higher Order Functions In Javascript**: In Javascript, functions can be assigned to variables in the same way that strings or arrays can. They can be passed into other functions as parameters or returned from them as well. A “higher-order function” is a function that accepts functions as parameters and/or returns a function.
 

**“this” Keyword In Javascript**: **“this”** keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function,** “this”** references the global object. If the function that is being referenced is a method in an object, **“this”** references the object itself.


**The call(), apply() and, bind() methods**: The call() , apply(), and bind() methods can be used to tie a function into an object and call the function as if it belonged to that object.

**The call() method** invokes a function with a specified context. In other words, you can tie a function into an object as if it belonged to the object. Example: 

```
var obj = { num: 2  };
function add(a, b){
return this.num + a + b;
}
console.log(add.apply(obj, [3, 5]));
```
Output: 
```
10
```

**The apply() method** takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list. 

```
var obj = { num: 2  };
function add(a, b){
return this.num + a + b;
}
console.log(add.apply(obj, [3, 5]));
```
Output: 

```
10
```

**The bind() method** allows an object to borrow a method from another object without making a copy of that method. Example: 
      

```
var obj = { num: 2  };
      function add(a, b){
return this.num + a + b;
}
const func = add.bind(obj, 3, 5);
func(); //Returns 10
```

      
      

**Currying In Javascript**: Currying is an advanced technique of working with functions. Currying is when a function instead of taking all arguments at one time takes the first one and returns a new function, which takes the second one and returns a new function, which takes the third one, etc. until all arguments are completed. Example:
  We’ll create a helper function curry(f) that performs currying for a two-argument f. In other words, curry(f) for two-argument f(a, b) translates it into a function that runs as f(a)(b):


```
function curry(f) { //(f) does the currying transform
return function(a) {
return function(b) {
return f(a, b);
};
};
}

// usage
function sum(a, b) {
return a + b;
}

let curriedSum = curry(sum);

alert( curriedSum(1)(2) ); // 3
```

 • The result of curry(func) is a wrapper function(a).
 • When it is called like curried Sum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
 • Then this wrapper is called with 2 as an argument, and it passes the call to the original sum.
          

**Scope And Scope Chain In JavaScript**: Scope is the way of accessing variables, functions, and objects in some particular part of your code during runtime. Scope provides some level of security to our code. Example:


```
//Global Variable
var num1 = 10;
var add = function(){
// Local Variable
var num2 = 20;
console.log(num1); \\ prints 10
console.log(num2); \\ prints 20
// Global Variable Accessible inside function 
return num1 + num2
}
console.log(num1); \\ prints 10
console.log(num2); \\ undefined error
console.log(add());\\ Print 30
```

**Scope chains** establish the scope for a given function. Each function defined has its own nested scope, and any function defined within another function has a local scope which is linked to the outer function — this link is called the chain. Example:


```
function parent() {
var name = 'Anabel';
console.log(name); 
// Reference error: age is not defined
console.log(age); 
// Reference error: places is not defined
console.log(places); 

function child() { 
// function linked to parent() that's why name is accessible.

var age = 23;
console.log(name); 
console.log(age);
// Reference error: places is not defined
console.log(places); 
function grandchild() { 
// this function is linked to child() & parent() that's why name, age are accessible.
var places = 'Coding';
console.log(name);
console.log(age);
console.log(places);
}
grandchild();
}
child();
}
parent();
```


Note: Any variable not declared without first being declared with the var keyword, it is automatically added to the global context which eventually becomes Global variable.



```
var Function = function () {
name = 'Anabel';
console.log(name); //Anabel
};
console.log(name); //Anabel
Function();
console.log(name); //Anabel
```


**Closures In Javascript**: A closure is a function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope. Example:


```
function greeting(message) {
   return function(name){
        return message + ' ' + name;
   }
}
let sayHi = greeting('Hi');
let sayHello = greeting('Hello');

console.log(sayHi('Joan')); // Hi Joan
console.log(sayHello('Joan')); // Hello Joan
```

• The greeting() function takes one argument named message and returns a function that accepts a single argument called name.
• The return function returns a greeting message that is the combination of the message and name variables.
• The greeting() function behaves like a function factory. It creates sayHi() and sayHello() functions with the respective messages Hi and Hello.
• The sayHi() and sayHello() are closures. They share the same function body but store different scopes.
• In the sayHi() closure, the message is Hi, while in the sayHello() closure the message is Hello.




** Object Prototypes In Javascript**: The prototype is an object that is associated with every functions and objects by default in JavaScript, where function's prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. The prototype object is special type of enumerable object to which additional properties can be attached to it which will be shared across all the instances of it's constructor function.

Example:
  
    

```
Student() {
    this.name = 'Joan';
    this.gender = 'F';
}

Student.prototype.age = 19;

var studObj1 = new Student();
alert(studObj1.age); // 19

var studObj2 = new Student();
alert(studObj2.age); // 19
```


 

**Callbacks**: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.  A callback function can run after another function has finished. Example:
      
     

```
 function greeting(name) {
        alert('Hello ' + name);
	}
function processUserInput(callback) {
var name = prompt(‘Please enter your name.’);
callback(name);
}
processUserInput(greeting);
```



Note: This is a synchronous callback as it is executed immediately.

**Memoization**:  Memoization is an optimization technique where expensive function calls are cached such that the result can be immediately returned the next time the function is called with the same arguments. This concept is relative to the application of functional programming. In many instances, you’ll reuse functions within a program. With the concept of Memoization, when a function is called, its result will temporarily be stored. Any computation that needs the result of this function will not have to execute that function again. Instead, it will reuse the stored result from the previous execution. Example: 


```
const clumsysquare = num =>{
let result = 0;
for  (let i =1; i <= num; i++) {
for (let j 1; j <= num; j++) {
result ++;
}
}
return result;
}
console.log(clumsysquare(4));
console.log(clumsysquare(10));
console.log(clumsysquare(12));
console.log(clumsysquare(17));
console.log(clumsysquare(20));
```


We will realize that it will re-execute the function whenever you call it and then return a squared value.

• **Recursion In A Programming Language**: Recursion is a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself in a step having a termination condition so that successive repetitions are processed up to the critical step where the condition is met at which time the rest of each repetition is processed from the last one called to the first.

• **Use Of A Constructor Function In Javascript**: A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword.
The purpose of a constructor is to create a new object and set values for any existing object properties. Example:


```
//Constructor
function User() {
this.name = ‘Joan’;
}

var user = new User
```


•**DOM**: Document Object Model (DOM) is a programming interface that allows us to create, change, or remove elements from the document. We can also add events to these elements to make our page more dynamic. The DOM views an HTML document as a tree of nodes. A node represents an HTML element.