en programming language golang 非公開: JavaScript interview common questions and answers

JavaScript interview common questions and answers

Incorporating JavaScript into your portfolio increases your chances of landing a software developer role. That said, let’s take a look at some common JavaScript interview questions.

JavaScript is one of the most commonly used languages ​​for web development. It is currently used to develop almost every type of application.

Before we get into the interview questions, let’s take a look at the benefits of learning JavaScript.

JavaScript
JavaScript

JavaScript is a lightweight, interpreted, or just-in-time compiled programming language. It is one of the core languages ​​of the World Wide Web. You probably know the other two core languages ​​of www. If you don’t have it, you should search for it.

JavaScript is primarily written for the web. But it’s not just the web now. It can run on almost any platform with the help of environments like Node, Deno, etc.

Let’s check out some of the benefits.

Advantages of JavaScript

  1. It’s easy to get started. You can learn without any coding knowledge.
  2. There’s a big community around it. If you get stuck somewhere, you’ll get all the help you need.
  3. There are many libraries/frameworks built using JavaScript that can help speed up application development.
  4. You can develop front-end, back-end, Android, iOS, and other applications with JavaScript. You can use it to create almost any kind of application. However, it is more robust for web development.
JavaScript interview common questions and answers
JavaScript interview common questions and answers

What are data types in JavaScript?

Data types are used to store different types of data. Data types vary by programming language. JavaScript has eight data types. Let’s look at them one by one.

  • number
  • string
  • boolean value
  • undefined
  • null
  • BigInt
  • symbol
  • object

All data types except Object are called primitive values. And they are unchanging.

JavaScript interview common questions and answers
JavaScript interview common questions and answers

What are JavaScript built-in methods?

JavaScript has different built-in methods for each data type. You can access these built-in methods using each data type. Let’s take a look at some of the built-in methods for different data types and data structures.

  1. number
    • to fixed
    • toString
  2. string
    • to lower case
    • starts with
    • on the chart
  3. array
    • filter
    • map
    • to each

Each data type has many built-in methods. You can find a reference for all built-in methods for various data types and data structures.

JavaScript interview common questions and answers
JavaScript interview common questions and answers

How do I create an array in JavaScript?

Arrays are one of the core data structures in JavaScript. Because JavaScript is dynamic, arrays can contain any type of data. Let’s see how to create an array in JavaScript.

You can create arrays using square brackets [] . Creating objects is easy and fast

 // Empty array
const arr = [];

// Array with some random values
const randomArr = [1, "One", true];

console.log(arr, randomArr);

You can create an array using Array constructor. In a typical project, constructors are rarely used to create arrays.

 // Empty array
const arr = new Array();

// Array with some random values
const randomArr = new Array(1, "One", true);

console.log(arr, randomArr);

JavaScript arrays are mutable. This means that you can modify it as needed after it is created.

JavaScript interview common questions and answers
JavaScript interview common questions and answers

How do I create objects in JavaScript?

Apart from arrays, objects are another core data structure in JavaScript. Objects use key-value pair storage. The key must be an immutable value, but the value can be anything. Let’s take a look at how to create objects in JavaScript.

You can create objects using curly braces {} . Creating objects is easy and quick.

 // Empty object
const object = {};

// Object with some random values
const randomObject = { 1: 2, one: "Two", true: false };

console.log(object, randomObject);

You can create objects using Object constructor. Very few people use this in general projects.

 // Empty object
const object = new Object();

// Object with some random values
const randomObject = new Object();
randomObject[1] = 2;
randomObject["one"] = "Two";
randomObject[true] = false;

console.log(object, randomObject);

JavaScript objects are mutable. This means that you can modify it after it’s created, as you can see in the second example.

How do you debug JavaScript code?

Debugging code is not easy. And it varies from programming language to programming language and from project to project. Let’s take a look at some common ones used for debugging JavaScript.

#1.Logging

You can use console.log statements in multiple places in your code to identify bugs. If the previous line has a bug, the code will stop executing the next line.

Logging is an old debugging method that is very effective for small projects. This is a common debugging technique in any programming language.

#2.Developer tools

JavaScript is primarily used for developing web applications. That’s why almost all browsers now include developer tools to help you debug your JavaScript code.

One of the most commonly used debugging methods is to set breakpoints in the developer tools. Breakpoints stop JavaScript execution and provide all information about execution at that point.

You can set multiple breakpoints around where the error is occurring to see what’s causing it. This is the most effective way to debug JavaScript web applications.

#3. IDE

You can use your IDE to debug JavaScript. VS Code supports debugging using breakpoints. Debugging features may vary depending on the IDE you are using. However, most IDEs have that functionality.

How do I add JavaScript code to an HTML file?

You can add JavaScript HTML files using script tag. You can see an example below.

 <!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
  </head>
  <body>
    <h1></h1>

    <script>
      // JavaScript code goes here
      console.log("This is JavaScript code");
    </script>
  </body>
</html>

What is a cookie?

Cookies are key-value pairs used to store small pieces of information. Any information is fine. Cookies can have an expiration date and are deleted after the expiry date. These are widely used to store user information.

Cookies are not erased by refreshing the page until you delete them or until they expire. You can view cookies for any web app/web page in any browser by opening the developer tools.

You can read cookies with JavaScript using document.cookie . All cookies created will be returned.

 console.log("All cookies", document.cookie);

If there is no cookie, an empty string is returned.

You can create a cookie by setting the key-value pair to document.cookie . Let’s look at an example.

 document.cookie = "one=One;";

In the above syntax, one cookie key and One are its values. You can add attributes to cookies, such as domain, path, and expiration date. Each must be separated by a semicolon (;) . All attributes are optional.

Let’s look at an example using attributes.

 document.cookie = "one=One;expires=Jan 31 2023;path=/;";

In the code above, we have added an expiration date and a path to the cookie. If no expiration date is specified, the cookie is deleted after the session. The default path will be the file path. The expiration date must be in GMT format.

Let’s see how to create multiple cookies.

 document.cookie = "one=One;expires=Jan 31 2023;path=/;";
document.cookie = "two=Two;expires=Jan 31 2023;path=/;";
document.cookie = "three=Three;expires=Jan 31 2023;path=/;";

If you set multiple cookies with different keys or paths, the cookies will not be overwritten. If the key and path are the same, the previous cookie will be overwritten. Check out the example below that overrides a previously set cookie.

 document.cookie = "one=One;expires=Jan 31 2023;path=/;";
document.cookie = "one=Two;path=/;";

Removed expiry date from cookie and changed value.

If you want to test whether your code works correctly, use an expiration date in the future. If you keep the same date Jan 31 2023 after Jan 31 2023 , no cookie will be created.

We’ve looked at how to create and update cookies. Let’s see how to delete cookies.

Deleting cookies is easy. Just change the cookie expiration date to a date in the past. Check the example below.

 // Creating cookies
document.cookie = "one=One;expires=Jan 31 2023;path=/;";
document.cookie = "two=Two;expires=Jan 31 2023;path=/;";
document.cookie = "three=Three;expires=Jan 31 2023;path=/;";

// Deleting the last cookie
document.cookie = "three=Three;expires=Jan 1 2023;path=/;";

The last cookie in the cookies is not found because the last cookie is deleted in the last line of code. This concludes the min cookie tutorial.

What are the different JavaScript frameworks?

There are many JavaScript frameworks. UI development using React, Vue, Angular, etc. For server-side development, such as Express, Koa, and Nest. For static site generation, such as NextJS and Gatsby. React Native, Ionic, etc. for mobile app development. We’ve covered some of the JavaScript frameworks here. You can find many more frameworks, but it takes time to explore them. Check it out when you need it.

Closures in JavaScript

A closure is a function bundled into its lexical scope and its parent lexical environment. Closures allow you to access data in the outer scope. Closures are formed when a function is created.

 function outer() {
  const a = 1;
  function inner() {
    // We can access all the data from the outer function scope here
    // The data will be available even if we execute this function outside the outer function 
    // as inners' closure formed while creating it
    console.log("Accessing a inside inner", a);
  }
  return inner;
}

const innerFn = outer();
innerFn();

Closures are widely used in JavaScript applications. You may have used closures before without realizing it was a closure. There’s a lot more to learn about closures. Please make sure you have fully learned this concept.

Hoisting in JavaScript

Hoisting is a process in JavaScript in which variable, function, and class declarations are moved to the top of scope before the code is executed.

 // Accessing `name` before declaring
console.log(name);

// Declaring and initializing the `name`
var name = "";

When I run the above code, no error is displayed. However, most languages ​​will give you an error. Hoisting only moves the declaration to the top and does not initialize it until line number 3, so the output is undefined .

Change var to let or const as follows and run the code again.

 // Accessing `name` before declaring
console.log(name);

// Declaring and initializing the `name`
const name = "";

Now I get a reference error saying that the variable cannot be accessed before initializing it.

 ReferenceError: Cannot access 'name' before initialization

So here let and const are introduced in ES6, but as the error indicates, they are not accessible before initialization. This is because variables declared with let or const are in a temporary dead zone (TDZ) until the line where they are initialized. Variables cannot be accessed from TDZ.

Currying in JavaScript

Currying is a technique that transforms a function with many parameters into a small number of parameters with multiple callable parameters. This allows you to convert a callable function add(a, b, c, d) to a callable add(a)(b)(c)(d). Let’s look at an example of how to do that.

 function getCurryCallback(callback) {
  return function (a) {
    return function (b) {
      return function (c) {
        return function (d) {
          return callback(a, b, c, d);
        };
      };
    };
  };
}

function add(a, b, c, d) {
  return a + b + c + d;
}

const curriedAdd = getCurryCallback(add);

// Calling the curriedAdd
console.log(curriedAdd(1)(2)(3)(4));

The getCurryCallback function can be generalized and used to convert various functions into curried callables. For more information, see JavaScript information .

Difference between document and window

window is the top object of the browser. This includes all information about your browser window, such as history, location, navigator, etc. Available worldwide with JavaScript. You can use it directly in your code without importing it. You can access properties and methods of window object without a window window.

Part of document window object. All HTML loaded into a web page is converted into a document object. The document object refers to a special HTMLDocument element. This element, like all HTML elements, has various properties and methods.

window object represents a browser window, and document represents an HTML document loaded into the browser window.

Difference between client side and server side

Client-side refers to the end user who uses the application. Server-side refers to the web server where the application is deployed.

In front-end terminology, the browser on a user’s computer can be referred to as the client side, and the cloud service can be referred to as the server side.

Difference between innerHTML and innerText

innerHTML and innerText are both properties of the HTML element. You can use these properties to modify the content of HTML elements.

You can assign an HTML string to innerHTML a property that is rendered just like regular HTML. Check the example below.

 const titleEl = document.getElementById("title");

titleEl.innerHTML = '<span style="color:orange;"></span>';

Add one element with id title to your HTML and add the above script to your JavaScript file. Run the code and check the output. orange It will be. If you inspect the element, you’ll see that it’s inside a span tag. So innerHTML takes an HTML string and renders it as regular HTML.

innerText on the other side takes a regular string and renders it as is. HTML like innerHTML will not be rendered. Change innerHTML to innerText in the above code and check the output.

 const titleEl = document.getElementById("title");

titleEl.innerText = '<span style="color:orange;"></span>';

You will now see the exact string you provided on the web page.

Difference between let and var

let and var keywords are used to create variables in JavaScript. The let keyword was introduced in ES6.

let is block scoped and var is function scoped.

 {
  let a = 2;
  console.log("Inside block", a);
}
console.log("Outside block", a);

Run the above code. Since it’s block scoped, you can’t access let a outside the block, so you get an error on the last line. Now change it to var and run it again.

 {
  var a = 2;
  console.log("Inside block", a);
}
console.log("Outside block", a);

You can also access a outside the block, so no error occurs. Next, let’s replace blocks with functions.

 function sample() {
  var a = 2;
  console.log("Inside function", a);
}
sample();
console.log("Outside function", a);

Since it is function scoped, you cannot access var a it from outside the function, so you will get a reference error when you run the above code.

You can redeclare a variable using var keyword, but you cannot redeclare a variable using the let keyword. Let’s look at an example.

 var a = "";
var a = "Chandan";
console.log(a);
 let a = "";
let a = "Chandan";
console.log(a);

The first part of the code does not throw an error and the value changes to the value assigned to a . The second part of the code throws an error because the variable cannot be redeclared using let .

Difference between session storage and local storage

Session storage and local storage are used to store information on a user’s computer that can be accessed without the Internet. Key-value pairs can be stored in both session storage and local storage. If you specify any other data type or data structure, both keys and values ​​are converted to strings.

Session storage is cleared after the session ends (when the browser is closed). Location storage won’t be cleared until you clear it.

sessionStorage and localStorage objects can be used to access, update, and delete session storage and location storage, respectively.

What are NaNs in JavaScript?

NaN is abbreviated as Not-a-Number . This means that something is not a valid number in JavaScript. You may get it as NaN output like 0/0 , undefined * 2 , 1 + undefined , null * undefined etc.

What is lexical scope?

Lexical scoping refers to accessing variables from the parent’s scope. Suppose we have a function with two internal functions. The innermost function can access the scope variables of its two parent functions. Similarly, second-level functions can access the outermost function scope. Let’s look at an example.

 function outermost() {
  let a = 1;
  console.log(a);
  function middle() {
    let b = 2;
    // `a` are accessible here
    console.log(a, b);
    function innermost() {
      let c = 3;
      // both `a` and `b` are accessible here
      console.log(a, b, c);
    }
    innermost();
  }
  middle();
}
outermost();

JavaScript uses scope chains to locate variables when you access them anywhere in your code. First, check the variables in the current scope, then check the parent scope up to the global scope.

What is passing by value and passing by reference?

Passing by value and passing by reference are two ways to pass arguments to functions in JavaScript.

Pass by value: Create a copy of the original data and pass it to the function. Therefore, any changes you make to the function do not affect the original data. Check the example below.

 function sample(a) {
  // changing the value of `a`
  a = 5;
  console.log("Inside function", a);
}
let a = 3;
sample(a);
console.log("Outside function", a);

You can see that even though we changed a within the function, the original value of a remains unchanged.

Pass by reference: Pass a reference of data to a function. Therefore, any changes you make to the function will also change the original data.

 function sample(arr) {
  // adding a new value to the array
  arr.push(3);
  console.log("Inside function", arr);
}
let arr = [1, 2];
sample(arr);
console.log("Outside function", arr);

You can see that when you change arr inside the function, it changes the original value.

Note: All primitive data types are passed by value, and non-primitive data types are passed by reference.

What is memoization?

Memoization is a technique that stores computed values ​​in a cache and uses them when needed without having to compute them again. If the calculations are very heavy, the code will run faster. There is a storage trade-off, but it’s not as big an issue compared to time.

 const memo = {};
function add(a, b) {
  const key = `${a}-${b}`;

  // checking whether we computed the value already or not
  if (memo[key]) {
    console.log("Not computing again");
    return memo[key];
  }

  // adding the newly computed value to cache
  // here cache is a simple global object
  memo[key] = a + b;
  return memo[key];
}

console.log(add(1, 2));
console.log(add(2, 3));
console.log(add(1, 2));

This is a simple example demonstrating memoization. Now, adding two numbers together is not a very difficult calculation. This is for demonstration purposes only.

What are the remaining parameters?

Remaining parameters are used to collect all remaining parameters in the function. Suppose you have a function that accepts at least two arguments and can accept up to any number of parameters. Since there is no maximum number of arguments, you can collect the first two parameters with regular variables and all other parameters with the remaining parameters using the rest operator .

 function sample(a, b, ...rest) {
  console.log("Rest parameter", rest);
}

sample(1, 2, 3, 4, 5);

The remaining parameters will be an array of the last three arguments from the example above. This allows functions to have any number of parameters.

A function can have only one remaining parameter. And the remaining parameters must be the last parameters in the parameter order.

What is object splitting?

Object splitting is used to access variables from an object and assign them to a variable with the same name as the object key. Let’s look at an example.

 const object = { a: 1, b: 2, c: 3 };

// Object destructuring
const { a, b, c } = object;

// Now, a, b, c will be used as normal variables
console.log(a, b, c);

You can change variables in a structured variable on the same line like this:

 const object = { a: 1, b: 2, c: 3 };

// Changing the names of `a` and `b`
const { a: changedA, b: changedB, c } = object;

// Now, changedA, changedB, c will be used as normal variables
console.log(changedA, changedB, c);

What is array structuring?

Array structuring is used to access variables from arrays and assign them to variables. Let’s look at an example.

 const array = [1, 2, 3];

// Array destructuring
// It's based on the index of the array
const [a, b, c] = array;

// Now, we can use a, b, c as normal variables
console.log(a, b, c);

What is event capture and event bubbling?

Event capture and event bubbling are two methods of event propagation in the HTML DOM. Suppose you have two HTML elements, one inside another. And the event fires on the inner element. Here, the event propagation mode determines the order in which these events are executed.

Event bubbling: Executes an event handler first on an element, then on that element, and finally up to the top element. This is the default behavior for all events.

Capturing an event: The event must specify that this type of event propagation should be used. Can be specified when adding an event listener. When event capture is enabled, events are executed in the following order:

  1. The event starts executing from the top element to the target element.
  2. The target element’s event is executed again.
  3. Bubbling event propagation occurs again until the top element fires.

You can stop event propagation by calling the event handler’s method event.stopPropogation .

What is the JavaScript promise?

Promise objects are used for asynchronous operations that complete in the future with a success or failure status.

Promise can be in one of the following states:

  1. pending – when the operation is still in progress.
  2. fulfilled – When an operation completes successfully. The result (if any) is obtained in the success state.
  3. rejected – If the operation completed unsuccessfully. You can find out why it failed (error).

Let’s look at two examples of success and failure.

 // Promise which will complete successfully
const successPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve({ message: "Completed successfully" });
  }, 300);
});
successPromise
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

// Promise which will complete with failure state
const failurePromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(new Error("Failing the promise for testing"));
  }, 300);
});
failurePromise
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

You can then create multiple chains as needed. Previously returned data will be accepted in the next then callback.

Describe the different types of scopes in JavaScript

There are two types of scope in JavaScript. Global scope and local scope .

You may have also heard of function scope and block scope. These are local scope for var and let , const respectively.

What is a self-calling function?

A self-calling function is an unnamed function that is executed immediately after creation. Let’s look at some examples.

 // Without any parameters
(function sayHello() {
  console.log("Hello, World!");
})();

// With parameters
(function add(a, b) {
  console.log("Sum", a + b);
})(1, 2);

As we saw in the example, you can also pass arguments to self-calling functions.

What is an arrow function?

Arrow functions are syntactic sugar that is a regular function with some modifications. These behave like regular functions for common use cases. Arrow functions are useful when you need callbacks. Let’s take a look at its syntax.

 // arrow functions will return by default if it doesn't have any brackets
let add = (a, b) => a + b;

console.log(add(1, 2));

There are some differences between arrow functions and regular functions.

  • Arrow functions do not have their own this binding. this keyword inside an arrow function refers to its parent scope this .
  • Arrow functions cannot be used as constructor functions

What is a callback?

A callback is a function that is passed to another function that is called within that function. Using callbacks is common in JavaScript. Let’s look at an example.

 function sample(a, b, callback) {
  const result = a + b;
  callback(result);
}

function finished(result) {
  console.log("Finished with", result);
}

sample(1, 2, finished);

Passed to sample as the function finished callback. The finished function is called with the result after performing some action. The use of callbacks is primarily in asynchronous operations such as Promises, setTimeout, etc.

What are the different types of errors?

Let’s check the JavaScript errors.

ReferenceError : This error occurs when the variable you are accessing is not available.

TypeError: JavaScript throws this error if the error doesn’t match any other type of error. It also occurs when you try to perform an action that is incompatible with the data.

SyntaxError: This error occurs when JavaScript syntax is incorrect.

There are several other types of errors. However, these are common types of errors in JavaScript.

What are the different scopes of variables in JavaScript?

JavaScript has two scopes for variables. Variables declared using var keyword have function scope, and variables declared using let and const have block scope .

See question 17 for more information about the scope of these variables.

What is an escape character in JavaScript?

The backslash is an escape character in JavaScript. Used to print special characters that cannot normally be printed. Suppose you want to output apostrophe (') within a string. This is normally not possible because the string ends with a second apostrophe. In that case, use the escape character to prevent the string from terminating at that point.

 const message = 'Hi, I\'m ';
console.log(message);

The above output can be achieved without using escape characters by replacing the outer single apostrophe with a double apostrophe. However, this is just one example of how to use escape characters. There are other characters that always require escape characters, such as \n , \t , and \\ .

What are BOM and DOM?

Browser Object Model (BOM): Every browser has a BOM that represents the current browser window. It contains the top-level window object used to manipulate the browser window.

Document Object Model (DOM): Browsers create a DOM when HTML is loaded into a tree structure. You can manipulate HTML elements using the DOM API.

What is a screen object?

The screen object is one of the properties of the global window object. It contains various properties of the screen on which the current browser window is rendered. Some of the properties include width , height , Orientation , and PixelDepth .

conclusion

You may have additional questions to all of the above questions. Therefore, you should prepare concepts regarding all the above questions.

You can also look up frequently asked Java interview questions and answers.

Have fun learning 🙂

Easy-to-understand explanation of “Frequently asked questions and answers in JavaScript interviews”! Best 2 videos you must watch

エンジニアを面接で見極める質問3選【経験者/人事 必見】
https://www.youtube.com/watch?v=oXThFYSvVwI&pp=ygU2IEphdmFTY3JpcHQg6Z2i5o6l44Gn44KI44GP44GC44KL6LOq5ZWP44Go5Zue562UJmhsPUpB
「最後に言い残したことはありますか?」に対する一橋大生の回答!
https://www.youtube.com/shorts/CsezcC5CUgI