JavaScript - Basic Flashcards
What are the key features of JavaScript?
- Dynamic and weak typing
- Prototype-based object-oriented programming
- Closures
- First-class functions
- Event-driven programming
- Asynchronous programming
Dynamic and weak typing
- Variables can hold values of any data type,
- and their types can be changed during runtime.
Closures
allow inner functions to access variables from their outer function scopes.
First-class functions
Functions can be:
- assigned to variables,
- passed as arguments,
- and returned as values.
How do you include JavaScript code in an HTML file?
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.
What are the primitive data types in JavaScript?
- Number
- String
- Boolean
- Undefined
- Null
- Symbol
Explain the concept of hoisting in JavaScript.
- 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
What are the different ways to define variables in JavaScript?
- var
- let
- const
How do you check the data type of a variable in JavaScript
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"
undefined
- It indicates that a variable has been declared but has not been assigned a value.
null
- 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.
What are the arithmetic operators in JavaScript?
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Modulus (remainder): %
- Exponentiation: **
- Increment: ++
- Decrement: –
What is the purpose of the “this” keyword in JavaScript?
- 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.
Explain the concept of closures in JavaScript.
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.
What is event delegation in JavaScript?
- 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 does prototypal inheritance work in JavaScript?
- 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()
What is the purpose of the “use strict” directive in JavaScript?
- 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 do you create an object in JavaScript?
- Object literals- just write the object out
- Constructor function - create a function and then use new to create the object
- Object.create()
What are the different ways to loop through an array in JavaScript?
- for loop
- forEach()
- for … of loop
- map()
- while loop
”==”
It attempts to convert the operands to a common type before making the comparison.
”===”
It returns true only if the values are equal and the types match.
NOTE: It does not perform type coercion.
What is the purpose of the “setTimeout” function in JavaScript?
- 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
How do you handle errors in JavaScript?
- 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); }
Explain the concept of asynchronous programming in JavaScript.
- allows code to execute independently and not block the execution of the entire program.
What are callback functions in JavaScript?
- 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.
Explain the concept of promises in JavaScript.
An object that represent the eventual completion (or failure) of an asynchronous operation
What are the three states of a promise?
- Pending
- Fulfilled
- Rejected
Promise Pending state
The initial state, neither fulfilled nor rejected.
Promise Fulfilled state
The operation completed successfully, and a result value is available.
Promise Rejected state
The operation failed, and an error reason is available.
What are the 2 main methods of a promise
then()
catch()
then()
Registers callbacks for handling the fulfilled state of a promise and the value it resolves to.
catch()
Registers a callback for handling the rejected state of a promise and the reason for rejection.
How do you clone an object in JavaScript?
- Object.assign()
- spread syntax
- JSON.parse() & JSON.stringify()
Object.assign()
- 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);
Spread syntax (operator):
- 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 };
JSON.parse() and JSON.stringify()
- You can use JSON.stringify() to
- convert the original object to a JSON string
- 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
- not supporting functions
- or undefined properties.
For example:
const originalObject = { name: "John", age: 25 }; const clonedObject = JSON.parse(JSON.stringify(originalObject));
Event bubbling
- when an event is triggered on an element,
- it first executes the event handlers attached to the innermost element
- 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.
Event capturing
- 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.
What are the different types of pop-up boxes available in JavaScript?
- alert()
- confirm()
- prompt()
alert()
- 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!');
confirm()
- 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 }
prompt()
- displays a prompt box that allows the user to input text.
- It accepts two parameters:
- the message to display
- 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.'); }
How do you detect the user’s browser in JavaScript?
- 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.'); }
Describe the difference in hoisting between var, let and const
- var is hoisted and initialized with the value of undefined
- let & const are hoisted but not initialized and cannot be accessed before their declairation.
What is the difference between undefined and null
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.