JavaScript - Basic Flashcards

1
Q

What are the key features of JavaScript?

A
  1. Dynamic and weak typing
  2. Prototype-based object-oriented programming
  3. Closures
  4. First-class functions
  5. Event-driven programming
  6. Asynchronous programming
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Dynamic and weak typing

A
  • Variables can hold values of any data type,
  • and their types can be changed during runtime.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Closures

A

allow inner functions to access variables from their outer function scopes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

First-class functions

A

Functions can be:

  1. assigned to variables,
  2. passed as arguments,
  3. and returned as values.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you include JavaScript code in an HTML file?

A

inline: You can write JavaScript directly within the HTML file using the script tag and placing the code between the opening and closing tags.

External file: You can also link an external JavaScript file using the src attribute of the script tag.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the primitive data types in JavaScript?

A
  1. Number
  2. String
  3. Boolean
  4. Undefined
  5. Null
  6. Symbol
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain the concept of hoisting in JavaScript.

A
  • variable and function declarations are moved to the top of their containing scope during the compilation phase.
  • This means that you can call functions before they are declared in their scope.
  • For let/const, only the declarations are hoisted, not the initializations or assignments.
  • For var, it is initialized with the value of undefined until it is declared
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the different ways to define variables in JavaScript?

A
  1. var
  2. let
  3. const
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you check the data type of a variable in JavaScript

A

typeof

For example:

let num = 10;
console.log(typeof num); // Outputs: "number"

.

message = "Hello";
console.log(typeof message); // Outputs: "string"

.

let isValid = true;
console.log(typeof isValid); // Outputs: "boolean"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

undefined

A
  • It indicates that a variable has been declared but has not been assigned a value.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

null

A
  • It represents the intentional absence of any object value.
  • It is typically assigned by developers to indicate that a variable or object property should have no value.
  • Unlike undefined, null is an explicitly assigned value.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the arithmetic operators in JavaScript?

A
  1. Addition: +
  2. Subtraction: -
  3. Multiplication: *
  4. Division: /
  5. Modulus (remainder): %
  6. Exponentiation: **
  7. Increment: ++
  8. Decrement: –
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of the “this” keyword in JavaScript?

A
  • The this keyword in JavaScript refers to the object on which a method is being invoked.

For example:

const person = {
  name: "John",
  sayHello: function() {
    console.log("Hello, " + this.name);
  }
};

person.sayHello(); // Outputs: "Hello, John"

In the above code, this.name accesses the name property of the person object using the this keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain the concept of closures in JavaScript.

A

An inner function always has access to the variables defined in the outer functions even if the outer function has finished executing.

For Example:

function outer() {
  let outerVariable = "I'm from the outer function";

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

  return inner;
}

const closureFunction = outer();
closureFunction(); // Outputs: "I'm from the outer function"

In the above code, the inner function forms a closure with the outer function’s scope. Even after the outer function has returned, the closureFunction still has access to the outerVariable variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is event delegation in JavaScript?

A
  • attach a single event listener to a parent element and use event bubbling to handle events instead of attaching multiple event listeners to it’s descendant elements.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How does prototypal inheritance work in JavaScript?

A
  • In JavaScript, prototypal inheritance is a way of creating objects based on other objects.
  • Each object in JavaScript has an internal property called [[Prototype]] that points to its prototype object.
  • When you access a property or method on an object, JavaScript first looks for it on the object itself. If it doesn’t find it, it continues to search for the property or method on the object’s prototype, and so on, forming a chain.

For example:

// Prototype object
const animal = {
  sound: "Sound not defined",
  makeSound: function() {
    console.log(this.sound);
  }
};

// Object inheriting from the prototype
const dog = Object.create(animal);
dog.sound = "Woof";
dog.makeSound(); // Outputs: "Woof"

// Object inheriting from the same prototype
const cat = Object.create(animal);
cat.sound = "Meow";
cat.makeSound(); // Outputs: "Meow"

In the above code, both the dog and cat objects inherit the sound property and makeSound method from the animal prototype object using Object.create()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the purpose of the “use strict” directive in JavaScript?

A
  • When strict mode is enabled, JavaScript enforces stricter rules and generates more errors in certain situations.
  • i.e. this in functions aren’t bound to the global variable (i.e. the window object if in a browser).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you create an object in JavaScript?

A
  • Object literals- just write the object out
  • Constructor function - create a function and then use new to create the object
  • Object.create()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the different ways to loop through an array in JavaScript?

A
  1. for loop
  2. forEach()
  3. for … of loop
  4. map()
  5. while loop
20
Q

”==”

A

It attempts to convert the operands to a common type before making the comparison.

21
Q

”===”

A

It returns true only if the values are equal and the types match.

NOTE: It does not perform type coercion.

22
Q

What is the purpose of the “setTimeout” function in JavaScript?

A
  • The setTimeout function is used to delay the execution of a function or the evaluation of an expression after a specified time interval.
  • It allows you to schedule a callback function to be executed asynchronously once the specified time has passed.
  • The time interval is specified in milliseconds.

for example:

function sayHello() {
  console.log("Hello!");
}

setTimeout(sayHello, 2000); // Executes sayHello after a 2-second delay
23
Q

How do you handle errors in JavaScript?

A
  • you can handle errors using try-catch blocks.

For example:

try {
  // Code that may throw an error
  const result = 10 / 0;
  console.log(result);
} catch (error) {
  // Code to handle the error
  console.log("An error occurred: " + error.message);
}
24
Q

Explain the concept of asynchronous programming in JavaScript.

A
  • allows code to execute independently and not block the execution of the entire program.
25
Q

What are callback functions in JavaScript?

A
  • Callback functions are functions that are passed as arguments to other functions and are invoked or called at a later point in time.
  • They allow you to define behavior that will be executed after a specific task or event has occurred.
  • Callback functions are commonly used in asynchronous programming, event handling, and in higher-order functions.

For example:

function fetchData(callback) {
  // Simulating an asynchronous operation
  setTimeout(function() {
    const data = "Data received";
    callback(data);
  }, 2000);
}

function processData(data) {
  console.log("Processing data: " + data);
}

fetchData(processData);

NOTE: In the above code, the fetchData function simulates an asynchronous operation by using setTimeout. It takes a callback function as an argument. Once the asynchronous operation is complete, the callback function (processData) is invoked with the received data.

26
Q

Explain the concept of promises in JavaScript.

A

An object that represent the eventual completion (or failure) of an asynchronous operation

27
Q

What are the three states of a promise?

A
  1. Pending
  2. Fulfilled
  3. Rejected
28
Q

Promise Pending state

A

The initial state, neither fulfilled nor rejected.

29
Q

Promise Fulfilled state

A

The operation completed successfully, and a result value is available.

30
Q

Promise Rejected state

A

The operation failed, and an error reason is available.

31
Q

What are the 2 main methods of a promise

A

then()

catch()

32
Q

then()

A

Registers callbacks for handling the fulfilled state of a promise and the value it resolves to.

33
Q

catch()

A

Registers a callback for handling the rejected state of a promise and the reason for rejection.

34
Q

How do you clone an object in JavaScript?

A
  1. Object.assign()
  2. spread syntax
  3. JSON.parse() & JSON.stringify()
35
Q

Object.assign()

A
  • The Object.assign() method is used to copy the values of all enumerable properties from one or more source objects to a target object.
  • It can be used to shallow clone an object.

For example:

const originalObject = { name: "John", age: 25 };
const clonedObject = Object.assign({}, originalObject);
36
Q

Spread syntax (operator):

A
  • The spread syntax (…) can be used to create a shallow clone of an object by expanding the properties of the original object into a new object.

For example:

const originalObject = { name: "John", age: 25 };
const clonedObject = { ...originalObject };
37
Q

JSON.parse() and JSON.stringify()

A
  • You can use JSON.stringify() to
    1. convert the original object to a JSON string
    2. and then use JSON.parse() to parse the JSON string into a new object.
  • This method provides a deep clone of the object,
  • but it has limitations, such as
    1. not supporting functions
    2. or undefined properties.

For example:

const originalObject = { name: "John", age: 25 };
const clonedObject = JSON.parse(JSON.stringify(originalObject));
38
Q

Event bubbling

A
  • when an event is triggered on an element,
    1. it first executes the event handlers attached to the innermost element
    2. and then bubbles up to the outermost element, triggering their event handlers as well.
  • the event starts from the target element and propagates upwards through its ancestors.
39
Q

Event capturing

A
  • The event starts from the outermost element and propagates downwards through its descendants, triggering their event handlers along the way.
  • This can be achieved by setting the useCapture parameter to true when adding an event listener.
  • In event capturing, the event is handled in the reverse order compared to event bubbling.
40
Q

What are the different types of pop-up boxes available in JavaScript?

A
  1. alert()
  2. confirm()
  3. prompt()
41
Q

alert()

A
  • The alert() function is used to display an alert box with a message to the user.
  • It typically contains a brief message or notification and an OK button to close the alert.

For example:

alert('This is an alert box!');
42
Q

confirm()

A
  • The confirm() function displays a confirmation box with a message and two buttons: OK and Cancel.
  • It is commonly used to prompt the user for a yes/no or OK/cancel response.

For example:

const result = confirm('Are you sure you want to delete this item?');
if (result) {
  // Delete the item
} else {
  // Cancel the operation
}
43
Q

prompt()

A
  • displays a prompt box that allows the user to input text.
  • It accepts two parameters:
    1. the message to display
    2. an optional default value for the input field.
  • The prompt box includes an input field, OK, and Cancel buttons.

For example:

const name = prompt('Please enter your name:', 'John Doe');
if (name) {
  console.log('Hello, ' + name + '!');
} else {
  console.log('You did not enter a name.');
}
44
Q

How do you detect the user’s browser in JavaScript?

A
  • by accessing the navigator object, which provides information about the user’s browser and operating system.

For example:

const userAgent = navigator.userAgent;

if (userAgent.includes('Chrome')) {
  console.log('User is using Chrome browser.');
} else if (userAgent.includes('Firefox')) {
  console.log('User is using Firefox browser.');
} else if (userAgent.includes('Safari')) {
  console.log('User is using Safari browser.');
} else {
  console.log('User is using a different browser.');
}
45
Q

Describe the difference in hoisting between var, let and const

A
  • var is hoisted and initialized with the value of undefined
  • let & const are hoisted but not initialized and cannot be accessed before their declairation.
46
Q

What is the difference between undefined and null

A

Undefined is assigned by JavaScript to indicate the absence of a value.

Null is assigned intentionally by the programmer to indicate the absence of a value.