20 JavaScript practice questions that cover a range of basic programming concepts:

Created with Sketch.

Certainly! Here are 20 JavaScript practice questions that cover a range of basic programming concepts:

1. **Hello World:**
Write a program that prints “Hello, World!” to the console.

 

console.log('Hello, World!');

2. **Variables and Data Types:**

Create variables for a person’s name, age, and whether they have a driver’s license. Print these variables to the console.

// Variable declarations
let personName = 'John';
let personAge = 25;
let hasDriverLicense = true;

// Print variables to the console
console.log('Name:', personName);
console.log('Age:', personAge);
console.log('Has Driver\'s License:', hasDriverLicense);

3. **Arrays:**
Create an array of your favorite colors and print each color to the console.

// Array of favorite colors
let favoriteColors = ['blue', 'green', 'red', 'purple', 'orange'];

// Print each color to the console
console.log('My favorite colors:');
favoriteColors.forEach(color => {
    console.log(color);
});

4. **Objects:**
Create an object representing a car with properties like make, model, and year. Print these properties to the console.

// Car object
let car = {
    make: 'Toyota',
    model: 'Camry',
    year: 2022
};

// Print car properties to the console
console.log('Car details:');
console.log('Make:', car.make);
console.log('Model:', car.model);
console.log('Year:', car.year);

5. **Functions:**
Write a function that takes two parameters and returns their sum.

// Function to add two numbers
function addNumbers(a, b) {
    return a + b;
}

// Example usage
let result = addNumbers(3, 5);
console.log('Sum:', result);

In this example, the addNumbers function takes two parameters (a and b) and returns their sum using the + operator. The function is then called with arguments 3 and 5, and the result is printed to the console. You can use this function with different values for a and b as needed.

6. **Conditionals:**
Write a program that checks if a number is even or odd. Print the result to the console.

// Function to check if a number is even or odd
function checkEvenOrOdd(number) {
    if (number % 2 === 0) {
        return 'Even';
    } else {
        return 'Odd';
    }
}

// Example usage
let num1 = 10;
let num2 = 7;

console.log(num1 + ' is ' + checkEvenOrOdd(num1));
console.log(num2 + ' is ' + checkEvenOrOdd(num2));

In this example, the checkEvenOrOdd function takes a number as a parameter and uses the modulo operator (%) to check if the number is divisible by 2. If the remainder is 0, the number is even; otherwise, it’s odd. The results are then printed to the console for two example numbers (num1 and num2).

7. **Loops:**
Use a loop to print the numbers from 1 to 5 to the console.

// Loop to print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
    console.log(i);
}

In this example, a for loop is used to iterate from 1 to 5 (inclusive). The loop variable i is incremented in each iteration, and the current value of i is printed to the console. The loop will run five times, printing the numbers 1 through 5.

8. **Functions and Loops:**
Write a function that takes a number as a parameter and prints the multiplication table for that number up to 10.

// Function to print multiplication table
function printMultiplicationTable(number) {
    console.log('Multiplication table for ' + number + ':');
    for (let i = 1; i <= 10; i++) {
        console.log(number + ' * ' + i + ' = ' + (number * i));
    }
}

// Example usage
let multiplier = 5;
printMultiplicationTable(multiplier);

In this example, the printMultiplicationTable function takes a number as a parameter and uses a for loop to iterate from 1 to 10, printing each multiplication operation along with its result. The function is then called with an example number (multiplier set to 5), and the multiplication table for 5 is printed to the console.

9. **String Methods:**
Create a string and use a string method to convert it to uppercase.

// Original string
let originalString = 'hello, world!';

// Convert the string to uppercase
let uppercaseString = originalString.toUpperCase();

// Print the results to the console
console.log('Original string:', originalString);
console.log('Uppercase string:', uppercaseString);

In this example, the toUpperCase method is used on the originalString to convert it to uppercase. The original and uppercase strings are then printed to the console.

10. **Array Methods:**
Create an array of numbers and use an array method to find the sum of all the numbers.

// Array of numbers
let numbers = [1, 2, 3, 4, 5];

// Use the reduce method to find the sum
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

// Print the sum to the console
console.log('Sum of numbers:', sum);

In this example, the reduce method is applied to the numbers array. The callback function passed to reduce takes two parameters (accumulator and currentValue) and adds them together. The initial value of the accumulator is set to 0. The result, which is the sum of all the numbers, is then printed to the console.

11. **Objects and Methods:**
Create an object representing a person with properties like name, age, and a method that prints a greeting using the person’s name.

// Person object
let person = {
    name: 'Alice',
    age: 30,
    greet: function() {
        console.log('Hello, my name is ' + this.name + '!');
    }
};

// Call the greet method
person.greet();

In this example, the person object has properties name and age, and a method called greet. The greet method uses console.log to print a greeting that includes the person’s name. The method is then called using person.greet(). You can customize the properties and add more methods as needed.

12. **Event Handling:**
Create an HTML button and use JavaScript to display an alert when the button is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Handling Example</title>
</head>
<body>

<!-- Button with onclick attribute -->
<button onclick="showAlert()">Click me</button>

<script>
    // JavaScript function to display an alert
    function showAlert() {
        alert('Button clicked!');
    }
</script>

</body>
</html>

In this example, the HTML document contains a button with an onclick attribute that specifies the JavaScript function showAlert() to be called when the button is clicked. The showAlert function is defined in the <script> section and uses the alert function to display a simple alert message.

13. **Asynchronous Programming (Callbacks):**
Write a function that simulates fetching data asynchronously and takes a callback function to handle the data.

// Function to simulate fetching data asynchronously
function fetchDataAsync(callback) {
    setTimeout(function () {
        // Simulated data
        let data = {
            message: 'Data successfully fetched!',
            timestamp: new Date()
        };

        // Invoke the callback function with the data
        callback(data);
    }, 2000); // Simulating a delay of 2 seconds
}

// Example usage
fetchDataAsync(function (result) {
    console.log(result.message);
    console.log('Timestamp:', result.timestamp);
});

In this example, the fetchDataAsync function simulates an asynchronous operation using setTimeout. After a delay of 2 seconds, it invokes the provided callback function with simulated data. The callback function is defined in the fetchDataAsync function and is called with the simulated data when the asynchronous operation is complete.

14. **Promises:**
Modify the previous function to use a Promise instead of a callback.

// Function to simulate fetching data asynchronously with a Promise
function fetchDataAsyncWithPromise() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            // Simulated data
            let data = {
                message: 'Data successfully fetched!',
                timestamp: new Date()
            };

            // Resolve the Promise with the data
            resolve(data);
        }, 2000); // Simulating a delay of 2 seconds
    });
}

// Example usage
fetchDataAsyncWithPromise()
    .then(function (result) {
        console.log(result.message);
        console.log('Timestamp:', result.timestamp);
    })
    .catch(function (error) {
        console.error('Error:', error);
    });

In this modified example, the fetchDataAsyncWithPromise function returns a Promise. The asynchronous operation is wrapped in the Promise, and the resolve function is used to fulfill the Promise with the simulated data. The example usage demonstrates how to handle the Promise using then for success and catch for error handling.

15. **ES6 Arrow Functions:**
Rewrite one of your previous functions using an arrow function.

// Function to simulate fetching data asynchronously with a Promise (using arrow function)
const fetchDataAsyncWithPromiseArrow = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // Simulated data
            let data = {
                message: 'Data successfully fetched!',
                timestamp: new Date()
            };

            // Resolve the Promise with the data
            resolve(data);
        }, 2000); // Simulating a delay of 2 seconds
    });
};

// Example usage
fetchDataAsyncWithPromiseArrow()
    .then(result => {
        console.log(result.message);
        console.log('Timestamp:', result.timestamp);
    })
    .catch(error => {
        console.error('Error:', error);
    });

In this example, I’ve used arrow function syntax to define both the fetchDataAsyncWithPromiseArrow function and the callback functions within the then and catch methods. Arrow functions are a concise way to write functions, especially when they have a simple and short body.

16. **Destructuring:**
Use destructuring to extract values from an object and print them to the console

// Person object
let person = {
    name: 'Bob',
    age: 35,
    country: 'USA'
};

// Destructuring to extract values
let { name, age, country } = person;

// Print the values to the console
console.log('Name:', name);
console.log('Age:', age);
console.log('Country:', country);

In this example, the destructuring assignment syntax { name, age, country } = person is used to extract values from the person object and assign them to variables with the same names. The values are then printed to the console using console.log.

17. **Classes:**
Create a class representing a book with properties like title and author. Instantiate an object and print its properties.

// Book class
class Book {
    constructor(title, author) {
        this.title = title;
        this.author = author;
    }
}

// Instantiate an object of the Book class
let myBook = new Book('The Great Gatsby', 'F. Scott Fitzgerald');

// Print the properties of the book to the console
console.log('Book Title:', myBook.title);
console.log('Author:', myBook.author);

In this example, the Book class has a constructor that takes title and author parameters to initialize the properties of the book. An object myBook is then instantiated from this class, and its properties are printed to the console.

18. **Default Parameters:**
Write a function that takes two parameters, with a default value for one of them.

// Function with default parameter
function greetPerson(name, greeting = 'Hello') {
    console.log(greeting + ', ' + name + '!');
}

// Example usage
greetPerson('Alice');  // Uses the default greeting ('Hello')
greetPerson('Bob', 'Good morning');  // Uses the provided greeting ('Good morning')

In this example, the greetPerson function takes two parameters, name and greeting. The default value for greeting is set to 'Hello'. If the greeting parameter is not provided when the function is called, it will default to 'Hello'.

19. **Map and Filter:**
Create an array of numbers, use `map` to double each number, and then use `filter` to only keep the even numbers.

// Array of numbers
let numbers = [1, 2, 3, 4, 5];

// Use map to double each number
let doubledNumbers = numbers.map(number => number * 2);

// Use filter to keep only the even numbers
let evenNumbers = doubledNumbers.filter(number => number % 2 === 0);

// Print the results to the console
console.log('Original numbers:', numbers);
console.log('Doubled numbers:', doubledNumbers);
console.log('Even numbers:', evenNumbers);

In this example, the map method is used to create a new array (doubledNumbers) where each element is the result of doubling the corresponding element in the original numbers array. Then, the filter method is used to create a new array (evenNumbers) containing only the even numbers from the doubledNumbers array. The results are printed to the console.

20. **Modules (ES6):**
Create two JavaScript files – one with a function and another that imports and calls that function.

// math.js - contains a simple function
export const add = (a, b) => a + b;
// main.js - imports and calls the function from math.js
import { add } from './math.js';

// Use the imported function
let result = add(3, 4);

// Print the result to the console
console.log('Result:', result);

In this example:

  • math.js exports a function named add that takes two parameters and returns their sum.
  • main.js imports the add function from math.js using the import statement.
  • The imported function is then used to add two numbers (3 and 4 in this case), and the result is printed to the console.

Note: To run this example, you would typically need an environment that supports ES6 module syntax, such as a web browser environment or a Node.js environment with support for ES6 modules. If you are running this in a browser, make sure to use the type="module" attribute in your HTML file script tag when including the main.js file.

Leave a Reply

Your email address will not be published. Required fields are marked *