CodingNic

Variables, Data Types & Operators

Module Exercises

Variables, Data Types & Operators 25 min read

Module Exercises

Objectives

This chapter introduces no new concepts. It’s a chance to put Module 2 together: declaring variables, data types, typeof, operators, and type conversion.

Exercises

Write JavaScript code to do each of the following:

  1. Declare a const called productName with the value "Notebook" and a let called price with the value 4.5. Log both in a single console.log() call. Expected output: Notebook 4.5.
  2. Try reassigning productName from Exercise 1 to "Pen". Run it and, in a comment, write down the exact error name Node gives you.
  3. Declare let count = 0;. Use += to increase it by 3, then by 2. Log the final value. Expected output: 5.
  4. Given let temperature = 72;, log typeof temperature. Expected output: number.
  5. Given let selected = null;, log typeof selected. In a comment, explain why the result isn’t "null".
  6. Given let nextStep; (declared but never assigned), log both nextStep and typeof nextStep. Expected output: undefined undefined.
  7. Compare 8 and "8" using both == and ===. Log both results. Expected output: true then false. In a comment, explain why they differ.
  8. Given const quantity = 3; and const unitPrice = 2.5;, calculate and log the total using *. Expected output: 7.5.
  9. Given let stock = 10;, use % to check whether stock is even, and log the boolean result. Expected output: true.
  10. Given const age = 16;, log the result of age >= 13 && age <= 19. Expected output: true.
  11. Given const rawInput = "42";, convert it to a number with Number(), add 8, and log the result. Expected output: 50.
  12. Log the result of "7" + 3 and, separately, "7" - 3. Expected output: 73 then 4. In a comment, explain why the two operators behave differently here.
  13. Log Boolean(0), Boolean(""), and Boolean("false"). Expected output: false, false, true. In a comment, explain why the third one is true even though it looks negative.
  14. Write a short script starting with "use strict" that assigns total = 50; without declaring total first, then logs it. Run it and write down the error type it throws instead of running successfully.

Recap

You can now declare variables with const and let, recognize JavaScript’s core data types, check a value’s type with typeof, and use arithmetic, comparison, logical, and assignment operators. You can also tell the difference between converting a value’s type on purpose and JavaScript doing it for you.

Next module: Control Flow, where these values and operators drive decisions in your code.