1. What is JavaScript, and what are its advantages?
JavaScript is a high-level, dynamic, and interpreted programming language. It’s commonly used for web development, and its main advantages include its ability to create responsive and interactive web pages, its support for object-oriented programming, and its versatility.
2. What is the difference between var, let, and const in JavaScript?
Var creates a function-scoped variable, while let and const create block-scoped variables. Additionally, var can be redeclared within the same scope, while let and const cannot be. For example:
var x = 5; var x = 10; // valid let y = 5; let y = 10; // invalid const z = 5; const z = 10; // invalid
3. What is closure in JavaScript?
A closure is a function that has access to variables in its outer (enclosing) function’s scope chain. The closure has access to variables in three scopes: its own scope, the outer function’s scope, and the global scope.
function outer() { const x = 10; function inner() { console.log(x); } return inner; } const innerFunc = outer(); innerFunc(); // output: 10
In the example above, inner is a closure that has access to the variable x in the scope of outer.
4. What is the use of the bind method in JavaScript?
The bind method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. For example:
const person = { name: 'John', greet() { console.log(`Hello, my name is ${this.name}.`); } }; const person2 = { name: 'Jane' }; const greet2 = person.greet.bind(person2); greet2(); // output: "Hello, my name is Jane."
In the example above, bind is used to create a new function greet2 with this set to person2.
5. What is event bubbling in JavaScript?
Event bubbling is a propagation model where the event first triggers on the innermost element and then propagates (bubbles up) to the outer elements until it reaches the document object. For example:
6. What are the new features in ES6?
ES6 or ECMAScript 2015 introduced several new features such as let and const for declaring variables, arrow functions, classes, template literals, destructuring, spread and rest operators, and more.
7. What is the difference between let and var?
var is function-scoped, while let is block-scoped. This means that variables declared with var are accessible within the function they are declared in, while variables declared with let are only accessible within the block they are declared in.
8. What is the difference between == and === in JavaScript?
== is the equality operator, which compares the values of two operands and returns true if they are equal, while === is the strict equality operator, which compares the values and types of two operands and returns true if they are equal.
console.log(1 == '1'); // Output: true console.log(1 === '1'); // Output: false
9. What is a callback function?
A callback function is a function that is passed as an argument to another function and is executed when the first function has finished executing. Callback functions are commonly used in JavaScript for asynchronous operations such as AJAX requests.
function fetchData(callback) { // Simulate a delay setTimeout(function() { var data = { name: 'John', age: 30 }; callback(data); }, 1000); } fetchData(function(data) { console.log(data); // Output: { name: 'John', age: 30 } });
10. What is the difference between null and undefined in JavaScript?
undefined is a variable that has been declared but has not been assigned a value, while null is a value that represents the intentional absence of any object value.
var x; console.log(x); // Output: undefined var y = null; console.log(y); // Output: null
11. What is the difference between synchronous and asynchronous programming?
Synchronous programming is where each statement in a program waits for the previous statement to complete before executing. Asynchronous programming is where statements are executed concurrently, and the program does not wait for each statement to complete before moving on to the next one.
Asynchronous programming is commonly used in JavaScript for operations that can take a long time to complete, such as AJAX requests or reading files from disk.
12. What are promises in JavaScript?
Promises are a way to handle asynchronous operations in JavaScript. A promise represents a value that may not be available yet, but will be at some point in the future. Promises have three states: pending, fulfilled, or rejected.
function fetchData() { return new Promise(function(resolve, reject) { // Simulate a delay setTimeout(function() { var data = { name: 'John', age: 30 }; resolve(data); }, 1000); }); } fetchData().then(function(data) { console.log(data); // Output: { name: 'John', age: 30 } });
13. What is a prototype in JavaScript?
Every JavaScript object has a prototype, which is a reference to another object that it “inherits” properties and methods from. The prototype is used to implement inheritance and is shared among all instances of a given object type.
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { console.log('Hello, my name is ' + this.name); } var john = new Person('John', 30); john.greet(); // Output: Hello, my name is John
14. What is the purpose of the “use strict” directive in JavaScript?
The “use strict” directive is used to enable strict mode in JavaScript. Strict mode enforces stricter rules for code behavior, such as disallowing undeclared variables and prohibiting the use of certain keywords. It helps to prevent common errors and makes the code easier to optimize.
15. What is hoisting in JavaScript?
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their respective scopes, regardless of where they are declared. This means that variables and functions can be used before they are declared, but their values may not be defined until later in the code.
16. What is the difference between a function declaration and a function expression?
A function declaration defines a function with a name that can be called anywhere in the code, while a function expression defines a function as a value of a variable and can only be called after it has been defined.
// Function declaration function greet(name) { console.log('Hello, ' + name); } greet('John'); // Output: Hello, John // Function expression var greet = function(name) { console.log('Hello, ' + name); }; greet('John'); // Output: Hello, John
17. What is the purpose of the “this” keyword in JavaScript?
The “this” keyword refers to the object that the function is a property of. The value of “this” depends on how the function is called and can change dynamically.
var person = { name: 'John', greet: function() { console.log('Hello, my name is ' + this.name); } }; person.greet(); // Output: Hello, my name is John
18. What is the difference between a for loop and a forEach loop in JavaScript?
A for loop is a traditional loop that is used to iterate over an array or object, while a forEach loop is a method that is called on an array and iterates over its elements.
var arr = [1, 2, 3]; // For loop for (var i = 0; i < arr.length; i++) { console.log(arr[i]); } // forEach loop arr.forEach(function(item) { console.log(item); });
19. What are the different types of errors in JavaScript?
There are three main types of errors in JavaScript:
Syntax errors: occur when the code violates the syntax rules of JavaScript.
Runtime errors: occur when the code throws an exception during execution, such as trying to call a method on an undefined variable.
Logical errors: occur when the code does not do what it is intended to do, but does not throw an exception.
// Syntax error console.log('Hello, world!); // Runtime error const obj = null; obj.foo(); // TypeError: Cannot read property 'foo' of null. // Logical error function sum(a, b)
20. What is the use of the Object.keys method in JavaScript?
The Object.keys method returns an array of a given object’s own enumerable property names. For example:
const obj = {a: 1, b: 2, c: 3}; console.log(Object.keys(obj)); // output: ["a", "b", "c"]
21. What is the difference between the spread operator and rest parameter in JavaScript?
The spread operator (…) is used to spread an array or object into individual elements, while the rest parameter (…) is used to collect individual elements into an array.
22. What is the difference between arrow functions and regular functions in JavaScript?
Arrow functions have a shorter syntax and do not create their own this context, while regular functions have a longer syntax and create their own this context.
23. What is the use of the setTimeOut method in JavaScript?
The setTimeOut method sets a timer that executes a function or a piece of code once the timer expires. For example:
setTimeout(() => { console.log('Hello, world!'); }, 1000); // executes after 1 second
24. What is the use of the setInterval method in JavaScript?
The setInterval method sets a timer that executes a function or a piece of code repeatedly at a specified interval. For example:
setInterval(() => { console.log('Hello, world!'); }, 1000); // executes every 1 second
25. What is the difference between `Object.freeze()` and `Object.seal()` in JavaScript?
`Object.freeze()` and `Object.seal()` are both methods that prevent changes to object properties, but `Object.freeze()` also prevents adding or removing properties from an object, while `Object.seal()` only prevents adding or removing properties.
Example:
const obj = { name: 'John', age: 30 }; Object.freeze(obj); obj.name = 'Jane'; // This will not change the value of obj.name. delete obj.age; // This will not delete the age property. obj.email = '[email protected]'; // This will not add a new email property. Object.seal(obj); obj.name = 'Jane'; // This will change the value of obj.name. delete obj.age; // This will not delete the age property. obj.email = '[email protected]'; // This will not add a new email property.