Share
Explore

Lab work book JavaScript: Loops, Branching, and Functions

Learning Outcomes:
In this lecture, we will be exploring fundamental concepts such as loops, if-then branching, and functions. We will also discuss other relevant topics like variables, data types, and arrays.
Variables and Data Types
JavaScript has a few basic data types, including numbers, strings, and booleans. To declare a variable, you can use the let keyword, followed by the variable name and an optional assignment.

let age = 25;
let name = "John Doe";
let isStudent = true;

Exercise 1:
Declare two variables: 'a' with a value of 10 and 'b' with a value of 20. Then, create a third variable called 'sum' and store the result of adding 'a' and 'b' in it.
If-Then Branching (Conditional Statements)
The if statement allows you to execute a block of code only if a specific condition is met. You can also use else if and else to check for additional conditions or provide a default action.

let weather = "sunny";

if (weather === "sunny") {
console.log("Let's go to the beach!");
} else if (weather === "rainy") {
console.log("Let's stay indoors.");
} else {
console.log("Let's check the weather forecast.");
}

Exercise 2:
Write an if-then-else statement that checks whether a number is positive, negative, or zero. Print the result to the console.
Loops
Loops allow you to repeatedly execute a block of code. JavaScript has several types of loops, including for, while, and do-while. Here's an example of a for loop:
javascriptCopy code
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}

Exercise 3:
Write a loop that prints the first 10 numbers of the Fibonacci sequence.
Arrays
An array is a data structure used to store multiple values in a single variable. You can create an array using the square bracket syntax and access its elements using indices.
javascriptCopy code
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: "red"

Exercise 4:
Create an array containing the names of 5 fruits. Then, use a loop to print each fruit's name.
Functions
Functions are reusable blocks of code that can be called with a specific set of input values, known as arguments. Functions can return a value as a result.
javascriptCopy code
function greet(name) {
return "Hello, " + name + "!";
}

let greeting = greet("Alice");
console.log(greeting); // Output: "Hello, Alice!"

Exercise 5:
Write a function called 'multiply' that takes two numbers as arguments and returns their product. Test your function with a few examples.
Conclusion:
Congratulations! You have learned the basics of JavaScript, including variables, data types, if-then branching, loops, arrays, and functions. Practice these concepts with the exercises provided, and you'll be well on your way to mastering JavaScript. Happy coding!

JavaScript 'typeof': Understanding Data Types

Welcome to our lecture on the typeof operator in JavaScript! In this lecture, we will explore the typeof operator, its usage, and its importance in understanding the data types of variables and values. We will also look at some common use cases and caveats. Let's dive in!
Introduction to typeof
In JavaScript, the typeof operator is used to determine the data type of a given value or variable. It returns a string that describes the data type, such as "number", "string", "boolean", "object", or "undefined". This operator can be very useful in situations where you need to ensure that a value is of a specific type before performing an operation.
Here's a simple example:
let number = 42;
console.log(typeof number); // Output: "number"

Basic Usage of typeof
Now, let's look at some more examples of typeof to understand how it works with different data types:
javascriptCopy code
let string = "Hello, World!";
console.log(typeof string); // Output: "string"

let boolean = true;
console.log(typeof boolean); // Output: "boolean"

let object = { name: "Alice", age: 30 };
console.log(typeof object); // Output: "object"

let array = [1, 2, 3, 4, 5];
console.log(typeof array); // Output: "object"

let func = function () {
return "Hello!";
};
console.log(typeof func); // Output: "function"

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

let nullable = null;
console.log(typeof nullable); // Output: "object"

As you can see, typeof works as expected for most data types, with a couple of exceptions. Arrays are considered "objects", and null values are also considered "objects" due to a historical bug in the language.
Common Use Cases
The typeof operator is often used for input validation, error handling, and conditional execution of code based on the data type. Here's an example of using typeof for input validation:
javascriptCopy code
function add(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new Error("Both arguments must be numbers.");
}
return a + b;
}

console.log(add(1, 2)); // Output: 3
console.log(add("1", 2)); // Throws an error

Caveats and Limitations
While typeof is a useful tool, it has some limitations. For instance, it cannot differentiate between plain objects and more specific object types, such as arrays or dates. To overcome this limitation, you can use more advanced techniques like Array.isArray() or Object.prototype.toString.call().
javascriptCopy code
console.log(Array.isArray([1, 2, 3])); // Output: true
console.log(Object.prototype.toString.call(new Date())); // Output: "[object Date]"

Conclusion:
The typeof operator is an essential tool in JavaScript for determining the data type of a value or variable. It's commonly used for input validation, error handling, and conditional code execution. However, it's important to be aware of its limitations and use alternative methods for more specific type checks when necessary. By understanding and utilizing typeof, you will be better equipped to write robust and reliable JavaScript code.
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.