Modern Markup - JavaScript Interview Questions
JavaScript Fundamentals: Modern Markup
Can you explain the script type attribute used in Modern JavaScript development?β
View Answer:
<script type="module">
import { myFunction } from './myModule.js';
myFunction();
</script>
What was the script language attribute used for in early web development?β
View Answer:
<html>
<body>
<script language="javascript">
// <-- this is the script language attribute
<!--
document.write('Hello JavaScript!');
//-->
</script>
</body>
</html>
In this example, we use an arrow function and template literals for cleaner code, default parameters for flexibility, destructuring for easier assignment, ES6 module exports, and class syntax for object-oriented programming.
What is the difference between traditional and modern JavaScript?β
View Answer:
function add(a, b) {
return a + b;
}
var result = add(5, 3);
console.log("Result: " + result);
const add = (a, b) => a + b;
const result = add(5, 3);
console.log(`Result: ${result}`);
What are the benefits of using ES6 syntax in JavaScript?β
View Answer:
// Arrow function and template literals
const greet = (name) => `Hello, ${name}!`;
// Default parameter
const multiply = (a, b = 2) => a * b;
// Destructuring assignment
const person = { name: 'Alice', age: 28 };
const { name, age } = person;
// ES6 module (export)
export const add = (a, b) => a + b;
// ES6 class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal('Buddy');
dog.speak(); // Output: Buddy makes a noise.
What is the difference between let and const variables?β
View Answer:
Here's an example:
let variableLet = "Hello";
variableLet = "Goodbye"; // This is allowed
console.log(variableLet); // Outputs: Goodbye
////////////////////////////////////
const variableConst = "Hello";
variableConst = "Goodbye"; // This will cause an error
console.log(variableConst); // Uncaught TypeError: Assignment to constant variable.
In the example above, variableLet
is a let
variable and it is allowed to be re-assigned. However, when we try to re-assign variableConst
, which is a const
variable, JavaScript throws a TypeError
.
What is a callback function in JavaScript?β
View Answer:
function fetchData(callback) {
setTimeout(() => {
const data = 'Hello, world!';
callback(data);
}, 1000);
}
fetchData((response) => {
console.log(response); // Output: Hello, world!
});
What is a promise in JavaScript?β
View Answer:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = 'Hello, world!';
resolve(data);
}, 1000);
});
}
fetchData()
.then((response) => {
console.log(response); // Output: Hello, world!
})
.catch((error) => {
console.error(error);
});
In this example, fetchData returns a Promise that simulates an asynchronous operation using setTimeout. The resolve function is called with the resulting data once the operation is complete. The then method handles the fulfilled Promise, logging the response, while the catch method handles errors.
What is async/await in JavaScript?β
View Answer:
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
const data = 'Hello, world!';
resolve(data);
}, 1000);
});
}
async function main() {
try {
const response = await fetchData();
console.log(response); // Output: Hello, world!
} catch (error) {
console.error(error);
}
}
main();
In this example, fetchData returns a Promise simulating an asynchronous operation. The main function is declared as async, allowing the use of await to pause execution until the Promise resolves. This results in more readable and synchronous-like code while handling asynchronous operations.
What is the purpose of the spread operator, in JavaScript?β
View Answer:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Merge arrays
const merged = [...arr1, ...arr2];
console.log(merged); // Output: [1, 2, 3, 4, 5, 6]
// Copy array
const copy = [...arr1];
console.log(copy); // Output: [1, 2, 3]
// Insert elements
const arrayWithZero = [0, ...arr1];
console.log(arrayWithZero); // Output: [0, 1, 2, 3]
In this example, the spread operator is used to merge arrays, create a copy of an array, and insert elements into a new array. It simplifies array manipulation and improves code readability.
What is JSX in React?β
View Answer:
import React from 'react';
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>; // JSX
}
export default Welcome;
In this example, the Welcome component is defined using JSX. The <h1> element is written with HTML-like syntax directly in the JavaScript code. {props.name} is a JavaScript expression within the JSX, displaying the value of the name prop when the component is rendered. The component can be imported and used in other parts of a React application, making it easier to manage UI components.
What is ES6 in relation to JavaScript?β
View Answer:
In JavaScript, What features were introduced in ES6?β
View Answer:
In JavaScript, What is the difference between let and var in ES6?β
View Answer:
function example() {
if (true) {
var varVariable = 'var';
let letVariable = 'let';
}
console.log(varVariable); // 'var'
console.log(letVariable); // ReferenceError: letVariable is not defined
}
example();
In this example, varVariable has function scope, so it's accessible throughout the example function, including outside the if block. In contrast, letVariable has block scope and is only accessible within the if block. Attempting to access letVariable outside the block results in a ReferenceError. Using let provides better control over variable scope and reduces the risk of unintentional access or modification.
What are arrow functions in ES6?β
View Answer:
// Traditional function expression
const squareTraditional = function (x) {
return x * x;
};
// Arrow function
const squareArrow = (x) => x * x;
console.log(squareTraditional(4)); // 16
console.log(squareArrow(4)); // 16
In this example, squareTraditional is a traditional function expression, while squareArrow is an arrow function. The arrow function has a more concise syntax, with an implicit return for single expressions. Both functions calculate the square of a number and produce the same result, but the arrow function makes the code shorter and more readable.
What are template literals in ES6?β
View Answer:
const name = 'John';
const age = 30;
// Traditional string concatenation
const greetingTraditional = 'Hello, ' + name + '. You are ' + age + ' years old.';
// Template literal
const greetingLiteral = `Hello, ${name}. You are ${age} years old.`;
console.log(greetingTraditional); // Hello, John. You are 30 years old.
console.log(greetingLiteral); // Hello, John. You are 30 years old.
In this example, greetingTraditional uses traditional string concatenation with single quotes and + operators. greetingLiteral uses a template literal, enclosed in backticks, with embedded expressions inside ${}. Both strings produce the same result, but the template literal is more readable and easier to work with, especially for complex strings.
What are classes in ES6?β
View Answer:
// ES6 Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // Rex barks.
In this example, we define an Animal class using the class keyword. The constructor function initializes the object with a name property. The speak method is added to the class prototype.
The Dog class extends the Animal class, inheriting its properties and methods. We override the speak method to provide a custom implementation for dogs.
Finally, we create a Dog instance and call its speak method. The ES6 class syntax provides a more intuitive way to define and work with objects and inheritance in JavaScript.
What is destructuring in ES6?β
View Answer:
const person = {
name: 'John',
age: 30,
city: 'New York',
};
// Destructuring assignment
const { name, age, city } = person;
console.log(name); // 'John'
console.log(age); // 30
console.log(city); // 'New York'
In this example, we have a person object with three properties: name, age, and city. We use destructuring assignment to extract the properties into individual variables.
The line const { name, age, city } = person; creates three new variables with the same names as the properties and assigns the corresponding property values. This concise syntax improves readability, especially when working with complex data structures.
What are default parameters in JavaScript?β
View Answer:
// Function with default parameters
function greet(name, greeting = 'Hello') {
console.log(`${greeting}, ${name}!`);
}
greet('John'); // 'Hello, John!'
greet('John', 'Hi'); // 'Hi, John!'
In this example, we define a greet function with two parameters: name and greeting. The greeting parameter has a default value of 'Hello'.
When we call greet('John'), the greeting parameter isn't provided, so the default value 'Hello' is used. When we call greet('John', 'Hi'), the greeting parameter is provided, so the default value is overridden. Default parameters simplify function calls and help handle cases where some arguments may not be provided.