JavaScript questions

  • Default Parameters
  • Template literals (`${}`)
  • Arrow function
  • let & const
  • Destructuring
  • Multiline string
  • Spread operator
  • rest parameter
  • Promises
  • Generator functions
  • Closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function.
  • It makes it possible for a function to have “private” variables
function myFunction() {
	var name = "Hello world";
	function displayName () {
		alert(name);
	}
	return displayName;
}
let myFunc = myFunction();
myFunc();

Here displayName() method is private method, meaning it can’t be access directly from outside

There are two ways to copy objects in javascript.

  • Shallow copy: A copy of the original object is stored and only the reference address is finally copied
  • Deep copy: The copy of the original object and the repetitive copies both are stored

Example

 // Shallow copy
 let employee = {
    firstname: 'John',
    lastname: 'Don'
 };

 let copyEmployee = employee; // copyEmployee object hold reference of employee.
 copyEmployee.firstname = 'Jack';
 console.log(employee.firstname, copyEmployee.firstname); // Output: Jack Jack

 // Deep copy
 let department = {
   name: 'IT',
   category: {
      value: 'Finance'
   }
 };

 let copyDepartment = JSON.parse(JSON.stringify(department));
 copyDepartment.category.value = 'Marketing';
 console.log(department.category.value, copyDepartment.category.value); // Output: Finance Marketing

Different ways to copy the object

  • Shallow copy: Object.assign(), spread operator(…), directly assign using equal to (=)
  • Deep copy: JSON.parse(JSON.stringify(obj)) and other 3rd party libraries like lodash (cloneDeep function)
  • Object.freeze() – It will make object immutable, we can not change/add/delete its properties value but we can reassign it.
  • Object.seal() – Same as Object.freeze() but we can update object property value as its writable.
  • Regular functions return only one, single value (or nothing), where generators can return (“yield”) multiple values, one after another, on-demand.
  • We CAN NOT create generator function with arrow operator.
  • Example:
function* generator(i) {
	yield i;
	yield i + 10;
};
const gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 20

We can use XMLHttpRequest object to create http request in javascript.

Example

let xhr = new XMLHttpRequest();
xhr.open('GET', "https://ipinfo.io/json", true); // Request type, url, Asynchronous/Synchronous(true/false)
xhr.send();
		
xhr.onreadystatechange = () => {
       if (xhr.readyState == 4 && xhr.status == 200) {
		let response = JSON.parse(xhr.responseText);
		document.querySelector("#ipText").innerHTML = response.ip;
       }
}
  1. let a = {}; // Using object literal
  2. let b = Object.create(); // Using create() method
  3. let c = new Employee(); // Using new keyword
  4. Using ES6 classes
constructor(name, maker, engine) {
	this.name = name;
	this.maker =  maker;
	this.engine = engine;
    }
}
let car1 = new Vehicle('GT', 'BMW', '1998cc');

Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array.

const printNumber = (a, b, ...args) => {
	console.log(a, b);
	console.log(args);
   }
printNumber(1, 2); // Output: 1 2
printNumber(1, 2, 3, 4); // Output: 3 4
  • Object.freeze(ObjName)
  • Object.preventExtensions(ObjName)
  • Object.seal(ObjName)

The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand

var age = 20;
age = (age++, age);
console.log(age); // Output: 21

Both are comparison operators. The difference between both the operators is that,“==” is used to compare values whereas, “ === “ is used to compare both value and types.
Example

let no1 = 20;
let no2 = "20";
(no1 == no2)  // Returns true since the value of both no1 and no2 is the same

(no1 === no2) // Returns false since the typeof no1 is "number" and typeof no2 is "string"

NaN property represents “Not-a-Number” value. It indicates a value which is not a legal number.
typeof NaN; // return Number
Example

isNaN("Hello")  // Returns true
isNaN(345)   // Returns false
isNaN('1')  // Returns false, since '1' is converted to Number type which results in 0 ( a number) 
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true

An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.
Example

(function(){ 
  console.log('IIFE');
})();

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.
Example

function memoizedAddTo256(){
  var cache = {};

  return function(num){
    if(num in cache){
      console.log("cached value");
      return cache[num]

    }
    else{
      cache[num] = num + 256;
      return cache[num];
    }
  }
}

var memoizedFunc = memoizedAddTo256();

memoizedFunc(20); // Normal return
memoizedFunc(20); // Cached return

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top