[Go to site: main page, start]

0% found this document useful (0 votes)
41 views12 pages

JavaScript Exercises with Solutions

The JavaScript Practice Workbook covers key concepts in JavaScript including variables, control structures, functions, arrays, strings, DOM manipulation, events, ES6+ features, asynchronous programming, and error handling. Each section includes practice exercises and mini challenges to reinforce learning. Solutions to the exercises are also provided for reference.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views12 pages

JavaScript Exercises with Solutions

The JavaScript Practice Workbook covers key concepts in JavaScript including variables, control structures, functions, arrays, strings, DOM manipulation, events, ES6+ features, asynchronous programming, and error handling. Each section includes practice exercises and mini challenges to reinforce learning. Solutions to the exercises are also provided for reference.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Practice Workbook

1. Variables and Data Types

Concept Recap:

Variables can be declared using let, const, or var. Data types include string, number, boolean, null,

undefined, object, and symbol.

Practice Exercises:

1. Declare a variable for your name and age.

2. Create a constant for your birth year.

3. Change the value of a let variable and print it.

Mini Challenge:

Write a program to swap two variables.


JavaScript Practice Workbook

2. Control Structures

Concept Recap:

Use if, else, and switch statements for conditional logic. Loops like for, while, and do...while repeat actions.

Practice Exercises:

1. Write a program to check if a number is even or odd.

2. Create a grading system using if-else.

3. Print numbers from 1 to 10 using a loop.

Mini Challenge:

FizzBuzz program: print numbers from 1 to 50. For multiples of 3 print 'Fizz', for 5 print 'Buzz', for both print

'FizzBuzz'.
JavaScript Practice Workbook

3. Functions

Concept Recap:

Functions help organize reusable logic. Use function declarations, expressions, and arrow functions.

Practice Exercises:

1. Write a function to add two numbers.

2. Convert Celsius to Fahrenheit.

3. Return the factorial of a number.

Mini Challenge:

Write a function to check if a string is a palindrome.


JavaScript Practice Workbook

4. Arrays & Objects

Concept Recap:

Arrays store ordered collections, objects store key-value pairs.

Practice Exercises:

1. Create an array of 5 fruits and print each using a loop.

2. Create an object with name, age, and city keys.

3. Use map() to double each number in an array.

Mini Challenge:

Write a function that takes an array of user objects and returns names of users aged 18+.
JavaScript Practice Workbook

5. Strings & Methods

Concept Recap:

Common methods: length, slice, split, replace, includes, toUpperCase, toLowerCase.

Practice Exercises:

1. Count characters in a string.

2. Convert a sentence to title case.

3. Replace bad words in a sentence with stars.

Mini Challenge:

Write a function to reverse a string.


JavaScript Practice Workbook

6. DOM Manipulation

Concept Recap:

Use getElementById, querySelector, and addEventListener to interact with the HTML DOM.

Practice Exercises:

1. Change the text of a button when clicked.

2. Display user input below a form.

3. Change background color of a div on mouseover.

Mini Challenge:

Create a live character counter for a textarea.


JavaScript Practice Workbook

7. Events & Forms

Concept Recap:

JavaScript can respond to user interactions using events like click, submit, keydown, etc.

Practice Exercises:

1. Alert user on button click.

2. Validate email in a form before submit.

3. Show a message while typing in input.

Mini Challenge:

Make a form that only submits if all fields are filled.


JavaScript Practice Workbook

8. ES6+ Features

Concept Recap:

Use let/const, template literals, destructuring, spread/rest, arrow functions.

Practice Exercises:

1. Use template literals to print user details.

2. Destructure an object and log the values.

3. Merge two arrays using spread operator.

Mini Challenge:

Use rest parameters to sum any number of arguments.


JavaScript Practice Workbook

9. Asynchronous JS

Concept Recap:

Use callbacks, promises, and async/await to handle asynchronous operations.

Practice Exercises:

1. Simulate a delay using setTimeout.

2. Fetch mock data using Promise.

3. Use async/await to wait for 2 seconds and return a value.

Mini Challenge:

Chain two promises that resolve sequentially.


JavaScript Practice Workbook

10. Error Handling

Concept Recap:

Use try...catch to handle errors in code. Create custom error messages when needed.

Practice Exercises:

1. Try parsing invalid JSON.

2. Write a function that throws an error if input is not a number.

3. Catch and log any runtime error.

Mini Challenge:

Wrap a calculator function in try-catch and show alerts if inputs are invalid.
JavaScript Practice Workbook

Solutions to Practice Exercises

Solutions to Practice Exercises:

1. Variables and Data Types:

let name = "John"; let age = 25;

const birthYear = 2000;

let city = "Delhi"; city = "Mumbai"; [Link](city);

Swapping: let a=5,b=10,temp=a;a=b;b=temp;

2. Control Structures:

Even/Odd: if(num % 2 == 0) { ... }

Grading: if(score >= 90) return 'A'; ...

FizzBuzz: use modulo and conditions.

3. Functions:

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

function toF(c){return (c*9/5)+32;}

function fact(n){...}

Palindrome: reverse the string and compare.

4. Arrays & Objects:

Loop: for(let fruit of fruits) [Link](fruit);

map: [Link](n => n*2);

Filter adults: [Link](u => [Link] >= 18).map(u => [Link]);

5. Strings:

Title case: split, map with word[0].toUpperCase()...

Reverse: [Link]("").reverse().join("");

6. DOM:
JavaScript Practice Workbook

[Link] = "Clicked!";

addEventListener("mouseover", ...);

7. Events:

[Link]("submit", e => { ... });

[Link]("input", ...);

8. ES6+:

Template: `Hi ${name}`;

Destructuring: const {name, age} = obj;

9. Async JS:

setTimeout(() => ..., 2000);

new Promise((res) => setTimeout(() => res("Done"), 1000));

async function demo() { await ...; }

10. Errors:

try { [Link]("invalid"); } catch(e) { [Link](e); }

if(typeof input !== "number") throw Error("Not a number");

Common questions

Powered by AI

Arrays are ordered collections of elements that are particularly suited for operations that involve sequentially iterating or managing a list of items, due to their indexed nature. They support numerous built-in methods such as map, filter, and reduce for efficient handling of sequences. Objects, on the other hand, are unordered collections of key-value pairs that are excellent for representing complex entities with properties. They facilitate operations based on keys, making them ideal for data models that map well to associative arrays or dictionaries in other languages .

The use of try...catch constructs in JavaScript allows developers to gracefully handle errors by catching exceptions and providing meaningful responses or corrective actions without crashing the entire application. This enhances robustness by isolating errors and maintaining application flow. Custom error messages can help debug, while using finally ensures critical code runs regardless of whether an error occurred. Proper error handling prevents unhandled exceptions, leading to better user experiences and decreased downtime .

'addEventListener' provides a more flexible approach to managing events by allowing multiple events to be handled for the same element without overwriting existing handlers, as opposed to using 'onclick' or similar event properties, which replace previous handlers. It also offers the ability to specify the event phase (capturing or bubbling) during which the listener should be triggered. This improves event-driven programming by enabling decoupling of event handling logic from HTML structure and allowing dynamic addition and removal of event handlers .

Promises provide a clear and manageable way to handle asynchronous operations through their syntax, allowing chaining of operations with 'then' and error handling with 'catch'. This reduces callback hell, which is common with traditional callback functions. However, promises can become unwieldy when chaining multiple asynchronous tasks. Async/await improves readability and introduces synchronous-like code for asynchronous operations by using 'await' keyword, making chaining straightforward. The main limitation is that 'await' can only be used inside functions declared with the 'async' keyword, and it still relies on the promise architecture under the hood .

Effective techniques for DOM manipulation include using 'getElementById', 'querySelector', and 'querySelectorAll' to access and modify elements based on id, class, or tag selectors. Manipulating element properties, such as 'innerHTML' for text or 'style' for CSS, allows for dynamic content updates. For instance, changing a button's text on click using an event listener with 'innerText', or displaying user input live with 'value' property modification. More complex interactions can involve creating new elements with 'createElement' and appending them using 'appendChild' .

Functions in JavaScript promote code reusability and efficiency by encapsulating blocks of logic that can be executed multiple times with different inputs without redundant code. Functions allow for the separation of concerns, making code easier to manage, test, and understand. Named functions provide self-documenting code, while anonymous functions and arrow functions introduced in ES6 add flexibility in functional programming paradigms .

To ensure a form is only submitted when all fields are filled, JavaScript validation techniques include using 'addEventListener' for the 'submit' event to prevent submission if any fields are empty. This can be achieved by checking the 'value' property of each required field before allowing submission. Enhancing user experience, provide real-time validation with 'input' events, displaying immediate feedback like highlighting empty fields or showing error messages, thus helping users correct errors before submission .

ES6+ features enhance JavaScript code efficiency and readability significantly. Destructuring allows for more concise assignments by unpacking properties directly from objects or array elements, which simplifies variable declarations. Spread and rest operators provide a flexible way to expand or condense arrays and objects, enabling efficient handling of dynamic arguments or cloning objects. Arrow functions offer a more readable syntax for writing functions, particularly for inline anonymous functions, and they handle 'this' context more intuitively by binding it lexically .

Control structures like 'if-else' allow for fine-grained, complex decision-making because they enable multiple conditions to be evaluated in sequence, which is perfect for tasks where various branches of code might run based on different conditions. 'Switch' statements improve readability and efficiency when dealing with numerous discrete values for a single variable, such as replacing long 'if-else' chains. They also make code execution faster and cleaner by jumping directly to the code associated with the matching 'case' .

'let' and 'const' are block-scoped, meaning they are only accessible within the block they are defined, while 'var' is function-scoped or globally scoped if declared outside a function. 'const' variables cannot be reassigned after their initial assignment, unlike 'let' and 'var', which can be updated. However, 'const' does not make the value immutable when it comes to objects and arrays, though the reference itself must remain constant .

You might also like