CodeBlog.xyz

50 intermediate javascript questions

September 6, 2023 | by Meir Achildiev

javascript questions

Here are 50 intermediate-level JavaScript questions along with their answers and code examples:

  1. What is Hoisting in JavaScript?
    • Hoisting is JavaScript’s behavior of moving declarations to the top of their containing scope. Note that only the declarations are hoisted, not the initializations.
   console.log(myVar); // undefined
   var myVar = 5;
   console.log(myVar); // 5
  1. What are JavaScript Prototypes?
    • Prototypes are the mechanism by which JavaScript objects inherit features from one another. The prototype is a property on a constructor function that sets what will become the __proto__ property on the constructed object.
   function Person(firstName, lastName) {
     this.firstName = firstName;
     this.lastName = lastName;
   }

   Person.prototype.fullName = function() {
     return this.firstName + ' ' + this.lastName;
   }

   const person = new Person('John', 'Doe');
   console.log(person.fullName()); // "John Doe"
  1. What is Event Bubbling in JavaScript?
    • Event bubbling is a type of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
   document.querySelector("#parent").addEventListener('click', (event) => {
     alert("Parent Clicked!");
   }, false);

   document.querySelector("#child").addEventListener('click', (event) => {
     alert("Child Clicked!");
     event.stopPropagation();
   }, false);
  1. What is Event Delegation in JavaScript?
    • Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is fired on the descendant elements due to event bubbling up the DOM.
   document.querySelector("#parent").addEventListener('click', function(event) {
     if (event.target.matches("#child")) {
       alert("Child Clicked!");
     }
   });
  1. What is a JavaScript Class?
    • JavaScript Classes are a template for creating objects. They encapsulate data with code to manipulate that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.
   class Rectangle {
     constructor(height, width) {
       this.height = height;
       this.width = width;
     }

     area() {
       return this.height * this.width;
     }
   }

   const rectangle = new Rectangle(5, 8);
   console.log(rectangle.area()); // 40
  1. What is a JavaScript Promise?
    • A Promise in JavaScript represents a value which may not be available yet, but will be available in the future, or it will never be available.
   var promise = new Promise(function(resolve, reject) {
     // a mock async action using setTimeout
     setTimeout(function() {
       resolve('Done!');
     }, 1000);
   });

   promise.then(function(value) {
     console.log(value);
     // "Done!"
   });
  1. What is ‘this’ keyword in JavaScript?
    • The JavaScript this keyword refers to the object it belongs to. It has different values depending on where it is used: In a method, this refers to the owner object and in a function, this refers to the global object.
   // In object method
   var person = {
     firstName: "John",
     lastName : "Doe",
     id     : 5566,
     fullName : function() {
       return this.firstName + " " + this.lastName;
     }
   };
   console.log(person.fullName()); // John Doe

   // In regular function
   function myFunction() {
     return this;
   }
   console.log(myFunction() === window); // true in a browser
  1. What is an Immediately Invoked Function Expression (IIFE)?
    • An IIFE is a function in JavaScript that runs as soon as it is defined.
   (function () {
     var name = 'Hello World';
     console.log(name);
   })(); // Hello World
  1. What are JavaScript data types?
    • JavaScript data types include:
  • Number
  • String
  • Boolean
  • Object
  • Undefined
  • Null
  • Symbol
  1. What is a constructor function in JavaScript?
    • A constructor function is a function that is used to instantiate new objects with properties and methods defined by that function.
   function Car(make, model, year) {
     this.make = make;
     this.model = model;
     this.year = year;
   }

   var myCar = new Car('Toyota', 'Corolla', 2005);
   console.log(myCar.model); // "Corolla"
  1. What are getter and setter methods in JavaScript?
    • Getters and setters are functions or methods used to get and set the values of variables. The get and set syntax binds an object property to a function that will be called when that property is looked up or set.
   class Circle {
     constructor(radius) {
       this._radius = radius;
     }

     get radius()

 {
       return this._radius;
     }

     set radius(radius) {
       if (radius > 0) {
         this._radius = radius;
       }
     }
   }

   let circle = new Circle(5);
   console.log(circle.radius); // 5
   circle.radius = 10;
   console.log(circle.radius); // 10
  1. What are Arrow Functions in JavaScript?
    • Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope.
   const greet = () => 'Hello, World!';
   console.log(greet()); // "Hello, World!"
  1. What is a closure in JavaScript?
    • A closure is the combination of a function and the lexical environment within which that function was declared. In other words, a closure gives you access to an outer function’s scope from an inner function.
   function makeAdder(x) {
     return function(y) {
       return x + y;
     };
   }

   var add5 = makeAdder(5);
   console.log(add5(2));  // 7
  1. How can you make a property of a JavaScript object private?
    • In JavaScript, we can’t make object properties truly private, but we can emulate this behavior using closures.
   function Person(name) {
     var _name = name;

     this.getName = function() {
       return _name;
     };
   }

   var john = new Person('John');
   console.log(john.getName()); // "John"
   console.log(john._name); // undefined
  1. What is a callback function in JavaScript?
    • A callback function is a function that is passed as an argument to another function, to be “called back” at a later time.
   function greet(name, callback) {
     console.log('Hello ' + name);
     callback();
   }

   greet('John', function() {
     console.log('The callback was invoked!');
   });
  1. What is the difference between == and === in JavaScript?
    • == compares values after performing any necessary type conversions. === does not do any type conversion (so if two values are not the same type, === will simply return false).
  2. What is the map() method in JavaScript?
    • The map() method creates a new array with the results of calling a provided function on every element in the calling array.
   var numbers = [1, 4, 9];
   var roots = numbers.map(Math.sqrt);
   console.log(roots); // [1, 2, 3]
  1. What is the reduce() method in JavaScript?
    • The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
   var numbers = [1, 2, 3, 4];
   var sum = numbers.reduce(function(prev, curr) {
     return prev + curr;
   });
   console.log(sum); // 10
  1. What are JavaScript Promises?
    • A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object from a function, to which you attach callbacks, instead of passing callbacks into a function.
   var promise = new Promise(function(resolve, reject) {
     var success = true;

     if (success) {
       resolve('Success!');
     } else {
       reject('Failure!');
     }
   });

   promise.then(function(value) {
     console.log(value); // "Success!"
   }, function(value) {
     console.log(value); // "Failure!"
   });
  1. What are JavaScript generators?
    • JavaScript generators are a special class of functions that simplify the task of writing iterators. A generator is a function that produces a sequence of results instead of a single value.
   function* idMaker() {
     let id = 0;

     while (true) {
       yield id++;
     }
   }

   const gen = idMaker();

   console.log(gen.next().value); // 0
   console.log(gen.next().value); // 1
  1. What is ‘use strict’ in JavaScript?
    • ‘use strict’ is a literal expression that was introduced in ECMAScript 5, which helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example:
   'use strict';
   x = 3.14; // This will cause an error because x is not declared
  1. What is a JavaScript Module?
    • JavaScript modules are reusable pieces of code that can be exported from one program and imported for use in another program. Modules are particularly useful for a number of reasons: maintaining a code’s organization, keeping the global scope clean, and for reusability.
   // lib.js
   export function hello() {
     return 'Hello, World!';
   }

   // main.js
   import { hello } from './lib';

   console.log(hello()); // "Hello, World!"
  1. What is the difference between JavaScript’s window, screen, and document objects?
    • The window object represents a window containing a DOM document. The document object represents the DOM in your web page. The screen object contains information about the user’s display.
  2. What is the JavaScript event loop?
    • The event loop is a single-threaded loop that monitors the call stack and checks if there is any work to be done in the task queue. If the call stack is empty and there are callback functions in the task queue, a function is dequeued and pushed onto the call stack to be executed.
  3. What are async functions in JavaScript?
    • Async functions enable us to write promise-based asynchronous code as if it were synchronous, but without blocking the main thread. They make code much cleaner and easy to read.
   async function myFunction() {
     const value = await someAsyncOperation();
     console.log(value);
   }
  1. What are JavaScript async/await keywords used for?
    • async and await make promises easier to write. async makes a function return a Promise, and await makes a function wait for a Promise.
   async function myFunction() {
     const value = await someAsyncOperation();
     console.log(value);
   }
  1. What are JavaScript decorators?
    • Decorators are a design pattern in JavaScript, achieved by annotating and modifying classes at design time.
   function readonly(target, key, descriptor) {
     descriptor.writable = false;
     return descriptor;
   }

   class Cat {
     @readonly
     meow() {
       console.log('Meow!');
     }
   }

   const cat = new Cat();
   cat.meow = function() { console.log('Woof!')

 }; // Error: Cannot assign to read only property 'meow' ...
  1. What is a Set in JavaScript?
    • A Set is a built-in JavaScript object that stores multiple values in a single variable. Set items are unique. Duplicates are not allowed.
   let mySet = new Set();
   mySet.add(1); 
   mySet.add(2);
   mySet.add(3);
   mySet.add(2); // Duplicate, won't be added.
   console.log(mySet); // Set(3) {1, 2, 3}
  1. What is a Map in JavaScript?
    • The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value.
   let map = new Map();
   map.set('name', 'John');
   map.set('age', 25);
   console.log(map.get('name')); // John
   console.log(map.get('age')); // 25
  1. What are JavaScript Symbols?
    • A Symbol is a unique and immutable primitive value and may be used as a key for an Object property.
   let sym1 = Symbol('Hello');
   let sym2 = Symbol('Hello');
   console.log(sym1 === sym2); // false, every symbol is unique
  1. What is the instanceof operator in JavaScript?
    • The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
   function Car(make, model, year) {
     this.make = make;
     this.model = model;
     this.year = year;
   }

   let auto = new Car('Honda', 'Accord', 1998);

   console.log(auto instanceof Car);  // true
  1. What are JavaScript template literals?
    • Template literals are string literals allowing embedded expressions. They were called “template strings” in prior editions of the ES2015 specification.
   let name = 'John';
   console.log(`Hello, ${name}!`); // "Hello, John!"
  1. How can you share code between files?
    • You can share code between files by exporting them from one file and importing them in another.
   // lib.js
   export function hello() {
     return 'Hello, World!';
   }

   // main.js
   import { hello } from './lib';

   console.log(hello()); // "Hello, World!"
  1. Why you might want to create static class members?
    • Static class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referred to. This can be useful when a value is shared across instances, for example, a software version number.
   class MyClass {
     static myStaticValue = 'Hello, World!';

     static myStaticMethod() {
       return MyClass.myStaticValue;
     }
   }

   console.log(MyClass.myStaticMethod()); // "Hello, World!"
  1. What is object destructuring in JavaScript?
    • Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.
   let obj = { first: 'John', last: 'Doe' };
   let {first: f, last: l} = obj;
   console.log(f); // "John"
   console.log(l); // "Doe"
  1. What are default parameters in JavaScript?
    • Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
   function multiply(a, b = 1) {
     return a * b;
   }

   console.log(multiply(5, 2)); // 10
   console.log(multiply(5)); // 5, because b will default to 1
  1. What are rest parameters in JavaScript?
    • The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
   function sum(...args) {
     return args.reduce((previous, current) => {
       return previous + current;
     });
   }

   console.log(sum(1, 2, 3, 4)); // 10
  1. What is JavaScript spread syntax?
    • Spread syntax allows an iterable (like an array or string) to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
   let arr1 = [0, 1, 2];
   let arr2 = [...arr1, 3, 4];
   console.log(arr2); // [0, 1, 2, 3, 4]
  1. What are JavaScript Iterators?
    • Iterators are objects which know how to access items from a collection one at a time, while keeping track of its current position within that sequence.
   const array1 = ['a', 'b', 'c'];

   // Array elements iteration using the Iterator
   let iterator1 = array1[Symbol.iterator]();

   console.log(iterator1.next().value); // expected output: "a"
   console.log(iterator1.next().value); // expected output: "b"
   console.log(iterator1.next().value); // expected output: "c"
  1. How can you copy an object in JavaScript?
    • One way to create a copy of an object is with the Object.assign() method.
   let obj = {a: 1, b: 2};
   let copy = Object.assign({}, obj);
   console.log(copy); // {a: 1, b: 2}

Another way is by using the spread syntax.

   let obj = {a: 1, b: 2};
   let copy = {...obj};
   console.log(copy

); // {a: 1, b: 2}

Note that these methods perform a shallow copy of the object. Nested objects are copied by reference, not duplicated.

RELATED POSTS

View all

view all