Exercises:
Variable Declaration:
- Declare a variable named
favoriteNumber
and assign your favorite number to it. Then, log the value to the console.
let favoriteNumber = 7; console.log("My favorite number is: " + favoriteNumber);
- Declare a variable named
String Manipulation:
- Create two variables,
firstName
andlastName
, with your first and last names. Combine them to form a full name and log it to the console.
let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName; console.log("My full name is: " + fullName);
- Create two variables,
Arithmetic Operations:
- Calculate the area of a rectangle with a width of 8 units and a height of 5 units. Log the result to the console.
let width = 8; let height = 5; let area = width * height; console.log("The area of the rectangle is: " + area);
Boolean Logic:
- Write a program that checks if a user is eligible to vote based on their age. If a user is 18 years or older, log "You can vote!" to the console; otherwise, log "You cannot vote."
let userAge = 20; if (userAge >= 18) { console.log("You can vote!"); } else { console.log("You cannot vote."); }
Homework:
Variable Declarations:
- Create three variables:
carBrand
,carModel
, andcarYear
. Assign values to them that represent a car's brand, model, and manufacturing year. Log all three values to the console.
let carBrand = "Toyota"; let carModel = "Camry"; let carYear = 2022; console.log("Car: " + carYear + " " + carBrand + " " + carModel);
- Create three variables:
String Operations:
- Declare a variable
sentence
and assign it a sentence of your choice. Find the length of the sentence and log it to the console.
let sentence = "JavaScript is a powerful programming language."; let sentenceLength = sentence.length; console.log("The length of the sentence is: " + sentenceLength + " characters.");
- Declare a variable
Temperature Conversion:
- Write a program to convert a temperature from Celsius to Fahrenheit. Prompt the user for the temperature in Celsius and then display the equivalent temperature in Fahrenheit.
let celsiusTemperature = prompt("Enter temperature in Celsius:"); let fahrenheitTemperature = (celsiusTemperature * 9/5) + 32; console.log("The temperature in Fahrenheit is: " + fahrenheitTemperature);
Boolean Logic and Conditions:
- Create a program that checks if a user's username and password match a predefined set of credentials. Provide appropriate messages for both correct and incorrect login attempts.
let storedUsername = "user123"; let storedPassword = "password123"; let enteredUsername = prompt("Enter your username:"); let enteredPassword = prompt("Enter your password:"); if (enteredUsername === storedUsername && enteredPassword === storedPassword) { console.log("Login successful!"); } else { console.log("Login failed. Please check your credentials."); }