Skip to main content

Modern Markup - JavaScript Interview Questions

JavaScript Fundamentals: Modern Markup




Can you explain the script type attribute used in Modern JavaScript development?​

View Answer:
Interview Response:The type attribute in modern JavaScript development is used to specify the scripting language or module format for an <script> element. For instance, setting type="module" allows you to use JavaScript modules with import/export syntax.

Code Example: JavaScript type attribute

<script type="module">
import { myFunction } from './myModule.js';
myFunction();
</script>
Here, the type="module" specifies that this script should be treated as a JavaScript module, enabling the use of import and export statements for modular code organization.

What was the script language attribute used for in early web development?​

View Answer:
Interview Response: This property displays the language of the script. According to the MDN, we no longer utilize it since it is deprecated.

Technical Response: In early web development, the type attribute in the <script> tag was used to specify the scripting language used in the code block within the script element. This was important at the time, different scripting languages were used for client-side scripts, such as JavaScript, VBScript, and others.

Code Example: JavaScript language attribute

<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:
Interview Response: Traditional JavaScript focuses on basic scripting, lacks advanced features, and has limited browser support. Modern JavaScript incorporates ECMAScript updates, provides advanced features, supports modern web development, and offers better browser compatibility.

Take a quick look at this code snippet - Traditional JavaScript:

function add(a, b) {
return a + b;
}

var result = add(5, 3);
console.log("Result: " + result);
This example uses a traditional function declaration and var for variable declaration. It defines a simple add function and logs the result to the console.

Modern JavaScript:

const add = (a, b) => a + b;

const result = add(5, 3);
console.log(`Result: ${result}`);
The modern example uses arrow functions (=>) for a more concise syntax and const for variable declaration, providing better scoping and immutability. Template literals are used for cleaner string interpolation.


What are the benefits of using ES6 syntax in JavaScript?​

View Answer:
Interview Response: ES6 provides enhanced readability, conciseness, and maintainability. It introduces arrow functions, template literals, destructuring, modules, and classes for improved programming experience and productivity.

Code Example: ES6 syntax

// 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.
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 let and const variables?​

View Answer:
Interview Response: let is used to declare block-scoped, mutable variables, while const declares block-scoped, immutable variables that cannot be reassigned.

Code Example:

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:
Interview Response: A callback function in JavaScript is a function passed as an argument to another function, executed after the completion of an asynchronous operation.

Code Example: Callback Function

function fetchData(callback) {
setTimeout(() => {
const data = 'Hello, world!';
callback(data);
}, 1000);
}

fetchData((response) => {
console.log(response); // Output: Hello, world!
});
In this example, fetchData simulates an asynchronous operation using setTimeout. The callback function is passed as an argument, which logs the response once the operation is complete.


What is a promise in JavaScript?​

View Answer:
Interview Response: A Promise in JavaScript represents the eventual completion or failure of an asynchronous operation, providing a more structured way to handle async code.

Code Example: Promise

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:
Interview Response: Async/await in JavaScript simplifies asynchronous code, making it more readable by using async functions and await expressions to handle Promises.

Code Example: Async/Await

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:
Interview Response: The spread operator in JavaScript (...) is used to expand elements of iterable objects, such as arrays or objects, making it easier to merge, copy, or insert elements.

Code Example: Spread Operator

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:
Interview Response: JSX (JavaScript XML) is a React-specific syntax extension for JavaScript, allowing you to write HTML-like code within JavaScript, making it easier to create and manage UI components.

Code Example:

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:
Interview Response: ES6, or ECMAScript 2015, is a major update to JavaScript introducing new features and syntax, enhancing readability, modularity, and maintainability, and promoting better programming practices.

In JavaScript, What features were introduced in ES6?​

View Answer:
Interview Response: ES6 introduced features such as arrow functions, classes, template literals, destructuring, Promises, modules (import/export), let and const, default parameters, rest and spread operators, and more.

In JavaScript, What is the difference between let and var in ES6?​

View Answer:
Interview Response: The difference between let and var is their scoping: let has block scope, while var has function scope. Additionally, β€˜let’ prevents hoisting-related issues.

Code Example:

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:
Interview Response: Arrow functions in ES6 are a shorter syntax for writing function expressions, providing implicit return for single expressions, lexical binding of this, and making code more readable and maintainable.

Code Example: Arrow Functions

// 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:
Interview Response: Template literals in ES6 are a new way to create strings, using backticks (``) instead of quotes, allowing embedded expressions, multiline strings, and improved readability.

Code Example: Template Literals

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:
Interview Response: Classes in ES6 are syntactic sugar for prototype-based inheritance, providing a more intuitive and familiar syntax for defining constructors, methods, and inheritance in object-oriented programming.

Code Example: Classes

// 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:
Interview Response: Destructuring in ES6 is a convenient syntax for extracting values from arrays or properties from objects into distinct variables, making code more concise and readable.

Code Example: Destructuring Assignment

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:
Interview Response: Default parameters in JavaScript allow function parameters to have default values, simplifying function calls and handling cases where arguments are missing or undefined.

Code Example: Destructuring Assignment

// 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.



What are JavaScript modules, and what benefits do they provide?​

View Answer:
Interview Response: JavaScript modules are separate files containing reusable code, promoting modularity, maintainability, and organization by enabling import/export of functions, classes, or variables across projects.