Share
Explore

JavaScript Introductory Concepts Lab Book

This lab book is designed for students with no prior programming experience. Each lesson focuses on a fundamental JavaScript concept, building upon previous lessons to create a solid foundation.

Lesson 1: Primitive Scalar Variables

JavaScript uses variables to store data. Think of them as labeled containers. There are different types of variables, but we'll start with primitive scalar variables:
* **Numbers:** e.g., `let age = 25;`
* **Strings:** e.g., `let name = "Alice";` (Notice the double quotes)
* **Booleans:** e.g., `let isAdult = true;`

**Key Concepts:**
* **`let`:** Declares a variable. Use `let` when the value of the variable might change.
* **`const`:** Declares a constant variable. Use `const` when the value should not change after it's assigned.
* **`var`:** An older way to declare variables. Avoid using `var` in modern JavaScript. We'll explain why later.
* **`typeof`:** Tells you the type of a variable. e.g., `typeof age` would return "number".
* **`valueOf`:** Returns the primitive value of a variable.
* **Comparisons:** `==` (loose equality), `===` (strict equality), `!=` (not equal), `!==` (strictly not equal), `>`, `<`, `>=`, `<=`.

Exercise: Create variables of different types, use `typeof` and `valueOf`, and experiment with comparisons.

Lab 1 Addendum: Deep Dive into Primitive Scalar Data Types
In JavaScript, data types classify the kind of values a variable can hold. Primitive scalar data types represent single values, not complex structures. Let's explore them:
image.png
Number: Represents both integers and floating-point numbers.
javascript
let integer = 42;
let float = 3.14;
let negative = -10;
let bigNumber = 9007199254740991n; // BigInt for very large integers (note the 'n')

console.log(typeof integer); // Output: "number"
console.log(typeof bigNumber); // Output: "bigint"

String: Represents text enclosed in single or double quotes.
javascript
let singleQuote = 'hello';
let doubleQuote = "hello";
let numberString = "123"; // This is a string, not a number

console.log(typeof singleQuote); // Output: "string"

Boolean: Represents logical values: true or false.
javascript
let isTrue = true;
let isFalse = false;

console.log(typeof isTrue); // Output: "boolean"

Null: Represents the intentional absence of a value. It's not zero or an empty string; it's the absence of any object value.
javascript
let nothing = null;

console.log(typeof nothing); // Output: "object" (a historical quirk)

Undefined: Indicates that a variable has been declared but hasn't been assigned a value.
javascript
let notDefined;

console.log(typeof notDefined); // Output: "undefined"

Symbol (Less Common for Beginners): Represents a unique and immutable value. Often used as keys for object properties. We won't delve deep into Symbols in this introductory lab.
javascript
const uniqueSymbol = Symbol('description'); // The description is optional

console.log(typeof uniqueSymbol); // Output: "symbol"

BigInt (For Advanced Scenarios): Represents arbitrarily large integers. Useful when dealing with numbers beyond the safe integer limit of regular numbers. We'll cover BigInts later in the course.
Important Considerations:
typeof null returns "object": This is a historical bug in JavaScript. null is not an object; it's a primitive value.
Casting: You can convert between some data types using functions like Number(), String(), and Boolean(). We'll explore type coercion and casting in a later lesson.
By understanding these primitive data types, you'll be well-equipped to work with different kinds of data in your JavaScript programs. Remember to practice and experiment with these types to solidify your understanding.


Lesson 2: Block Statements and Variable Visibility

Curly braces `{}` define code blocks. Variables declared inside a block are only visible within that block (local scope). Variables declared outside any block are global.

```javascript
let globalVar = "I'm global";

{
let localVar = "I'm local";
console.log(globalVar); // Accessible here
console.log(localVar); // Accessible here
}

console.log(globalVar); // Accessible here
console.log(localVar); // Error! localVar is not defined here
```

Exercise: Experiment with nested blocks and variable visibility.



Lesson 3: If/Else Statements


`if/else` statements allow your code to make decisions.

```javascript
let age = 18;

if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You cannot vote yet.");
}

Exercise: Create a program that checks if a number is even or odd.

error

Lesson 3: If/Else Statements (with Modulo Operator)

if/else statements allow your code to make decisions. We can use them to check if a number is even or odd using the modulo operator (%).
The Modulo Operator (%):
The modulo operator gives you the remainder of a division. For example:
10 % 2 is 0 because 10 divided by 2 has a remainder of 0.
11 % 2 is 1 because 11 divided by 2 has a remainder of 1.
Checking for Even or Odd:
A number is even if it's perfectly divisible by 2 (remainder is 0). It's odd if the remainder is 1.
javascript
let number = 10;

if (number % 2 === 0) {
console.log(number + " is even.");
} else {
console.log(number + " is odd.");
}

number = 11;

if (number % 2 === 0) {
console.log(number + " is even.");
} else {
console.log(number + " is odd.");
}

Explanation:
We declare a variable number.
The if statement checks if the remainder of number divided by 2 is equal to 0. We use strict equality (===) to ensure we're comparing numbers.
If the remainder is 0, the code inside the first block executes, printing that the number is even.
Otherwise (if the remainder is not 0, meaning it's 1), the code inside the else block executes, printing that the number is odd.
Exercise: Write a program that prompts the user to enter a number and then tells them whether the number is even or odd. Use the prompt() function to get input from the user and parseInt() to convert the input string to a number. Handle the case where the user enters something that's not a number (e.g., text). You can use a try/catch block (from Lesson 4) for error handling.

Lesson 4: Try/Catch Exception Handling


`try/catch` blocks handle errors gracefully.

```javascript
try {
// Code that might throw an error
let result = 10 / 0;
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
}

Exercise: Try to access a non-existent variable inside a `try` block and handle the error.



Lesson 5: Assignment, Equality, and Strict Equality

* `=`: Assignment operator (assigns a value to a variable).
* `==`: Loose equality (converts types before comparing).
* `===`: Strict equality (compares both value and type).

```javascript
let x = 5; // Assignment
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
```

Exercise: Experiment with different values and types using these operators.



Lesson 6: For and While Loops


Loops repeat a block of code.

* **`for` loop:**

```javascript
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log("Sum of numbers 1 to 100:", sum);
```

* **`while` loop:**

```javascript
let i = 1;
let sum = 0;
while (i <= 100) {
sum += i;
i++;
}
console.log("Sum of numbers 1 to 100:", sum);
```

Exercise: Create a loop that prints even numbers from 2 to 20.



Lesson 7: Arrays

Arrays store collections of data.

```javascript
let colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.