What is JavaScript?
- Answer: JavaScript is a high-level, interpreted programming language that is primarily used for building web applications. It runs in web browsers and allows you to add interactivity to your web pages.
What are the different data types in JavaScript?
- Answer: JavaScript has six primitive data types:
string
,number
,boolean
,null
,undefined
, andsymbol
. Additionally, there is an object data type.
- Answer: JavaScript has six primitive data types:
How do you check the type of a variable?
- Answer: You can use the
typeof
operator. - var variable = 42; console.log(typeof variable); // Outputs: "number"
- Answer: You can use the
What is the difference between
==
and===
in JavaScript?- Answer:
==
is a loose equality operator that performs type coercion, while===
is a strict equality operator that does not perform type coercion. - console.log(5 == "5"); // Outputs: true console.log(5 === "5"); // Outputs: false
- Answer:
Explain the concept of closures.
- Answer: A closure is the combination of a function and the lexical environment within which that function was declared. It allows a function to access variables from its outer (enclosing) scope even after the outer function has finished executing.
- function outer() { var outerVariable = 10; function inner() { console.log(outerVariable); } return inner; } var closureFunction = outer(); closureFunction(); // Outputs: 10
What is the difference between
let
,const
, andvar
?- Answer:
var
has function scope, whilelet
andconst
have block scope. Variables declared withvar
are hoisted to the top of their function or global context, whilelet
andconst
are not hoisted in the same way. - // Example using var function exampleVar() { if (true) { var localVar = "I am a var!"; console.log("Inside if block (var):", localVar); } console.log("Outside if block (var):", localVar); } exampleVar(); // Outputs: // Inside if block (var): I am a var! // Outside if block (var): I am a var! // Example using let function exampleLet() { if (true) { let localLet = "I am a let!"; console.log("Inside if block (let):", localLet); } // Uncommenting the line below would result in an error since 'localLet' is not defined here // console.log("Outside if block (let):", localLet); } exampleLet(); // Outputs: // Inside if block (let): I am a let! // Error: localLet is not defined
- Answer:
What is the event loop in JavaScript?
- Answer: The event loop is a core concept in JavaScript's concurrency model. It continuously checks the message queue for new events or tasks, executes them in the order they are received, and waits for new events.
What is a callback function? Provide an example of its usage.
- Answer: A callback function is a function passed as an argument to another function, which will be invoked at some point in the future. It's commonly used in asynchronous operations.
- function fetchData(callback) { setTimeout(function() { callback("Data fetched!"); }, 1000); } fetchData(function(result) { console.log(result); // Outputs: Data fetched! });
- Explain the event delegation pattern in JavaScript.
- Answer: Event delegation is a technique where a single event listener is attached to a common ancestor, instead of attaching multiple event listeners to individual elements. This is useful for efficiency and managing dynamic content.
- document.getElementById("parentElement").addEventListener("click", function(event) { if (event.target.tagName === "LI") { console.log("Item clicked: ", event.target.textContent); } });
What is the purpose of the
bind
method in JavaScript?- Answer: The
bind
method is used to create a new function with a specifiedthis
value and initial arguments. It's often used to set the context of a function explicitly. - var obj = { value: 42 }; function getValue() { console.log(this.value); } var boundFunction = getValue.bind(obj); boundFunction(); // Outputs: 42
- Answer: The
What is the difference between
null
andundefined
?- Answer:
null
is an assigned value that represents the absence of any object value, whileundefined
is a variable that has been declared but has not been assigned a value. - var a; console.log(a); // Outputs: undefined var b = null; console.log(b); // Outputs: null
- Answer:
Explain asynchronous JavaScript and how it is handled.
- Answer: Asynchronous JavaScript allows tasks to run independently of the main program flow. Commonly used mechanisms for handling asynchronous code include callbacks, promises, and async/await.
- // Using a callback function fetchData(callback) { setTimeout(function() { callback("Data fetched!"); }, 1000); } fetchData(function(result) { console.log(result); // Outputs: Data fetched! });
What is the purpose of the
async
andawait
keywords in JavaScript?- Answer: The
async
keyword is used to define asynchronous functions, and theawait
keyword is used withinasync
functions to wait for the resolution of aPromise
. This helps in writing asynchronous code in a more synchronous-like fashion.
- async function fetchData() { let result = await fetch('https://example.com/data'); let data = await result.json(); console.log(data); } fetchData();
- Explain the concept of promises in JavaScript.
- Answer: Promises are objects representing the eventual completion or failure of an asynchronous operation. They have states (pending, fulfilled, or rejected) and are commonly used for handling asynchronous code in a more readable and manageable way.
- const fetchData = new Promise((resolve, reject) => { setTimeout(() => { resolve("Data fetched!"); // or reject("Error occurred!"); }, 1000); }); fetchData.then(result => console.log(result)) .catch(error => console.error(error));
- Explain the difference between
map
andforEach
array methods. - Answer: Both
map
andforEach
are array iteration methods.map
creates a new array by applying a function to each element of the original array, whileforEach
simply iterates over the array and performs an action without creating a new array. - const numbers = [1, 2, 3]; const squared = numbers.map(x => x * x); // [1, 4, 9] numbers.forEach(x => console.log(x)); // Outputs: 1, 2, 3
- How does hoisting work in JavaScript?
- Answer: Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. However, only the declarations are hoisted, not the initializations.
- // Assignment before declaration age = 25; // Declaration using var var age; console.log(age); // Outputs: 25 console.log(x); // Outputs: undefined var x = 5; // Function declaration hoisting sayHello(); // Outputs: Hello function sayHello() { console.log('Hello'); } // console.log(y); // ReferenceError: Cannot access 'y' before initialisation let y = 10;
- Explain the concept of prototypal inheritance in JavaScript.
- Answer: JavaScript uses prototypal inheritance, where objects can inherit properties and methods from other objects through their prototype chain. Each object has a prototype object, and properties/methods are inherited from the prototype to the object.
Primitive Data Types:
1. Number:
let num = 42;
let floatNum = 3.14;
2. String:
let greeting = "Hello, World!";
let name = 'John';
3. Boolean:
let isTrue = true;
let isFalse = false;
4. Undefined:
let undefinedVar;
5. Null:
let nullVar = null;
6. Symbol:
let sym = Symbol('uniqueSymbol');
Reference Data Types:
7. Object:
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
8. Array:
let numbers = [1, 2, 3, 4, 5];
let fruits = ['apple', 'banana', 'orange'];
9. Function:
function add(a, b) {
return a + b;
}
Special Data Types:
10. BigInt:
let bigInteger = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1);
Checking Data Types:
Using typeof
Operator:
console.log(typeof num); // Outputs: "number"
console.log(typeof greeting); // Outputs: "string"
console.log(typeof isTrue); // Outputs: "boolean"
console.log(typeof undefinedVar); // Outputs: "undefined"
console.log(typeof nullVar); // Outputs: "object"
console.log(typeof sym); // Outputs: "symbol"
console.log(typeof person); // Outputs: "object"
console.log(typeof numbers); // Outputs: "object"
console.log(typeof add); // Outputs: "function"
console.log(typeof bigInteger); // Outputs: "bigint"
Understanding and working with these data types is fundamental for effective JavaScript programming