Basics of JavaScript

Learn the basics of JavaScript including variables, data types, arrays, conditionals, and functions.

Basics of JavaScript Interview with follow-up questions

Interview Question Index

Question 1: What are the different data types available in JavaScript?

Answer:

JavaScript has several built-in data types, including:

  • Primitive data types: such as number, string, boolean, null, undefined, and symbol (added in ES6).
  • Object data type: such as object and array.

These data types can be used to store and manipulate different kinds of values in JavaScript.

Back to Top ↑

Follow up 1: Can you explain the difference between null and undefined?

Answer:

In JavaScript, null and undefined are both special values that represent the absence of a value.

  • null is a value that represents the intentional absence of any object value. It is a primitive value that is assigned to a variable to indicate that it has no value or that it is empty.
  • undefined is a value that represents an uninitialized, missing, or non-existent value. It is a primitive value that is automatically assigned to a variable that has been declared but has not been assigned a value.

In summary, null is an assignment value that indicates no value or empty value, while undefined is a default value that indicates a variable has not been assigned a value.

Back to Top ↑

Follow up 2: What is the typeof operator used for?

Answer:

The typeof operator in JavaScript is used to determine the data type of a value or variable.

For example:

typeof 42; // returns 'number'
typeof 'Hello'; // returns 'string'
typeof true; // returns 'boolean'
typeof undefined; // returns 'undefined'
typeof null; // returns 'object' (this is a known bug in JavaScript)
typeof [1, 2, 3]; // returns 'object'
typeof {name: 'John', age: 30}; // returns 'object'
Back to Top ↑

Follow up 3: How does JavaScript handle type conversions?

Answer:

JavaScript has two types of type conversions:

  • Implicit type conversion: JavaScript automatically converts values from one data type to another when needed. For example, when performing operations between different data types, JavaScript will convert one or both values to a common data type.

  • Explicit type conversion: JavaScript provides several built-in functions and operators to explicitly convert values from one data type to another. For example, the Number(), String(), and Boolean() functions can be used to convert values to the corresponding data types.

Here are some examples of type conversions:

var num = 42;
var str = String(num); // explicit conversion to string
console.log(str); // '42'

var bool = Boolean(''); // explicit conversion to boolean
console.log(bool); // false

var sum = '10' + 5; // implicit conversion to string
console.log(sum); // '105'

var difference = '10' - 5; // implicit conversion to number
console.log(difference); // 5
Back to Top ↑

Follow up 4: What is the difference between double equals (==) and triple equals (===) in JavaScript?

Answer:

In JavaScript, the double equals (==) and triple equals (===) are comparison operators used to compare values.

  • Double equals (==): It compares the values on both sides of the operator after performing type coercion if necessary. It allows for loose equality comparison, meaning that it can convert values of different types to a common type before comparing them.

  • Triple equals (===): It compares the values on both sides of the operator without performing any type coercion. It checks for strict equality, meaning that it does not convert values of different types.

Here are some examples:

console.log(42 == '42'); // true (loose equality, converts string to number)
console.log(42 === '42'); // false (strict equality, different types)
console.log(0 == false); // true (loose equality, converts boolean to number)
console.log(0 === false); // false (strict equality, different types)
Back to Top ↑

Question 2: What are variables in JavaScript and how are they declared?

Answer:

In JavaScript, variables are used to store data values. They are declared using the var, let, or const keywords. The var keyword is used to declare a variable with function scope, meaning it is accessible within the function it is declared in. The let keyword is used to declare a variable with block scope, meaning it is accessible within the block it is declared in (e.g., within a loop or conditional statement). The const keyword is used to declare a constant variable, which cannot be reassigned once it is declared.

Back to Top ↑

Follow up 1: What is the difference between var, let and const?

Answer:

The main difference between var, let, and const is the scope and reassignment behavior. var has function scope and can be reassigned and redeclared within its scope. let has block scope and can be reassigned but not redeclared within its scope. const also has block scope but cannot be reassigned or redeclared once it is declared. Here's an example:

var x = 1;
let y = 2;
const z = 3;

if (true) {
  var x = 4; // This reassigns the value of x
  let y = 5; // This creates a new block-scoped variable y
  const z = 6; // This creates a new block-scoped constant z
}

console.log(x); // Output: 4
console.log(y); // Output: 2
console.log(z); // Output: 3

In the example above, the var variable x is reassigned within the if statement, while the let variable y creates a new block-scoped variable with a different value. The const variable z also creates a new block-scoped constant with a different value.

Back to Top ↑

Follow up 2: What is hoisting in JavaScript?

Answer:

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions before they are declared in your code. However, only the declarations are hoisted, not the initializations. Here's an example:

console.log(x); // Output: undefined
var x = 10;

console.log(y); // Output: ReferenceError: y is not defined
let y = 20;

In the example above, the var variable x is hoisted to the top of its scope, so it is accessible but has an initial value of undefined. The let variable y is not hoisted, so trying to access it before its declaration results in a ReferenceError.

Back to Top ↑

Follow up 3: Can you explain the concept of scope in JavaScript?

Answer:

Scope in JavaScript refers to the visibility and accessibility of variables, functions, and objects in some particular part of your code during runtime. JavaScript has function scope and block scope. Function scope means that variables declared within a function are only accessible within that function or any nested functions. Block scope means that variables declared within a block (e.g., within a loop or conditional statement) are only accessible within that block. Here's an example:

function example() {
  var x = 1; // Function-scoped variable

  if (true) {
    let y = 2; // Block-scoped variable
    console.log(x); // Output: 1
    console.log(y); // Output: 2
  }

  console.log(x); // Output: 1
  console.log(y); // Output: ReferenceError: y is not defined
}

example();

In the example above, the variable x is function-scoped and accessible within the example function and any nested functions. The variable y is block-scoped and only accessible within the if statement block.

Back to Top ↑

Follow up 4: What happens if you try to use a variable that has not been declared?

Answer:

If you try to use a variable that has not been declared, JavaScript will throw a ReferenceError and your code will stop executing. This is because JavaScript requires variables to be declared before they can be used. Here's an example:

console.log(x); // Output: ReferenceError: x is not defined
Back to Top ↑

Question 3: What are arrays in JavaScript and how can you manipulate them?

Answer:

Arrays in JavaScript are a type of object that can store multiple values in a single variable. They are used to store and manipulate collections of data. Arrays in JavaScript are zero-indexed, which means the first element is at index 0, the second element is at index 1, and so on. You can manipulate arrays in JavaScript using various methods and operations.

Back to Top ↑

Follow up 1: What are some methods you can use to manipulate arrays in JavaScript?

Answer:

There are several methods you can use to manipulate arrays in JavaScript:

  • push(): Adds one or more elements to the end of an array.

  • pop(): Removes the last element from an array and returns that element.

  • shift(): Removes the first element from an array and returns that element.

  • unshift(): Adds one or more elements to the beginning of an array.

  • splice(): Adds or removes elements from an array at a specified index.

  • slice(): Returns a shallow copy of a portion of an array into a new array.

  • concat(): Joins two or more arrays and returns a new array.

  • sort(): Sorts the elements of an array in place.

  • reverse(): Reverses the order of the elements in an array.

  • forEach(): Executes a provided function once for each array element.

  • map(): Creates a new array with the results of calling a provided function on every element in the array.

Back to Top ↑

Follow up 2: How do you add and remove elements from an array?

Answer:

To add elements to an array, you can use the push() method to add elements to the end of the array, or the unshift() method to add elements to the beginning of the array.

To remove elements from an array, you can use the pop() method to remove the last element from the array, or the shift() method to remove the first element from the array. You can also use the splice() method to remove elements from a specific index in the array.

Back to Top ↑

Follow up 3: What is the difference between an array and an object in JavaScript?

Answer:

In JavaScript, arrays and objects are both types of objects, but they have some key differences:

  • Arrays are ordered collections of data, while objects are unordered collections of key-value pairs.

  • Arrays use numeric indices to access and manipulate elements, while objects use string keys.

  • Arrays have a length property that represents the number of elements in the array, while objects do not.

  • Arrays have built-in methods for manipulating and iterating over elements, while objects do not.

  • Arrays are best suited for storing and manipulating ordered collections of data, while objects are best suited for storing and accessing data using descriptive keys.

Back to Top ↑

Follow up 4: How can you iterate over an array in JavaScript?

Answer:

There are several ways to iterate over an array in JavaScript:

  • for loop: You can use a traditional for loop to iterate over an array by using the array's length property and accessing each element using its index.
var array = [1, 2, 3, 4, 5];

for (var i = 0; i < array.length; i++) {
    console.log(array[i]);
}
  • forEach() method: You can use the forEach() method to execute a provided function once for each element in the array.
var array = [1, 2, 3, 4, 5];

array.forEach(function(element) {
    console.log(element);
});
  • for...of loop: You can use a for...of loop to iterate over the values of an array.
var array = [1, 2, 3, 4, 5];

for (var element of array) {
    console.log(element);
}
  • map() method: You can use the map() method to create a new array with the results of calling a provided function on every element in the array.
var array = [1, 2, 3, 4, 5];

var newArray = array.map(function(element) {
    return element * 2;
});

console.log(newArray);
Back to Top ↑

Question 4: What are conditionals in JavaScript and how are they used?

Answer:

Conditionals in JavaScript are used to make decisions and execute different blocks of code based on certain conditions. They allow the program to perform different actions based on different inputs or situations. The most common types of conditionals in JavaScript are if-else statements, the ternary operator, and the switch statement.

Back to Top ↑

Follow up 1: What is the syntax for an if-else statement in JavaScript?

Answer:

The syntax for an if-else statement in JavaScript is as follows:

if (condition) {
    // code to be executed if the condition is true
} else {
    // code to be executed if the condition is false
}
Back to Top ↑

Follow up 2: What is the ternary operator and how is it used?

Answer:

The ternary operator is a shorthand way of writing an if-else statement in JavaScript. It allows you to write a single line of code to perform a conditional operation. The syntax for the ternary operator is as follows:

condition ? expression1 : expression2

If the condition is true, expression1 is evaluated and returned. If the condition is false, expression2 is evaluated and returned.

Back to Top ↑

Follow up 3: What is the switch statement and how is it used?

Answer:

The switch statement is used to perform different actions based on different conditions. It evaluates an expression and executes the code block associated with the matching case. If no matching case is found, the code block associated with the default case is executed. The syntax for the switch statement is as follows:

switch (expression) {
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    default:
        // code to be executed if expression does not match any case
}
Back to Top ↑

Follow up 4: Can you explain the concept of truthy and falsy values in JavaScript?

Answer:

In JavaScript, truthy and falsy values are values that are considered true or false when evaluated in a boolean context. The following values are considered falsy:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are considered truthy. When using conditionals, these truthy and falsy values can be used to determine the flow of the program. For example, if a variable is assigned a falsy value, the corresponding code block in an if-else statement will not be executed.

Back to Top ↑

Question 5: What are functions in JavaScript and how are they declared?

Answer:

Functions in JavaScript are reusable blocks of code that perform a specific task. They are declared using the function keyword followed by the function name, a list of parameters (optional), and the function body enclosed in curly braces. Here's an example:

function greet(name) {
  console.log('Hello, ' + name + '!');
}
Back to Top ↑

Follow up 1: What is the difference between a function declaration and a function expression?

Answer:

In JavaScript, a function declaration is a statement that defines a named function and hoists it to the top of the current scope. It can be called before it is defined. On the other hand, a function expression is an assignment of a function to a variable or a constant. It is not hoisted and can only be called after it is defined. Here's an example:

// Function declaration
function greet(name) {
  console.log('Hello, ' + name + '!');
}

// Function expression
const greet = function(name) {
  console.log('Hello, ' + name + '!');
};
Back to Top ↑

Follow up 2: What is a callback function?

Answer:

A callback function is a function that is passed as an argument to another function and is invoked inside that function. It allows for asynchronous and event-driven programming in JavaScript. Callback functions are commonly used in scenarios like handling AJAX requests, event handling, and timeouts. Here's an example:

function fetchData(callback) {
  // Simulating an asynchronous operation
  setTimeout(function() {
    const data = 'Some data';
    callback(data);
  }, 1000);
}

function processData(data) {
  console.log('Processed data:', data);
}

fetchData(processData);
Back to Top ↑

Follow up 3: What are arrow functions and how do they differ from regular functions?

Answer:

Arrow functions are a concise syntax for writing functions in JavaScript. They were introduced in ES6. Unlike regular functions, arrow functions do not have their own this value, arguments object, or super keyword. They also cannot be used as constructors with the new keyword. Arrow functions are often used in scenarios where a short, anonymous function is needed. Here's an example:

// Regular function
function multiply(a, b) {
  return a * b;
}

// Arrow function
const multiply = (a, b) => a * b;
Back to Top ↑

Follow up 4: Can you explain the concept of closures in JavaScript?

Answer:

In JavaScript, a closure is a function that has access to its own scope, the scope in which it is defined, and the scope of its outer function. It allows a function to access and manipulate variables from its outer function even after the outer function has finished executing. Closures are often used to create private variables and encapsulate functionality. Here's an example:

function outer() {
  const message = 'Hello';

  function inner() {
    console.log(message);
  }

  return inner;
}

const closure = outer();
closure(); // Output: Hello
Back to Top ↑