Free JavaScript Course on Scrimba: Learn Programming Basics Part I

Free JavaScript Course on Scrimba: Learn Programming Basics Part I

The only way to to learn to code is to write more code -Aristoteles

Introduction to my JavaScript Journey

These are the following topics I have learned to build the passenger Counter app.

  1. Introduction to My JavaScript Journey: Embarking on a Coding Adventure

  2. My First Project: Building a Passenger Counter App

  3. Understanding the Script Tag: Inline vs. External JavaScript Explained

  4. Mastering Variables: The Core of JavaScript Programming

  5. Playing with Numbers: Basic Math Operations in JavaScript

  6. Strings in JavaScript: Concatenation and Formatting Techniques

  7. Debugging with console.log(): A Developer's Best Friend

  8. Exploring Functions: Writing Commands to Perform Tasks

  9. Demystifying the DOM: Interacting with Web Pages

  10. My Thoughts on Data Flow and Manipulation: Creating Interactive Web Apps

  11. Using getElementById: Accessing HTML Elements Efficiently

  12. Modifying Content with .innerText: A Practical Guide

  13. Final Project: Building the Passenger Counter App

  14. HTML Code Breakdown: Understanding the Structure

  15. Conclusion: Reflecting on My Learning Experience


Hello, I go by the name Mostackito. As a newbie web developer, I've embarked on my first journey into web development with the Scrimba JavaScript course. At the end of the course, my tutor, Per Harald Borgen, encouraged me to write about my experience in a blog, sharing what I learned, how the course went, and the ups and downs of the learning journey. I have built a passenger counter app, a blackjack game, a Chrome extension, and a mobile app.

My first project was a JavaScript app called Passenger Counter.

Understanding the Script Tag: Inline vs. External JavaScript
I learned two ways to create a <script> tag: inline JavaScript, where you place the script directly in the HTML file, and

External JavaScript:

A more efficient and organised way is to write JavaScript in a separate file (e.g., index.js) and link to it using a script tag with a src attribute in your HTML index.


Mastering Variables: The Building Blocks of JavaScript
I learned that variables in JavaScript act as containers for storing data, which can change as the program runs. In my project, I worked with a variable called count, which starts at 0. I practiced increasing this value by 1, so each time the code runs, the count variable updates from 0 to 1 and continues to increment. This helped me see how variables hold values that can be updated or manipulated in real time.


Playing with Numbers: Basic Math in JavaScript
I learned that variables holding numbers can be used for basic math operations like +, -, *, and /. In a challenge, I created two variables, myAge and humanDogRatio, and then used multiplication to calculate myDogAge. By logging it to the console, I saw the result of myAge * humanDogRatio, which helped me understand how variables interact in calculations.

let myAge = 35
let humanDogRatio = 7

let myDogAge = myAge * humanDogRatio

console.log(myDogAge)

Strings in JavaScript: Concatenation and Formatting
I learned that a string is a data type used for text in JavaScript. To combine strings, we use + for concatenation, allowing us to join multiple strings together. However, JavaScript doesn’t automatically add spaces or punctuation, so we need to include these manually for proper formatting.

  • Here, messageToUser contains the full message with added punctuation and spacing."
let username = "per"
let message = "You have tree new notifications"
let messagetoUser = message + ", " + username + "!"

console.log(messagetoUser)
console.log(message + ", " + username + "!")


// Create a variable, messageToUser, that contains the message we have logged

Debugging with console.log(): A Developer's Best Friend
This is a function you use in JS to check for bugs in your code, to see if it is working correctly and outputting the intended outcome.

  • - In JavaScript, console.log() is a built-in function that allows you to output messages or values to the console. It is commonly used for debugging and understanding what is happening in your code!

"I created two variables: name and greeting. name holds my name, and greeting holds the text 'Hi, my name is.' Then I created a third variable, myGreeting, by concatenating greeting and name using +. Since JavaScript doesn't automatically add spaces or punctuation, I included them manually to format the final message properly.

This displays a formatted greeting with punctuation and spacing."

let name = "moshtak"
let greeting = "Hi my name is"

let myGreeting = greeting + ", " + name + "!"

console.log(myGreeting)

Exploring Functions: Writing Commands to Perform Tasks

  • A function is a set of commands that performs a task based on specific instructions. You define the function with instructions as its body, and when you call the function, it executes those commands to give you a result.

In my example:
I created a function, lapTimes, that adds up the times from three laps. Calling lapTimes() outputs the total lap time by adding lap1, lap2, and lap3 together."

let lap1 = 34
let lap2 = 33
let lap3 = 36

function laptimes(){
    console.log(lap1 + lap2 + lap3)
}

laptimes()

Functions in JavaScript are reusable blocks of code written to perform specific tasks. They often consist of a name and parameters (which you can think of as placeholders for values). Parameters let you pass in options or inputs when you call the function.

For example, if I want to write a function to add two numbers, I might first think, 'I need to add someNumber with anotherNumber and get back the result.' The function would look something like this:

Here, someNumber and anotherNumber are parameters that accept values when the function is called. This function adds them and returns the result.

function addTwoNumbers(someNumber, anotherNumber) {
      return someNumber + anotherNumber;
}

I’m still working on fully understanding functions, but I’m confident that with more practice, I’ll get comfortable with them. Functions are incredibly powerful in coding, and I’m excited to master them over time!


Demystifying the DOM: Interacting with Web Pages
The Document Object Model (DOM) is how JavaScript connects with and modifies a webpage. Here's a quick breakdown:

  • D for Document: This represents the HTML document, including tags like headers, paragraphs, images, and more.

  • O for Object: JavaScript turns HTML elements into objects, letting us interact with them through various methods.

  • M for Model: JavaScript organizes HTML elements into a structured model, making it easy to access and modify the document's structure and content.


My Thoughts on Data Flow and Manipulation:
By focusing on how data is structured, manipulated, and displayed, you can create more effective and interactive web apps.

  • Data Flow:
    Understanding how data moves from HTML to JavaScript and back to HTML through the DOM.

  • Manipulation:
    Using JavaScript to manipulate the data to create dynamic and interactive web pages.

  • Linkage:
    The linkage between HTML elements and JavaScript variables/functions is crucial for dynamic updates.


Using getElementById: Accessing HTML Elements
This is how you interact with HTML elements: when you create an HTML element with an ID attribute, you use the getElementById() method to interact with it.

 <h2 id="count-el">0</h2>
let countEl = document.getElementById("count-el")
console.log(countEl)

//I have created a variable countEl that grabs the html element via the
//ID count-el (“count-el“) is a string
//And I console.log it out to confirm the html element in the console.

Modifying Content with .innerText: A Practical Guide

The .innerText property lets you change or retrieve the visible text of an HTML element. This is a useful way to update content on the page through the JavaScript DOM.

Explanation: The increment function increases the count by 1 each time it runs. It then updates the countEl HTML element to display the latest count value using .innerText. This allows the webpage to reflect the new count instantly.

function increment() {
    count = count + 1
    countEl.innerText = count

/*
Function increment: It increases the count by +1 and 
updates the HTML element to display the new count via the .innerText 
property
*/

Building the Passenger Counter App

HTML Code Breakdown:

HTML Code Breakdown: Understanding the Structure

In this HTML structure, we have two buttons, each with unique ids. Each button uses the onclick event to call a specific function from the JavaScript code when clicked:

  • The first button (increment-btn) calls the increment() function to increase the count.

  • The second button (save-btn) calls the save() function to save and display the current count.

Additionally, a <p> element with the id="save-el" is included. This element will display all saved counts on the webpage by storing strings created by the line:
saveEl.textContent += countStr.
This line appends the current count to the <p> element each time the save() function runs, allowing multiple saved entries to appear sequentially.

We also have:

  • An <h2> element with id="count-el", used to display the current count value, starting initially at 0.

Finally, the JavaScript file containing the logic (index.js) is linked at the end of the <body> section using the <script src="index.js"></script> tag. This connection ensures that the JavaScript code for increment and save runs properly when the buttons are clicked.

<html>
    <head>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <h1>People entered:</h1>
        <h2 id="count-el">0</h2>
        <button id="increment-btn" onclick="increment()">INCREMENT</button>
        <button id="save-btn" onclick="save()">SAVE</button>
        <p id="save-el">Previous entries: </p>
        <script src="index.js">
            nnerText
        </script>
    </body>
</html>

JavaScript Code Breakdown:

In this project, two main variables, saveEl and countEl, are assigned HTML elements using the getElementById() method. These elements will display the current count and saved entries on the page.

We also initialise a count variable set to 0, which will track the current count value.

increment() function:

This function increments the count by 1 each time the button is clicked. We use:

count += 1

to add 1 to the count variable and then update the displayed value in countEl by setting:

countEl.textContent = count

This ensures the new count appears on the webpage instantly

save() function:

The save() function is used to save the current count as a string, followed by " - " for separation:

let countStr = count + " - "

We then add this string to saveEl using:

saveEl.textContent += countStr

This appends countStr to the previous entries without overwriting them.

Finally, we reset the counter. Setting countEl.textContent = 0 visually resets the count, while count = 0 resets it internally for future increments.

Final Code:

let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let count = 0

function increment() {
    count += 1
    countEl.textContent = count
}

function save() {
    let countStr = count + " - "
    saveEl.textContent += countStr
    countEl.textContent = 0
    count = 0
}

Link to my app

Conclusion: Reflecting on My Learning Experience

Reflecting on my journey through the Scrimba JavaScript course, I feel a strong sense of accomplishment and growth. This course has been an essential step in my web development journey, providing a solid foundation in JavaScript. From mastering basics like variables and functions to understanding the DOM, each lesson has added a crucial building block towards creating interactive applications. Building my first JavaScript app, the Passenger Counter, was especially rewarding; it brought together everything I’d learned, from using functions to increment counts to dynamically displaying saved values with DOM manipulation. Though there were challenges, each obstacle became a valuable learning experience. I’m excited to continue exploring web development, and this experience has not only strengthened my technical skills but also boosted my confidence to take on future projects.


PROJECT: BLACKJACK GAME

These are the following topics I have learned building the blackjack game.

1. Arrays: Harnessing the Power of JavaScript Arrays for Data Management

2. Objects: Understanding JavaScript Objects for Structured Data

3. Booleans: Mastering True and False with JavaScript Booleans

4. If Else Statements: Making Decisions with JavaScript If-Else Logic

5. Comparison Operators: Utilizing the AND Operator for Effective Comparisons

6. Logical Operators: Understanding JavaScript’s Logical Operators

7. For Loops: Iterating with Precision Using JavaScript For Loops

8. The Math Object: Leveraging JavaScript’s Math Object for Calculations

9. Return Statements: Crafting Efficient Functions with JavaScript Return Statements

10. Building My First JavaScript Blackjack Game: A Step-by-Step Guide

11. HTML Code Explanation: Setting Up the User Interface

12. JavaScript Code Explanation: Game Logic and Flow

Arrays: Harnessing the Power of JavaScript Arrays for Data Management

An array is like a container, similar to a variable, but with the unique capability to hold multiple values of different data types within the same structure. Unlike a standard variable, which typically holds a single value, arrays are designed to store several pieces of data in one place, making them useful for managing lists of items.

To create an array, use square brackets [ ] and separate each item (or element) with a comma. Arrays are zero-indexed, which means that indexing begins at 0. For instance, in an array like food = [fruits, meat, veggies], the first element, "fruits," is at index 0, "meat" at index 1, and "veggies" at index 2.

Arrays also have a built-in property called .length, which provides the total count of items in the array. This property is not zero-indexed—its purpose is solely to indicate the number of elements, regardless of their positions. So, in our food array example, .length would return 3, reflecting the total number of items.

One key feature of arrays is their ability to hold multiple data types, which can include strings, numbers, and booleans. For example, an array can contain a name as a string, an age as a number, and a status as a boolean, grouping related information in one structure.

let moshtak = ["moshtak", 35, true]

console.log(moshtak)
console.log( moshtak [0])
console.log(moshtak [1] )
console.log(moshtak [2])

Console
›["moshtak", 35, true]
›moshtak
›35true

I’ve been learning about array methods, specifically push() and pop(). The push() method adds new elements to the end of an array.

For one challenge, I had an array called messages that I wanted to add a new message to. By using push(), I added newMessage to the end of messages. After this, messages included both the original entries and the new addition. I used console.log() to view the updated array, confirming the addition was successful.

// Push the newMessage to the messages array, and then log out the array

let messages = [
    "Hey, how's it going?",        
    "I'm great, thank you! How about you?",
    "All good. Been working on my portfolio lately."
]

let newMessage = "Same here!"

//solution
messages.push(newMessage)
console.log(messages)

Console
›["Hey, how's it going?", "I'm great, thank you! How about you?", 
"All good. Been working on my portfolio lately.", "Same here!"]

Next, I explored the pop() method, which removes the last element from an array. In this challenge, after using push() to add newMessage to the messages array, I applied pop() to remove the last element.

The pop() method is particularly useful because it targets the last element without needing to know the array's exact length. To confirm the removal, I used console.log() again to display the updated array, where newMessage was no longer present.

After applying pop(), the messages array reverted to its original state, demonstrating the method's effect.

// Push the newMessage to the messages array, and then log out the array

let messages = [
    "Hey, how's it going?",        
    "I'm great, thank you! How about you?",
    "All good. Been working on my portfolio lately."
]

let newMessage = "Same here!"

//solution
messages.push(newMessage)
console.log(messages)

Console
›["Hey, how's it going?", "I'm great, thank you! How about you?", 
"All good. Been working on my portfolio lately.", "Same here!"]

// How can you remove the last item in an array? Try to google it!

messages.pop()
console.log(messages)

Console
›["Hey, how's it going?", "I'm great, thank you! How about you?", 
"All good. Been working on my portfolio lately."]

Objects: Understanding JavaScript Objects for Structured Data

Objects are a way to store multiple related data types within a single structure. Unlike primitive data types, such as numbers or strings, objects are dynamic, meaning their properties can be changed after they are created.

Objects can contain a mix of data types, including numbers, strings, booleans, and even other objects or arrays.

You define an object using curly brackets { }, where each piece of data is stored as a property in the form of key-value pairs. For example, in the object below, the keys include title, lessons, creator, and length, while the corresponding values are "Learn CSS Grid for free", 16, "Per Harald Borgen", and 63.

In this case, course.tags retrieves the array ["html", "css"].

let course = {
    title: "Learn CSS Grid for free",
    lessons: 16,
    creator: "Per Harald Borgen",
    length: 63,
    level: 2,
    isFree: true,
    tags: ["html", "css"]
}


console.log( course.tags )

Console
›["html", "css"]

In another challenge, I was tasked with creating an object that represents an Airbnb castle listing. The goal was to include different data types: at least one boolean, one string, one number, and one array.

For this object, I defined the following keys: title, price, isSuperHost, and images. The corresponding values are "Live like a king in my castle" (a string), 190 (a number), true (a boolean), and ["img/castle1.png", "img/castle2.png"] (an array).

To log out the values, I used the dot notation with the object name and the specific key. Here’s how it looks:

let castle = {
    title: "Live like a king in my castle",
    price: 190,
    isSuperHost: true,
    images: ["img/castle1.png", "img/caste2.png"]
}

console.log(castle.price)
console.log(castle.isSuperHost)

//The output confirms the values:
Console
›190true

The last concept I explored was methods on objects. Methods are actions or behaviors that are associated with objects, allowing us to interact with and manipulate the data contained within them.

For example, in JavaScript, the document object has methods like getElementById, which enable us to select and manipulate elements on a webpage. Here, document is the object, and getElementById is the method that operates on it.

In essence, a method is a function that serves as a property of an object, allowing us to perform specific actions related to that object.

Regarding Data Types:

  • Objects are dynamic data types that can store multiple values and be modified. They can contain complex data types, including arrays, functions, and other objects.

  • Primitive Data Types, such as numbers, strings, and booleans, are simpler and immutable. They cannot be changed directly and are not considered objects.


Booleans: Mastering True and False with JavaScript Booleans

Booleans are true/false values used to represent binary choices, such as:

  • YES / NO

  • ON / OFF

  • TRUE / FALSE

In programming, booleans are crucial for making decisions between two possibilities. JavaScript has a Boolean data type that can only hold one of two values: true or false.

For example, you can create a boolean to represent the state of the weather. Let's assume the typical British weather is often bad, so we might set it as true (indicating bad weather). To check and respond to this condition, we use if, else if, and else statements.

  • The if block checks whether the condition (e.g., greatBritishWeather) is true and executes a specific action if it is.

  • The else if block checks whether the condition is false, allowing the program to handle the opposite scenario.

  • The else block serves as a fallback when neither the if nor else if conditions are met, ensuring that the program has a default action to take, which acts as a safety net.

In this example, if the weather changes and becomes good, the else if block would handle that situation. If the weather doesn’t match either extreme, the else block will execute, providing a fallback message.

Code Example:

let greatBritishWeather = false;

if (greatBritishWeather) {
    console.log("It's typical British weather!");
} else if (!greatBritishWeather) {
    console.log("The weather seems to be changing.");
} else {
    console.log("Looks like the sun came out!");
}

//output
The weather seems to be changing.

When you use boolean variables with if, else if, and else statements, you're checking whether the condition is true or false to determine which block of code to execute.

A boolean is a data type that represents either true or false. You can use if, else if, and else conditions to evaluate the state of a boolean and define different actions based on the result. Each condition allows you to handle a specific outcome (whether it's true or false), while the else block acts as a catch-all for any other possibilities not covered by the preceding conditions.

In essence, these conditional statements enable you to "branch" the logic of your program based on the boolean (or other conditions), allowing your code to react appropriately to various scenarios.


If Else Statements: Making Decisions with JavaScript If-Else Logic

If-else statements are used to check the truthfulness of variables and make decisions based on their values.

Challenge Solved:

  • Check if a person is old enough to enter a nightclub (age 21)

  • Log a suitable message to the console in both cases.

In this challenge, we check the age variable in the if statement. If the age is less than 21, the following message will be logged to the console:

Console Output: "You cannot enter the club!"

If you change the value of age to 22, the message will be: "Welcome!"

Code:

let age = 18

if (age < 21) { 
    console.log("You can not enter the club!")
}
 else {
    console.log("Welcome!")
}

//output
Console you can not enter the club!

Challenge: Check Eligibility for a Birthday Card from the King
In this challenge, we determine if a person is eligible for a birthday card from the King at age 100.

Explanation:
The variable age is set to 100, which means the second condition (else if) will execute, and the other conditions will be ignored. Therefore, the message logged to the console will be: "Here is your birthday card from the King!"

By changing the value of the age variable, different condition blocks will run, resulting in different outputs:

  • If age is less than 100, the output will be: "Not eligible."

  • If age is exactly 100, the output will be: "Here is your birthday card from the King!"

  • If age is greater than 100, the output will be: "Not eligible, you have already gotten one."

Console Output: "Here is your birthday card from the King!"

Code:

let age = 100

if (age < 100) {
    console.log("Not elegible")  
} else if ( age === 100) {
    console.log("Here is your birthday card from the King!")
} else{
    console.log("Not elegible, you have already gotten one")
}

Console
›Here is your birthday card from the King!

Comparison Operators: Utilizing the AND Operator (&&) for Effective Comparisons

The AND operator (&&) checks if multiple conditions are true. In an if statement, the block will only execute if all conditions are true; if any condition is false, the block won’t run.

Example:
In the following code, two boolean variables—hasCompletedCourse and givesCertificate—are both set to true. The if statement checks whether both conditions are satisfied. If they are, the generateCertificate() function is called, which outputs "Generating certificate...." to the console.

This ensures that a certificate is generated only when both criteria are met, enhancing the code's robustness.

Key Point: All conditions connected by && must be true for the block to execute.

Code:

let hasCompletedCourse = true
let givesCertificate = true

if (hasCompletedCourse === true && givesCertificate === true) {
    generateCertificate()
}

function generateCertificate() {
    console.log("Generating certificate....")
}

Logical Operators: Understanding JavaScript's Logical Operators

Logical operators combine conditions and return a boolean value. The main logical operators are:

  • (&&) AND: Returns true if both conditions are true; false if either is false.

  • (||) OR: Returns true if at least one condition is true; false if both are false.

For the OR operator (||), if either condition is true, the code inside the if statement will execute.

Challenge: Create two boolean variables, likesDocumentaries and likesStartups. Use an OR statement (||) to call recommendMovie() if either variable is true.

Example: In this code, since likesDocumentaries is true and likesStartups is false, the recommendMovie() function will run.

Code:

let likesDocumentaries = true
let likesStartups = false
if (likesDocumentaries === true || likesDocumentaries === true){
    recommendMovie()
}


function recommendMovie() {
    console.log("Hey, check out this new film we think you will like!")
}

For Loops: Iterating with Precision Using JavaScript For Loops

Understanding the for Loop

A for loop iterates through data by specifying a START, END, and INCREMENT (SIZE).

Challenge: Count from 1 to 10.

Solution: To count from 1 to 10, I initialized a variable count with a value of 1 and used a for loop to increment it by 1 until it reaches 10. The loop stops when count becomes greater than or equal to 11.

Breakdown of the for loop:

  • START: let count = 1 initializes count at 1.

  • END: count < 11 allows the loop to run while count is less than 11.

  • INCREMENT: count += 1 increases count by 1 in each iteration.

Code:

//    START           FINISH       STEP SIZE
for ( let count = 1;  count < 11;  count += 1 )  {

    console.log(count)

}

Combining for Loops and Arrays

Using for loops with arrays allows us to efficiently access and manipulate each element.

Challenge: Log all cards in the array.

Solution: We created a for loop that starts at index 0 and iterates through each element in the cards array. The loop uses the .length property to adjust its endpoint dynamically, ensuring it accommodates changes in the array size. It increments by 1 (i += 1), allowing it to access each element sequentially.

Code:

let cards = [7, 3, 9]

for (let i = 0; i < cards.length; i+= 1) {
    console.log(cards[i])
}

//output
Console
›739

Challenge: Rendering a Sentence with a For Loop

Task: Render a sentence inside the greetingEl paragraph using a for loop and .textContent.

Solution: I created a for loop that iterates over the sentence array, starting at index 0. The loop uses the .length property to adjust dynamically to changes in the array size, incrementing by 1 (i++) to access each element.

To display the sentence, I set greetingEl.textContent by appending each element from the array using +=.

Bonus Challenge: If spaces between words are removed from the array, I can add a space while rendering by appending " " to each element. For example:

let sentence = ["Hello ", "my ", "name ", "is ", "Per"] 
let greetingEl = document.getElementById("greeting-el")

for (let i = 0; i < sentence.length; i++){
    greetingEl.textContent += sentence[i]
}

/*
how do you keep the spaces between the words 
if you remove them from the array?
*/

let sentence = ["Hello", "my", "name", "is", "Per"] 
let greetingEl = document.getElementById("greeting-el")

for (let i = 0; i < sentence.length; i++) {
    greetingEl.textContent += sentence[i] + " "  
}

// I have added the spacing in the rendering part of the code. + " "

For loops and arrays are a powerful combination in programming. A for loop lets you iterate through data with defined start, end, and increment parameters, while arrays provide a flexible way to store and manipulate data. Together, they allow for efficient data processing and transformation in creative ways.


The Math Object: Leveraging JavaScript's Math Object for Calculations

Explanation:
Math.random() generates a random decimal number between 0 (inclusive) and 1 (exclusive), returning values like 0.0001 or 0.5432, but never 1. It’s commonly used in areas like cryptography, cybersecurity, and gaming to introduce randomness.

Multiplying Math.random() by a number (e.g., Math.random() * 6) scales the result, producing a value between 0 and 5.9999. This extends the range while keeping the value below the whole number you're multiplying by.

To round down the result, we use Math.floor(), which removes the decimal part. For instance, Math.floor(12.999999) rounds down to 12.

Example:

let flooredNumber = Math.floor(12.999999999999)

console.log(flooredNumber)

Console
›12

Challenge:
Modify the expression to generate a random number between 1 and 6.

Solution:
By adding +1, we shift the range from 0-5 to 1-6.

Code:

let randomNumber = Math.floor( Math.random() * 6 ) + 1

console.log(randomNumber)

Challenge:
Create a function, rollDice(), that returns a random number between 1 and 6.

Solution:
I created the rollDice() function to simulate a dice roll by generating a random number between 1 and 6. Inside the function, I declared a variable randomNumber, which uses Math.random() * 6 to get a value between 0 and 5.9999. Applying Math.floor() rounds it down to 0-5, and adding 1 shifts the range to 1-6.

The return statement outputs the randomNumber, allowing the function to display the result when called.

Code:

let randomNumber = Math.floor( Math.random() * 6 ) + 1

function rollDice() {
    let randomNumber = Math.floor(Math.random() * 6 ) + 1
    return randomNumber
}

console.log(rollDice())

Console
›15

Return Statements: Crafting Efficient Functions with JavaScript Return Statements

The return statement in functions sends a value back to the caller, allowing it to be logged or stored in a variable for later use. You can think of functions as recipes: they take specific inputs, process them, and provide an output.

Challenge:
Write a function that returns the total race time, call it, store the returned value in a variable, and log that variable.

Solution:
In this example, the totalRaceTime function calculates the total race time by adding player1Time and player2Time. When totalRaceTime() is called, it executes the function, returns the result, and stores it in the totalTime variable, which can then be logged or used elsewhere.

Code:

let player1Time = 102
let player2Time = 107

function totalRaceTime() {
    return player1Time + player2Time

}

let totalTime = totalRaceTime()
console.log(totalTime)

Console
›209

So, essentially, the return statement "sends back" a result from the function, making it available to whatever calls the function.

Another Challenge:
Complete getRandomNumber function;
Solution:

The getRandomCard function generates a random number between 1 and 13, representing a card drawn from a deck.

  • Random Number Generation: It uses Math.floor(Math.random() * 13) + 1 to achieve this.

  • Face Cards Logic: If the generated number (randomNumber) is greater than 10, the function returns 10, which corresponds to the face cards (Jack, Queen, King).

  • Ace Card Logic: If randomNumber equals 1, the function returns 11, representing the Ace card, which can count as either 1 or 11 in many games.

  • Returning Numbers: For any other number between 2 and 10, the function simply returns that number.

Overall, the function effectively handles the unique values associated with a deck of cards.

function getRandomCard() { 
    // if 1     -> return 11
    // if 11-13 -> return 10
    let randomNumber = Math.floor( Math.random()*13 ) + 1
    if (randomNumber > 10) {
        return 10
    } else if (randomNumber === 1) {
        return 11
    } else {
        return randomNumber
    }
}

Building my first JavaScript Blackjack game

HTML Code Breakdown:

This is the HTML code for my Blackjack game. The document begins with a title created using the <h1> tag, which labels the game.

I have also included four <p> paragraphs with unique IDs assigned to each, such as message-el, cards-el, and sum-el. These IDs will allow JavaScript to dynamically update the content displayed to the user during the game.

Additionally, I created two button elements that trigger specific actions when clicked: the "START GAME" button calls the startGame() function to initialize the game, while the "NEW CARD" button invokes the newCard() function to draw a new card.

Overall, this HTML structure sets up the user interface for the Blackjack game, providing elements for displaying game information and buttons for user interaction.

<html>
    <head>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <h1>Blackjack</h1>
        <p id="message-el">Want to play a round?</p>
        <p id="cards-el">Cards:</p>
        <p id="sum-el">Sum:</p>
        <button onclick="startGame()">START GAME</button>
        <button onclick="newCard()">NEW CARD</button>
        <p id="player-el"></p>
        <script src="index.js"></script>
    </body>
</html>

JavaScript Code Breakdown:

  • Variables and Initial Setup: I will Describe the purpose of each initial variable, including the player object, array for cards, and the boolean flags.

  • DOM Elements and Player Display: I will Explain how and why elements are selected with getElementById and how the player’s name and chips are displayed.

  • Random Card Generation (getRandomCard): I will Detail how getRandomCard works, including the reasoning behind the conditional checks.

  • Game Flow (startGame and renderGame): I will Break down startGame to set up a new game and initialize variables. Then explain how renderGame displays the game status and controls the main game logic based on sum.

  • Adding a New Card (newCard): I will Walk through the conditions that allow for drawing a new card and explain the role of renderGame in updating the game state.


Variables and Initial Setup

The cards variable is an array that will store the cards drawn in the game, and the sum variable will keep track of their combined total. The hasBlackJack and isAlive variables are both booleans: hasBlackJack checks if the player has hit Blackjack (21), while isAlive checks if the player is still in the game or has lost. The message variable is an empty string that will be used to store different messages shown to the player based on their score during the game.

The variables messageEl, sumEl, cardsEl, and playerEl refer to elements in the HTML (DOM elements) where this information will be displayed on the webpage, like the player’s current cards, sum, and status messages.


DOM Elements and Player Display:

The messageEl variable selects an HTML element with the getElementById() method, using "message-el" as the argument. This allows us to easily update this element with different messages throughout the game, like "Want to play a round?" at the start.

The sumEl variable is used to display the total value of the cards drawn so far. Each time the player interacts with the "START GAME" or "NEW CARD" button, the sum of the cards is recalculated and updated in this element on the webpage.

The cardsEl variable is responsible for showing the individual cards the player has drawn. When the player draws a new card by clicking the "NEW CARD" button, this element displays the updated list of cards under "Cards:".

The playerEl variable displays the player’s name and current chips on the page. To achieve this, we create an object called player with two keys: name and chips. By setting playerEl.textContent to player.name and player.chips, we dynamically show the player’s name and chip count, giving a personalized feel to the game.


Random Card Generation (getRandomCard):

The getRandomCard() function is used to simulate the drawing of a card in Blackjack, where cards have values between 1 and 13. Inside the function, a random number is generated to represent the card value.

  1. Random Number Generation: The randomNumber variable is created by combining Math.random() and Math.floor():

    • Math.random() generates a random decimal between 0 (inclusive) and 1 (exclusive).

    • Multiplying by 13 and using Math.floor() rounds the result down to the nearest integer, giving a range from 0 to 12.

    • Adding 1 shifts the range from 1 to 13, matching card values used in Blackjack.

  2. Conditional Checks:

    • if (randomNumber > 10): If the number is 11, 12, or 13, it corresponds to face cards (Jack, Queen, King), which all have a value of 10 in Blackjack. The function returns 10 for these cases.

    • else if (randomNumber === 1): If the number is 1, it represents an Ace. In Blackjack, an Ace can be worth either 1 or 11. Here, the function assumes the Ace is worth 11 and returns that.

    • else: For any other value (2-10), the function returns randomNumber itself, as these represent regular cards with values 2 through 10.

Summary:

The getRandomCard() function simulates card drawing by generating a number from 1 to 13, then applying specific rules for face cards (11-13) and Aces (1) to return values that follow Blackjack rules. This approach captures the randomness and special values of cards in the game.


Game Flow (startGame and renderGame):

The startGame() function initiates a new round by setting isAlive = true, indicating that the player is actively in the game. It draws two initial cards by calling the getRandomCard() function twice, storing these values in firstCard and secondCard. This gives the player two starting cards, which are then added to the cards array for tracking. Next, the sum variable is updated to reflect the total of these two cards, providing the initial sum for gameplay. Finally, startGame() calls the renderGame() function, which will handle updating the game display and determining the player’s next options based on the current sum.

The renderGame() function manages the game’s display and main logic by updating the cards, sum, and message elements on the webpage. Here’s a breakdown:

  1. Displaying Cards:
    We start by setting cardsEl.textContent to "Cards: ", which provides the label for the cards section. Then, a for loop iterates through the cards array (which contains the player’s current cards) and appends each card’s value to cardsEl.textContent. The + " " in this line adds a space between each card for easier readability.

  2. Displaying Sum:
    The sumEl element is updated next to display "Sum: " followed by the current sum. This sum represents the total value of the player’s cards, calculated in startGame().

  3. Main Game Logic (Conditions):
    Using an if...else if...else structure, the function determines the message to display:

    • If sum <= 20: The player hasn’t reached Blackjack, so the message prompts, "Do you want to draw a new card?"

    • Else if sum === 21: The player has hit Blackjack, so hasBlackJack is set to true, and the message is "You've got Blackjack!"

    • Else: If the sum exceeds 21, the player is "out of the game," and isAlive is set to false to mark the end of the round.

  4. Displaying the Message:
    Finally, messageEl.textContent is set to message, which now holds the appropriate message based on the game’s current state.


Adding a New Card (newCard):

The newCard() function allows the player to draw a new card under certain conditions and updates the game’s display with renderGame().

  1. Conditions for Drawing a Card:
    The if statement checks two conditions:

    • isAlive === true: Ensures that the player is still in the game.

    • hasBlackJack === false: Confirms that the player hasn’t already hit Blackjack.
      Both conditions must be true for the function to proceed with drawing a new card.

  2. Drawing and Adding a New Card:
    Inside the if block:

    • A new variable, card, is created by calling getRandomCard(). This generates a random card value to be added to the game.

    • The sum variable is updated by adding card to the current sum, reflecting the new total of all drawn cards.

    • The card is added to the cards array using the push() method, which updates the list of displayed cards.

  3. Updating the Game Display:
    Finally, renderGame() is called to refresh the webpage display with the updated cards, sum, and message based on the new game state.


Final Code:

let player = {
    name: "player",
    chips: 200
}

let cards = []
let sum = 0
let hasBlackJack = false
let isAlive = false
let message = ""
let messageEl = document.getElementById("message-el")
let sumEl = document.getElementById("sum-el")
let cardsEl = document.getElementById("cards-el")
let playerEl = document.getElementById("player-el")

playerEl.textContent = player.name + ": $" + player.chips

function getRandomCard() {
    let randomNumber = Math.floor( Math.random()*13 ) + 1
    if (randomNumber > 10) {
        return 10
    } else if (randomNumber === 1) {
        return 11
    } else {
        return randomNumber
    }
}

function startGame() {
    isAlive = true
    let firstCard = getRandomCard()
    let secondCard = getRandomCard()
    cards = [firstCard, secondCard]
    sum = firstCard + secondCard
    renderGame()
}

function renderGame() {
    cardsEl.textContent = "Cards: "
    for (let i = 0; i < cards.length; i++) {
        cardsEl.textContent += cards[i] + " "
    }

    sumEl.textContent = "Sum: " + sum
    if (sum <= 20) {
        message = "Do you want to draw a new card?"
    } else if (sum === 21) {
        message = "You've got Blackjack!"
        hasBlackJack = true
    } else {
        message = "You're out of the game!"
        isAlive = false
    }
    messageEl.textContent = message
}


function newCard() {
    if (isAlive === true && hasBlackJack === false) {
        let card = getRandomCard()
        sum += card
        cards.push(card)
        renderGame()        
    }
}

Here’s a quick summary of how the Blackjack game app was broken down:

  1. Initial Setup: You start with variables to keep track of the game state, including cards (array of drawn cards), sum (total value of the cards), and booleans like isAlive (whether the player is still in the game) and hasBlackJack (whether they hit exactly 21). DOM elements display the game status to the player.

  2. getRandomCard(): This function generates a random card value between 1 and 11 to simulate the cards in Blackjack. Cards above 10 return a value of 10, and an Ace (1) returns 11 for simplicity.

  3. startGame(): This initializes the game by setting isAlive to true, drawing two random cards with getRandomCard(), storing them in cards, calculating their sum, and then calling renderGame() to display the results.

  4. renderGame(): This function updates the game display by showing the drawn cards, the current sum, and a message to prompt the player. If the sum is less than 21, it invites the player to draw another card. If the sum is 21, the player wins ("Blackjack!"). If the sum is over 21, the player is out.

  5. newCard(): Allows the player to draw another card if they haven’t won or lost yet. It adds the new card’s value to sum, updates cards, and calls renderGame() again to refresh the game status.

link to my app


I want to take a moment to express my deepest gratitude to my incredible tutors, Per Borgen and Rafid Hoda, for their unwavering support and guidance throughout this amazing free Scrimba JavaScript course. @perborgen and @rafidhoda, your passion for teaching and your dedication to making coding accessible to everyone have truly inspired me.

Through your clear explanations and engaging lessons, I’ve not only built my first app but also gained confidence in my ability to code—something I never thought possible. This course has been life-changing, and it’s all thanks to your efforts.

As I move forward, I’m excited to continue learning and exploring more courses with Scrimba. Thank you for making this journey so memorable and for believing in every student’s potential.

Here’s to the community you’ve built and the countless lives you’re changing—one line of code at a time!

Twitter link for Rafid Hoda
Twitter link for Per Borgen

With immense gratitude and admiration,

Mostackito 👨🏻‍💻❤️