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:
- Declare a
constcalledproductNamewith the value"Notebook"and aletcalledpricewith the value4.5. Log both in a singleconsole.log()call. Expected output:Notebook 4.5. - Try reassigning
productNamefrom Exercise 1 to"Pen". Run it and, in a comment, write down the exact error name Node gives you. - Declare
let count = 0;. Use+=to increase it by3, then by2. Log the final value. Expected output:5. - Given
let temperature = 72;, logtypeof temperature. Expected output:number. - Given
let selected = null;, logtypeof selected. In a comment, explain why the result isn’t"null". - Given
let nextStep;(declared but never assigned), log bothnextStepandtypeof nextStep. Expected output:undefined undefined. - Compare
8and"8"using both==and===. Log both results. Expected output:truethenfalse. In a comment, explain why they differ. - Given
const quantity = 3;andconst unitPrice = 2.5;, calculate and log the total using*. Expected output:7.5. - Given
let stock = 10;, use%to check whetherstockis even, and log the boolean result. Expected output:true. - Given
const age = 16;, log the result ofage >= 13 && age <= 19. Expected output:true. - Given
const rawInput = "42";, convert it to a number withNumber(), add8, and log the result. Expected output:50. - Log the result of
"7" + 3and, separately,"7" - 3. Expected output:73then4. In a comment, explain why the two operators behave differently here. - Log
Boolean(0),Boolean(""), andBoolean("false"). Expected output:false,false,true. In a comment, explain why the third one istrueeven though it looks negative. - Write a short script starting with
"use strict"that assignstotal = 50;without declaringtotalfirst, 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.