Interview Questions Flashcards
What is JavaScript?
JavaScript is a client-side/server-side programming language that can be inserted into otherwise static HTML pages to add page interactivity and enable user engagement.
What is hoisting in JavaScript?
Hoisting means all the declarations are moved to the top of the scope before the code is run.
For functions, this means you can call them from anywhere in the scope, even before they are defined.
For variables, hoisting is a bit different. It assigns undefined to them at the top of the scope.
Calling a variable before defining:
console.log(dog); var dog = "Spot"; Output:undefined
If you declare a function or variable, it is always moved on the top of the scope no matter where you declare it.
What does the isNan() function do?
You can use isNan() function to check if the type of a value is a number and it’s NaN. Returns true/false.
(And yes, NaN is of type number even though it’s a “Not-a-Number” by name. This is because it’s a numeric type under the hood, even though it does not have a numeric value.)
What is negative infinity in JavaScript?
You get a negative infinity if you divide a negative number with zero in JavaScript.
For instance:
console.log(-10/0)
Output:
-Infinity
What is an undeclared variable?
How about an undefined variable?
Undeclared variables do not exist in a program at all.
Undefined variables are declared in the program but don’t have a value. If the program tries to read an undefined variable, an undefined value is returned and the app does not crash.
What types of popup boxes are there in JavaScript?
The three types of popups are alert, confirm, and prompt. Let’s see an example use of each:
Alert
window.alert(“Hello, world!”);
Confirm if (window.confirm("Are you sure you want to go?")) { window.open("exit.html", "See you again!");}
Prompt let person = window.prompt("Enter your name"); if (person != null) { console.log('Hello', person); }
What is the difference between == and ===?
== compares values === compares both the value and the type
What does implicit type coercion do? Give an example.
Implicit type coercion means a value is converted from one type to another under the hood. This takes place when the operands of expressions are of different types.
For example, string coercion means applying + operator on a number and a string converts the number into a string automatically. For example:
var x = 1; var y = “2”;
x + y // Returns “12”
But when dealing with subtraction, the coercion works the other way. It converts a string into a number. For instance:
var x = 10; var y = “10”;
x - y // Returns 0
Is JavaScript statically or dynamically typed language? What does this mean?
JavaScript is dynamically typed.
This means the type of objects is checked during run-time. (In a statically typed language, the type is checked during compile-time.)
In other words, JavaScript variables are not associated with a type. This means you can change the data type with no problem.
What is NaN in JavaScript?
NaN means “Not-a-Number”. This means a value that is not officially a number in JavaScript.
What may be confusing is that type-checking NaN with typeof() function results in Number.
console.log(typeof(NaN))
Output: Number
To avoid confusion, use isNaN() to check if the type of a value is NaN or not number.
What is the spread operator in JavaScript?
Spread operator allows iterables ( arrays / objects / strings ) to be expanded into single arguments/elements.
function sum(a, b, c) { return a + b + c; } const nums = [15, 25, 35];
console.log(sum(…nums));
Output: 75
What is a closure in JavaScript?
A closure in JavaScript means an inner function has access to the variables of the outer function—even after the outer function has returned.
How to handle exceptions in JavaScript?
If an expression throws errors, you can handle them with the try…catch statement.
The idea of using this structure is to try running an expression, such as a function with an input, and catch the possible errors.
function weekDay(dayNum) { if (dayNum < 1 || dayNum > 7) { throw 'InvalidDayNumber' } else { return ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dayNum - 1]; } } try { // Try to run the following let day = weekDay(8); console.log(day); } catch (e) { // catch an error if the above try failed let day = 'unknown'; console.log(e); }
What Is web storage?
Web storage is an API that provides a way for browsers to store key-value pairs to the user’s browser locally. Using web storage makes this process way more intuitive than using cookies.
Web storage provides two ways for storing data:
Local storage — stores data for the client without an expiration date.
Session storage — stores data for only one session. The data is gone when the browser is closed.
// Save data to sessionStorage
sessionStorage.setItem(‘favoriteColor’, ‘gray’);
// Get the color from the sessionStorage
let data = sessionStorage.getItem(‘favoriteColor’);
console.log(data);
// Remove saved color preset from sessionStorage
sessionStorage.removeItem(‘favoriteColor’);
// Remove ALL the saved data from sessionStorage
sessionStorage.clear();
And here’s how you can do the same using the localStorage:
// Save data to localStorage
localStorage.setItem(‘favoriteColor’, ‘gray’);
// Get the color from the localStorage
let data = localStorage.getItem(‘favoriteColor’);
console.log(data);
// Remove saved color preset from localStorage
localStorage.removeItem(‘favoriteColor’);
// Remove ALL the saved data from localStorage
localStorage.clear();
Why do you need web storage?
Web storage makes it possible to store large amounts of data locally without affecting the performance of a website.
This information is not stored in a server, making it a more preferable approach compared to cookies.
What are modules?
Modules are units of reusable code. Usually, you can import a useful function or constructor to your project from the module.
Importing features from modules could look like this:
import { hello } from ‘./modules/helloWorld.js’;
What is meant by “scope” in JavaScript?
Scope describes where variables, functions, and other objects are accessible in the code. Scopes are created in your code during the runtime.
For example, a block scope means the “area” between curly braces:
What are higher-order functions in JavaScript?
A higher-order function operates on another function(s). It either takes a function as an argument or returns another function.
function runThis(inputFunction) { inputFunction();}
runThis(function() { console.log(“Hello world”) });
Output: Hello world
What is the “this” keyword in JavaScript?
This refers to the object itself. var student = { name: "Matt", getName: function(){ console.log(this.name); } }
student.getName();
Output: Matt
To make the getName() method work in the student object, the object has to access its own properties. This is possible via this keyword inside the object.
What does the .call() method do?
The call() method can be used to call a method of an object on another object. The call() can also accept arguments.
obj1.func.call(obj2)
var student = { name: "Matt", getName: function(){ console.log(this.name); } }
var anotherStudent = {
name: “Sophie”};
student.getName.call(anotherStudent);
Output: Sofie
What is the apply() method?
The apply() method does the same as the call() method. The difference is that apply() method accepts the arguments as an array.
const person = { name: ‘John’ }
function greet(greeting, message) {
return ${greeting} ${this.name}. ${message}
;}
let result = greet.apply(person, [‘Hello’, ‘How are you?’]);
console.log(result);
Output: Hello John. How are you?
In the line:
let result = greet.apply(person, [‘Hello’, ‘How are you?’]);
‘Hello’ is assigned to greeting and ‘How are you?’ is assigned to message in the greet() function.
What is the bind() method?
The bind() method returns a new function whose this has been set to another object.
Unlike apply() and call(), the bind() does not execute the function immediately. Instead, it returns a new version of the function whose this is set to another value.
What is currying?
Currying means transforming a function with n arguments, to n functions of one or fewer arguments.
For example, say you have a function add() that sums up two numbers:
function add(a, b) { return a + b;} You can call this function by: add(2,3) Let’s then curry the function: function add(a) { return function(b) { return a + b;}} Now you can call this curried function by: add(2)(3) Currying does not change the behavior of a function. It changes the way it’s invoked.
What is a promise in JavaScript?
A promise is an object that may produce value in the future. A promise is always in one of the possible states: fulfilled, rejected, or pending.
const promise = new Promise(function(resolve, reject) { // implement the promise here }) For example, let’s create a promise that’s resolved two seconds after being called.
const promise = new Promise(resolve => { setTimeout(() => { resolve("Hello, world!"); }, 2000); }, reject => {}); Now the key of promises is you can execute code right after the promise is resolved by using the .then() method:
promise.then(result => console.log(result));
Output: Hello, world!
Promises can be chained together such that a resolved promise returns a new promise.
Why use promises?
In JavaScript, promises are useful with async operations.
What is a callback function in JavaScript?
A callback function is a function that is passed as an argument to another function. This function is executed inside the function to which it’s passed as to “call back” when some action has been completed.
Why use callbacks in JavaScript?
The callbacks are useful because JavaScript is an event-driven language. In other words, instead of waiting for a response, it keeps executing while listening for other events.
function greetName(name) { console.log('Hello ' + name);}
function askName(callback) { let name = prompt('Enter your name.'); callback(name);}
askName(greetName);
What is a strict mode in JavaScript?
Strict mode allows your program to operate in a strict context, preventing certain actions from being taken. Also, more exceptions are thrown.
The expression “use strict”; tells the browser to enable the strict mode.
For example:
“use strict”;
number = 1000;
This causes an error because strict mode prevents you from assigning a value to an undeclared variable.
What is an Immediately Invoked Function?
An Immediately Invoked Function (IIFE) runs right after being defined. For example: (function(){ // action here })(); To understand how an IIFE works, look at the parenthesis around it: When JavaScript sees the keyword function, it assumes there’s a function declaration coming. But the declaration above is invalid because the function does not have a name. To fix this, the first set of parenthesis around the declaration is used. This tells the interpreter that it’s a function expression, not a declaration. (function (){ // action here; }) Then, to call the function, another set of parenthesis needs to be added at the end of the function declaration. This is similar to calling any other function: (function (){ // action here })();
What is a cookie?
A cookie is a small data packet stored on your computer. A website can place cookies on visitors’ browsers to remember login credentials.
Basically, cookies are text files with key-value pairs that you can create, read, or delete cookies, using the document.cookie property.
For example, let’s create a cookie that saves the username:
document.cookie = “username=foobar123”;
Why use strict mode in JavaScript?
Strict mode helps write “secure” JavaScript code. This means bad syntax practices are converted into real errors.
For example, strict mode prevents creating global variables.
To declare strict mode, add ‘use strict’; statement before the statements which you want to be under strict mode:
‘use strict’;
const sentence = “Hello, this is very strict”;
What does double exclamation do?
The double exclamation converts anything to boolean in JavaScript. !!true // true !!2 // true !![] // true !!"Test" // true !!false // false !!0 // false !!"" // false
How can you delete a property and its value from an object?
You can use the delete keyword to delete the property and its value from an object.
var student = {name: "John", age:20}; delete student.age; console.log(student); Output: {name: "John"}
How can you check the type of a variable in JavaScript?
Use the typeof operator.
typeof “John Abraham” // Returns “string”
typeof 100 // Returns “number”
What is null in JavaScript?
null represents the absence of value. It highlights that a variable points to no object.
The type of null is an object:
var name = null;
console. log(typeof(name))
returns: object
Null vs undefined?
Null
Represents the absence of a value of a variable.
Value that indicates the variable points to no object.
Is of type object.
Represents null, empty, or non-existent reference.
Converts to 0 with primitive operations.
Undefined
Represents the absence of the variable.
A variable that has been declared but doesn’t have a value
Is of type undefined.
Converts to NaN with primitive operations.
Can you access history in JavaScript?
You can access history via window.history that contains the browser’s history.
To retrieve the previous and next URLs, use these methods:
window. history.back();
window. history.forward();
What is a global variable?
A global variable is available everywhere in the code.
To create a global variable, omit the var keyword:
x = 100; // Creates a global variable.
Also, if you create a variable using var outside any functions, you create a global variable.
Does JavaScript relate to Java?
They are two different programming languages that have nothing to do with one another.
What are JavaScript events?
Events are what happens to HTML elements. When JavaScript is used in an HTML page, it can react to the events, such as a button click.