第二十一章·实战练习
In this chapter we will be performing exercises to test our knowledge in JavaScript. The exercises that we will be performing are listed below:
- Concatenation
- Conditional Statements
- Constants
- Console
- FizzBuzz Problem
- Functions
- Get the Titles!
- Multiplication
- Objects
- User Input Variables
Concatenation
In any programming language, string concatenation simply means appending one or more strings to another string. For example, when strings "World" and "Good Afternoon" are concatenated with string "Hello", they form the string "Hello World, Good Afternoon". We can concatenate a string in several ways in JavaScript.
Example:
const icon = "👋";
// using template Strings
`hi ${icon}`;
// using join() Method
["hi", icon].join(" ");
// using concat() Method
"".concat("hi ", icon);
// using + operator
"hi " + icon;
// RESULT
// hi 👋
📝 Task:
[ ] Write a program to set the values for
str1andstr2so the code prints 'Hello World' to the console.[ ] Write a program that prompt user to enter their first name(
first_name) and last name(last_name). Then, use string concatenation to create and display their full name(full_name).[ ] Write a program that prompt user to enter their name. Then, use string concatenation to create a greeting message that include their name. For examples:
Good morning, Aman.
💡 Hints:
- Visit the concatenation chapter of strings for more info about string concatenation. Console output: website
Try it!
Output:
Conditional Statements
Conditional logic is vital in programming as it makes sure that the program works regardless of what data you throw in and also allows branching. This exercise is about the implementation of various conditional logic in real-life problems.
📝 Task:
- [ ] Write a program to create a prompt "How many km is left to go?" and based on the user and the following conditions, print the results in the
console.- If there are more than 100 km left to go, print:
"You still have a bit of driving left to go". - If there are more than 50 km, but less or equal to 100 km, print:
"I'll be there in 5 minutes". - If there are less than or equal to 50 km, print:
"I'm parking. I'll see you right now".
- If there are more than 100 km left to go, print:
[ ] Write a program that checks whether a person is eligible to vote or not based on their age.
- If the age of user is 18 or older then print
You are eligible to vote If the age of user is less than 18 then print
You aren't eligible to vote.Note:
agecan be between1to100.
- If the age of user is 18 or older then print
💡 Hints:
- Visit the conditional logic chapter to understand how to use conditional logic and conditional statements.
Try it!
Output:
Constants
Constants were introduced in ES6(2015), and use a const keyword. Variables that are declared with const cannot be reassigned or redeclared.
Example:
const VERSION = "1.2";
📝 Task:
[ ] Run the program mentioned below and fix the error that you see in the console. Make sure that the code result is
0.9when it is fixed in the console.const VERSION = "0.7"; VERSION = "0.9"; console.log(VERSION);[ ] Write a program that prompts user to enter a temperature in degrees Celsius, then use constant
CONVERSION_FACTORwhich equals to9/5to convert to degrees Fahrenheit.const CONVERSION_FACTOR = 9 / 5; /* Start your code from here*/
💡 Hints:
- Visit the Variables chapter for more info about const and also look for "TypeError assignment to constant variable" in search engines to learn a fix.
Try it!
Output:
Console
In JavaScript, we use console.log() to write a message (the content of a variable, a given string, etc.) in console. It is mainly used for debugging purposes, ideally to leave a trace of the content of variables during the execution of a program.
Example:
console.log("Welcome to Learn JavaScript Beginners Edition");
let age = 30;
console.log(age);
Math with console
You can also write math equation in console in order to know the answer to an expression.
Example:
console.log("What's the age a decade later?");
let age = 30;
console.log(age + 10);
//returns 40 in the console
Booleans in console
Another useful way developers use console is to check wether something is true or false. For instance in the example below you can check wether the age of a person being equal to 45 is true or false.
Example:
console.log("Are they 50 years old?");
let age = 30;
console.log(age === 50);
//result: false
📝 Tasks:
- Write a program to print
Hello Worldon the console. Feel free to try other things as well! - Write a program to print variables to the
console.- Declare a variable
animaland assign the dragon value to it. - Print the
animalvariable to theconsole.
- Declare a variable
Write a program to print the number
45with a math expression of your choice. (Bonus if one of the numbers is a variable!)Write a program in the console that checks if the amounts of eggs is more than
12.- Declare a variable
eggsand assign a number of your choice to it - Call the
eggsvariable in theconsoleand use the correct operator to see if the number assigned toeggsis greater that 12- If the number of eggs is greater, it should print
true, if not then it should printfalse
- If the number of eggs is greater, it should print
- Declare a variable
💡 Hints:
- Visit the variable chapter to understand more about variables.
- Visit the operators page to know the possible operators you can use.
Try it!
Output:
FizzBuzz Problem
The FizzBuzz problem is one of the commonly asked questions, here one has to print Fizz and Buzz upon some conditions.
📝 Tasks:
[ ] Write a program to print all the numbers between 1 to 100 in such a way that the following conditions are met.
- For multiples of 3, instead of the number, print
Fizz. - For multiples of 5, print
Buzz. For numbers that are multiples of both 3 and 5, print
FizzBuzz./ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 .... .... 98 Fizz Buzz /
- For multiples of 3, instead of the number, print
💡 Hints:
- Visit the loops chapter to understand how the loop works.
Try it!
Output:
Functions
A function is a block of code designed to perform a specific task and executed when "something" invokes it. More info about functions can be found in the functions chapter.
📝 Task:
[ ] Write a program to create a function named
isOddthat passes a number45345as an argument and determines whether the number is odd or not.[ ] Call this function to get the result. The result should be in a boolean format and should return
trueinconsole.[ ] Write a program to create a function named
calculateRectangleAreathat takes two parameterswidthandheightof the rectange and should returnareaof the rectangle.
💡 Hints:
- Visit the functions chapter to understand functions and how to create them.
Try it!
Output:
Get the Titles!
The Get the Titles! problem is an interesting problem where we have to get the title from a list of books. This is a good exercise for the implementation of arrays and objects.
📝 Tasks:
Given an array of objects that represent books with an author.
const books = [
{
title: "Eloquent JavaScript, Third Edition",
author: "Marijn Haverbeke"
},
{
title: "Practical Modern JavaScript",
author: "Nicolás Bevacqua"
}
]
- [ ] Write a program to create a function
getTheTitlesthat takes the array and returns the array of title and print its value in theconsole.
💡 Hints:
Try it!
Output:
Multiplication
In JavaScript, we can perform the multiplication of two numbers by using the asterisk (*) arithmetic operators.
Example:
let resultingValue = 3 * 2;
Here, we stored the product of 3 * 2 into a resultingValue variable.
📝 Tasks:
[ ] Write a program to store the product of
23times41and print its value.[ ] Write a program that generates a multiplication table for a specific number. The program should take a number as input and then display the multiplication table for that number, from 1 to 10.
💡 Hints:
- Visit the Basic Operators chapter to understand the mathematical operations.
Try it!
Output:
Objects
Objects are the collection of key, value pairs and each pair of key-value are known as a property. Here, the property of the key can be a string whereas its value can be of any value.
📝 Tasks:
Given a Doe family that includes two members, where each member's information is provided in form of an object.
let person = {
name: "John", //String
lastName: "Doe",
age: 35, //Number
gender: "male",
luckyNumbers: [ 7, 11, 13, 17], //Array
significantOther: person2 //Object,
};
let person2 = {
name: "Jane",
lastName: "Doe",
age: 38,
gender: "female",
luckyNumbers: [ 2, 4, 6, 8],
significantOther: person
};
let family = {
lastName: "Doe",
members: [person, person2] //Array of objects
};
- [ ] Find a way to print the name of the first member of the Doe family in a
console. - [ ] Change the fourth
luckyNumbersof the second member of the Doe family to33. - [ ] Add a new member to the family by creating a new person (
JimmyDoe,13,male,[1, 2, 3, 4],null) and update the member list. - [ ] Print the
SUMof the lucky numbers of Doe family in theconsole.
💡 Hints:
- Visit the objects chapter to understand how the object work.
- You can get
luckyNumbersfrom each person object inside the family object. - Once you get each array just loop over it adding every element and then add each sum of the 3 family members.
Try it!
Output:
User Input Variables
In JavaScript, we can take input from users and use it as a variable. One doesn't need to know their value to work with them.
📝 Tasks:
- [ ] Write a program to take input from a user and add
10to it, and print its result.
💡 Hints:
- The content of a variable is determined by the user's inputs. The
prompt()method saves the input value as a string. - You will need to make sure that the string value is converted into an integer for calculations.
- Visit the Basic Operators chapter for the type conversion of
stringtoint.