Code Accelerator - Web Developer Kit
Code Accelerator - Web Developer Kit
WEB DEVELOPER
CERTIFICATION KIT
Level 1-1—Unlocking the Power of Code To Change Your World 6
Everyone Can Code, Including You! 7
No One Gets Left Behind. 7
Learn to Think Like A Coder. 8
Javascript is everywhere. 9
The Back-end 11
Developer Tools: IDEs and editors 12
Developer Tools: Developer Console 12
Variables 13
Basic Data Types 13
Reference Data Types 14
Let’s Review! 15
Preview Next Lesson 16
Your Turn Now. 16
Homework Assignment—Building Confidence Through Practice 16
Homework #1 16
Homework #2 17
Homework #3 18
You did it! 18
Level 1-2: Building Your Programming Fundamentals with Tic-Tac-Toe 20
Art vs. Science 21
The Science of Coding 21
The Art of Coding 21
Bringing Art and Science Together 22
Why This Matters for Developers 22
More about variables 23
Declaring Variables with let 24
Initializing Variables with let 24
Declaring and Initializing in One Step 25
Understanding const 25
Use Cases 26
Best Practices 26
You did it! 26
Introduction to var 27
Understanding Where Your Variables Can Be Used (Introducing "Scope") 27
Redeclaration with var 28
Understanding Redeclaration with let 28
Understanding Hoisting (Moving Variables To The Top of the Scope) 29
Hoisting with var vs. let and const 30
Why This Matters 31
Understanding Functions in JavaScript with Simple Examples 31
Example #1: A Function to Make a Sandwich 31
Defining Functions 31
Using the makeSandwich Function 33
Example 2: A Function to Calculate the Area of a Rectangle 33
Defining a calculateArea Function 33
Using the Function 34
The console Object and the log Method 34
The console Object 34
The log Method 34
How console.log Relates to Defining Functions 35
Why This Matters 36
Introducing Hoisting and Function Scope with Simple Functions 36
Do You Remember What Hoisting Is? 36
A Function to Make Coffee 37
Example: A Function to Calculate Discount 37
The var Quirk 38
Arrays and Indexed Collections 39
Loops 40
Using a for Loop 41
Understanding the for Loop and Array Length 41
How the Loop Works 42
Introduction to Comparison 43
The Less Than Operator in Action 43
What’s Going On Here? 43
Connecting the Dots 44
From < to Equality Comparisons 44
Loose Equality (==) 44
What’s Happening Here? 45
Strict Equality (===) 45
What’s Happening Here? 45
Why It Matters 45
Practical Example: Checking User Input 46
Bringing It All Together: The .every Array Method 47
What is the .every Method? 47
Example: Checking if All Numbers are Positive 47
How It Works 48
Why Use .every? 48
Practical Example: Validating User Input 48
How It Works 49
Connecting the Dots 49
You’ve Come a Long Way: Let’s Make A Tic-Tac-Toe Game 50
How Other Developers Did It 50
Example 1: A Detailed Solution on GeeksforGeeks 50
Example 2: A Simpler Approach on Medium 51
What These Solutions Have in Common 52
Unlocking the if Statement Superpower 52
Understanding if Statements 52
The Basics of if Statements 52
Example: Checking a Number 52
Why if Statements Are So Powerful 53
Connecting The Dots 53
You’re Ready! 54
Design Thinking 54
We Can Code This! 54
Representing Winning Patterns 55
Example: Vertical Win in the Middle 55
Example: Diagonal Win from Upper-Right to Lower-Left 56
Putting It All Together 57
Remember the for loop? 59
Let's Walk Through the Code Together, Line by Line 61
1. Function Definition 61
2. Define Winning Combinations 61
3. Loop Through Each Winning Combination 62
4. Accessing the Current Combination 62
5. Checking If the Player Occupies All Three Spots 63
6. Return true if a Winning Combination is Found 63
7. End of the Loop and Return `false` 63
8. Example Board State and Function Call 64
Wow! You've Come So Far 64
What You’ve Accomplished 64
Keep Going 65
Homework: Grow Your Superpowers 65
1. Create Your Own Tic-Tac-Toe Board 65
2. Check for a Winner 66
3. Experiment with New Winning Combinations 66
4. Reflection 66
Extra Challenge: Make It Interactive 67
What’s Next? 67
Level 1-1—Unlocking the Power
of Code To Change Your World
Welcome developers to the Code Accelerator Junior Web Developer
Certification kit!
You're in the right place if you've ever felt like the world of coding was a
closed door because of a lack of experience. We're going to help you open
that door!
Everyone Can Code, Including You!
Code Accelerator knows that everyone, from passionate beginners to
seasoned thinkers, can unlock this door—with the right key.
Code touches almost every aspect of our modern lives—from the apps that
wake us up, to the cars that drive us home.
And learning the fundamentals of coding is not just for web developers and
computer scientists anymore; it's for anyone with the curiosity to learn.
That's why no matter who you are or where you've started, we ask you to
build a foundation with us on the basics and fundamentals, as we work our
way up step by step with other developers in the community.
Just like in the movie ‘The Karate Kid’ where simple, everyday actions build
up confidence and power, Code Accelerator’s step by step approach builds
your coding journey one computer science concept at a time using ways of
thinking about things that can be familiar to everyone.
In the Code Accelerator camp, understanding both the front and back end of
applications makes you an active participant, a creator, and an innovator in
the tech space whether you're a back-end web developer, UX designer, team
lead, or startup founder.
You can unlock Code Accelerator certifications only when you're ready to be
prepared to think, to solve problems, and to design solutions.
Code Accelerator helps you learn how to think like a confident coder.
As we move through today's Level 1-1 session, remember that every expert
was once a beginner and every teacher was once a student.
Your journey might have started with a simple line of code, but where it goes
is up to you—and that's limitless.
The Level 1-1 session is an overview of what we’ll study more closely in the
Level 1-2 learning session named “Building Your Programming
Fundamentals with Tic-Tac-Toe”, where we’ll build or rebuild your
fundamental understandings of common computer science concepts like
variables, functions, and data types.
Code Accelerator certification kits are especially designed to teach you the
things you need to learn in the order you need to learn them so that you grow
into a more powerful understanding of web development and web
applications.
Level 1-3’s learning session will take a detour to cover HTML and CSS to
create and style the web pages that will support our web applications.
Having spent the proper time to build up your understanding of the
foundation of our web applications, Level 1-4 unlocks even more of your
JavaScript superpowers, especially handling events and manipulating the
DOM within your HTML structure.
By the end of Level 1-5 (“Understanding Reactive Frameworks”) & Level 1-6
(“Understanding Websockets and Real-Time Connections”) you'll be using
the understanding that you've built up thus far to wrap your mind around how
front-end and back-end tech stacks work together and are used everyday to
fuel the apps that show up in our everyday lives.
There are even more cool things we can learn from there, but before we get
ahead of ourselves, we're going to start today's learning session:
“Unlocking the Power of Code To Change Your World”.
Javascript is everywhere.
As of July 2024, ZipRecruiter lists the average “JavaScript Developer” salary
as $106,583.
This shows just how important Javascript skills are when it comes to
building and maintaining anything that lives on the web.
Support from big companies like Facebook and Google has made
JavaScript the most popular language on the Internet.
Client-side code is just the code that is stored and running right now on your
home computer or in your hand on your mobile device!
Javascript is everywhere in our everyday lives, and that's why every single
internet browser on the planet has a built-in way to process JavaScript!
Browsers use special software called a JavaScript engine to read and use
JavaScript code to power the websites that make our lives easier. There are
different JavaScript engines for every browser; V8 for Chrome, Gecko for
Firefox, and JavaScriptCore for Safari.
V8 (logo left), Gecko (logo center) and JavascriptCore (right) are popular Javascript engines.
The Front-end
JavaScript, CSS (Cascading Style Sheets), and HTML (Hypertext Markup
Language) files are really just text files inside of folders on a computer.
And those code files stack up layer by layer to display everything that you
see in your web app. Everything that appears in a web browser is referred to
as happening on the client side.
Web developers call this client-side mix of Javascript, HTML, and CSS files
the front-end of our web applications.
JavaScript
▲
|
CSS
▲
|
HTML
▲
|
Machine Language (Assembly)
1. HTML rests at the bottom of the stack, creating the basic structure of
our web application.
2. CSS sits on top of the HTML. It adds style to the HTML structure by
adding colors, layouts, and animations that communicate importance
to human users.
The Back-end
From its birth in 1995 up until 2008, JavaScript remained trapped inside the
client-side of the browser.
But in 2009, a software named Node.js was released that broke JavaScript
out from the front-end!
The term server describes computers that run software like Node.js to
communicate with other computers and databases and send .js, .html and
.css files to and from your browser.
The combination of files and folders that sit on servers and make them work
is called the back-end, because these files quietly work in the background
to make our web applications do all the wonderful things they do.
Now that developers like us have access to Node.js, we can use JavaScript
to create both the front-end and the back-end for powerful applications that
live on the World Wide Web.
Developer Tools: IDEs and editors
Integrated development environments like Visual Studio Code are software
applications that help programmers develop code more effectively and
quickly.
Visual Studio Code (logo left) and Notepad++ (logo right) are important tools for any junior web developer.
Lightweight code editors like Notepad++ are simple text editors with less
features than IDEs.
While IDEs are project-focused, lightweight editors are faster for single-file
tasks.
The key is finding the right balance between power and simplicity for efficient
coding.
You'll be using this console to try out small bits of code, called code
snippets. It's great because you can see your code working in real-time
without affecting anything big—just like practicing in a sandbox!
Variables
In Javascript, information is usually held in containers. These data
containers are called variables.
The keywords let and const are part of the syntax that allow us to declare
and initialize a variable.
Keywords are the words in your code that are part of the syntax of the
programming language.
The term “syntax of a programming language” just means the specific things
you must type to correctly communicate with the Javascript engine.
These primitive data types are used to create other data structures in
JavaScript.
An object in JavaScript is just like any object in the real world. It has
properties (attributes or qualities) and actions (functions).
JavaScript
// initialize an array
const myArray = [ "Javascript", "HTML", "CSS"];
// initialize an object
const myEyes = { vision: "20/20" };
// declare a function
function lookAtSomething (subject) {
return subject;
};
For example: my eyes (object) can look at something (function) with 20/20 vision (quality).
And just like in the real world, objects are everywhere in JavaScript, so if
you’ve ever used Javascript you've probably also used objects already.
The properties and methods (variables and functions) that live in an object
should be separated by commas.
JavaScript
// initialize an object
const myEyes = {
vision: "20/20",
lookAtSomething: function (subject) {
return subject;
}
};
// object property
console.log(myEyes.vision) // Output: "20/20"
// object method
console.log(myEyes.lookAtSomething("thing")) // Output: "thing"
Let’s Review!
As we wrap up today’s session, let’s quickly review the key concepts we
covered:
2. The Front-End Stack: You learned about the layers of the front-end
stack—HTML for structure, CSS for styling, and JavaScript for
interactivity.
This foundation sets you up perfectly for our next session, where we’ll dive
deeper into the programming fundamentals that will power your journey
through the world of coding.
Homework #1
Object Creation:
Homework #2
JavaScript
// Example:
let age = 25;
let isAdult = age > 18;
console.log(isAdult); // Output: true
console.log(typeof age); // Output: ??
console.log(typeof isAdult); // Output: ??
let greeting = "Hello";
let to = "World";
let combinedGreeting = greeting + " " + to; console.log(combinedGreeting); //
Output: "Hello World"
Homework #3
Remember, every expert coder started where you are right now—with
curiosity and a willingness to learn. The challenges you face today will
become the building blocks of your success tomorrow.
Your journey in coding is just beginning, and I’m excited to see where it takes
you. The skills you’re developing here can open doors to new opportunities,
so take pride in each step you take. The world of code is vast and full of
possibilities—let’s unlock those possibilities together.
JR. WEB DEVELOPER
CERTIFICATION KIT
Level 1-2: Building Your
Programming Fundamentals
with Tic-Tac-Toe
In this lesson, we will use the Tic-Tac-Toe game to explore fundamental
JavaScript concepts. Through this, we'll not only learn a little about how
writing JavaScript games works, but also deepen our understanding of core
programming principles.
However, like art, coding also requires creativity, intuition, and personal
expression. The beauty of coding lies in its ability to combine elements,
allowing developers to solve problems in unique and innovative ways.
As you progress in your coding journey, remember that your ability to think
creatively and approach problems from different angles is just as valuable as
your technical skills.
Coding is an art, and you are the artist—your creativity and unique
perspective are your superpowers.
More about variables
In Level 1-1, we discussed variables as containers for data and explored the
seven basic data types in JavaScript: strings, numbers, booleans, null,
undefined, symbols, and BigInt.
JavaScript
let myVariable;
myVariable = "Code Accelerator"; // String (text)
myVariable = 2024; // Number
myVariable = BigInt(2^53); // BigInt (for big numbers)
myVariable = true; // Boolean (true or false)
myVariable = Symbol("Code Accelerator"); // Symbol
myVariable = null; // null(empty value)
myVariable = ""; // Undefined (no value yet)
In the last lesson, we talked about how the keyword let can be used to
declare or initialize variables.
JavaScript
// declare a variable named myBootcamp
let myBootcamp;
JavaScript
// initialize a variable named myBootcamp
JavaScript
// declare a variable named myBootcamp
let myBootcamp;
Here, myBootcamp is declared but not yet initialized, meaning it exists in memory but doesn’t hold any value.
JavaScript
// initializing a variable named myBootcamp
myBootcamp = "Code Accelerator";
Now, myBootcamp holds the value "Code Accelerator". We’ve taken our declared variable and given it a purpose.
Declaring and Initializing in One Step
Combined Declaration and Initialization: Oftentimes, you’ll just declare
and initialize a variable in a single step for convenience and clarity.
JavaScript
// declaring AND initializing a variable named myBootcamp
let myBootcamp = "Code Accelerator";
This is a common practice, especially when you already know the value you want the variable to hold.
Understanding const
Introduction to const: While let allows you to declare variables that can be
reassigned later, const is used for variables that should not be reassigned
after their initial value is set. This makes const ideal for values that should
remain constant throughout your code no matter what.
JavaScript
// initializing a constant variable and trying to reassign it
const pi = 3.14159;
pi = 3.14; // Output: TypeError: Assignment to constant variable.
Here, pi is a constant, meaning you cannot reassign pi to another value later in your code. If you try to do so, JavaScript
will throw an error.
JavaScript
// declaring a constant variable without a value
const pi; // Output: SyntaxError: Missing initializer in const declaration
You also can't declare a constant without giving it a value in the declaration.
Use Cases
● Use let when you expect the value of a variable to change over time.
● Use const when you know that a variable’s value should remain
constant and unchanged.
Best Practices
● Use const first. As a best practice, many developers recommend
using const when declaring variables and only using let when you
know the value will need to change.
● Clarity and Intent. Using const by default makes your code clearer
and more readable, as it clearly indicates which variables should
remain unchanged.
In Level 1-2, we’ll explore how these principles apply in practice through our
Tic-Tac-Toe game. You’ll see how careful management of variables can lead
to cleaner, more reliable code, and you’ll gain a deeper appreciation for the
role of variables in programming.
Next up, we’ll dig into the concept of hoisting, which is closely related to how
variables are declared and initialized. Understanding hoisting will give you
further understanding of how JavaScript handles your code under the hood.
Introduction to var
In early versions of JavaScript, the only way to declare variables was by
using the var keyword.
But var behaves differently from let and const in ways that can be confusing,
especially for beginners.
● If you create the variable outside of any function, it’s said to be in the
global scope. This means it can be used anywhere in your entire
program. Think of it as being available to everyone, everywhere.
● If you create the variable inside a function, it’s in the function scope.
This means it can only be used within that specific function. Imagine it
as a special tool that only works inside one room (the function) and
can't be taken outside.
Unlike let and const, which are block-scoped (they only work within blocks
which are smaller sections of your code, like loops or if statements), var is
more flexible—it works throughout the entire function or your entire program
(depending on where you declare it).
● Why Is This Useful? This rule helps prevent mistakes. It stops you
from accidentally overwriting a variable that you’ve already created,
which can make your code more reliable and easier to understand.
JavaScript
let myVariable = "Code Accelerator";
let myVariable = "New"; // SyntaxError: Identifier 'myVariable' has already been
declared
Unlike var, which allows you to create (or redeclare) the same variable name
multiple times in the same scope (which can lead to confusion and bugs), let
is stricter.
That’s why using let and const helps you keep your variables organized and
avoids unintended bugs.
Understanding Hoisting (Moving Variables
To The Top of the Scope)
In JavaScript, there's a behind-the-scenes behavior called hoisting that
affects how your code runs.
Imagine that JavaScript reads through your code before it actually runs it.
During this reading process, it finds all the places where you declare
variables and functions, and it moves those declarations to the top of their
scope or section of code (like to the top of a function or your entire program).
This doesn’t change the order of your code, but it does change when
JavaScript becomes aware of your variables and functions.
How This Affects var. With var, this means you can use a variable before it’s
actually declared in your code. However, because only the declaration is
moved to the top, not the assignment, the variable won’t have its value yet.
The variable will read as undefined until we get to the line where you actually
assigned it a value.
JavaScript
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
In this example, even though var x = 5; appears after the first console.log(x);, JavaScript knows about` `x when the code
runs because it moved the declaration to the top. But since the value assignment happens later, x is undefined at first.
var As we mentioned, var lets you use a variable before it’s declared in your
code because JavaScript moves the declaration to the top. However, since
only the declaration gets moved and not the assignment, the variable will be
undefined until you actually give it a value.
JavaScript
// JavaScript moves the declaration here: var x;
console.log(x); // Output: undefined
var x = 5; // behaves like a redeclaration
console.log(x); // Output: 5
let and const: When let and const are also hoisted, they behave differently.
Even though their declarations are also moved to the top, you can’t use
these variables until the code actually reaches the line where they are
declared. This creates what’s called a temporal dead zone—a fancy way of
saying you can’t use the variable before it’s properly declared.
JavaScript
console.log(y); // Error: Cannot access 'y' before initialization
let y = 10;
console.log(y); // Output: 10
console.log(z); // Error: Cannot access 'z' before initialization
const z = 20;
console.log(z); // Output: 20
● Only use let when you expect the value of a variable to change over
time.
let and const help prevent mistakes by making sure the code can’t use the
variable until it’s actually declared in the code.
Using let and const is safer and helps you write more reliable code because
you can be sure that the variable has been properly set up before your code
tries to use it.
Imagine you’re in the kitchen, and you want to make a sandwich. You can
think of a function as a set of instructions for making that sandwich. Instead
of giving each instruction every time you want to make a sandwich, you can
create a function that performs all the steps for you.
Defining Functions
Here is the format you use to write any function:
JavaScript
function functionName(parameter1, parameter2, parameter3) {
return parameter1 + parameter2;
}
The makeSandwich function combines the bread and filling and then
returns a string data type telling you what kind of sandwich you made.
Using the makeSandwich Function
Now, whenever you want to make a sandwich, you just call the function and
give it the ingredients:
JavaScript
let myLunch = makeSandwich("whole wheat", "turkey");
This is much easier than writing out all those steps every time we want to
describe the process of making a sandwich!
Functions are also great for performing calculations. Let’s say you need to
calculate the area of a rectangle in different situations. Instead of writing the
formula over and over, you can create a function to do it.
JavaScript
function calculateArea(length, width) {
return length * width;
}
● Parameters: length and width are the inputs you need to perform the
calculation.
● Return Value: The function multiplies the length by the width and
returns the area.
JavaScript
let area = calculateArea(5, 3);
console.log(area); // Output: 15
This function makes your code shorter, clearer, and easier to update if you
need to change the way you calculate the area.
● Return Value: While console.log doesn’t return a value that you can
use later, it performs an action—outputting text to the console.
JavaScript
console.log("Hello, world!"); // Output: ??
● "Hello, world!": The parameter that gets passed into the function.
Functions like console.log are incredibly powerful because they let you
reuse the same code with different inputs, making your code more efficient
and easier to manage.
JavaScript
console.log(makeCoffee()); // Output: "Your coffee is ready!"
function makeCoffee() {
return "Your coffee is ready!";
}
How It Works: Even though the console.log comes before the makeCoffee
function in the code, JavaScript “hoists” the function declaration to the top.
So, when the code runs, JavaScript already knows about the makeCoffee
function, and everything works fine.
JavaScript
function calculateDiscount(price) {
let discount = 0.1; // 10% discount
return price - (price * discount);
}
console.log(calculateDiscount(100)); // Output: 90
console.log(discount); // Error: discount is not defined
How It Works:
Think of an array like a bookshelf, where each book (or item) has its own
specific spot on the shelf.
Arrays are one of the most basic tools you'll use in JavaScript, but they are
also incredibly powerful.
They help you keep your data organized, make your code more efficient, and
allow you to do more with less effort. Understanding how to use arrays is a
JavaScript superpower that you’re going to want to unlock.
Arrays keep everything in a specific order.
Imagine you have a list of your favorite fruits or a list of scores from a game.
Instead of writing down each fruit or score separately, you can put them all
together in an array.
Each item in an array has a number, called an index, which tells you its
position in the list.
● Access Items Quickly: By using the index number, you can easily
find or change any item in the list.
● Loop Through Items: If you want to do something with each item (like
printing them out or adding them up), arrays let you go through the list
automatically.
JavaScript
let fruits = ["apple", "banana", "cherry"];
In this array:
Loops
Arrays are used with loops to perform the same operation on each element
(the term “element” is the developer term for any item in an array).
Let’s say you want to print out every element in the fruits variable.
Using a for Loop
Here’s an example to make it clearer:
JavaScript
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
/*
Output:
apple
banana
cherry
*/
The loop kicks off with i starting at 0. It keeps going as long as i is less than
the total length of the fruits array (which has 3 items in it).
Each time the loop runs (and it runs three times in this case), fruits[i] grabs
the fruit at the current spot in the list, and console.log(fruits[i]) prints that fruit
to the console for you to see.
So, as i goes from 0 to 2, the loop prints each fruit in the order they appear in
the array.
On the fourth turn, i becomes 3, which is equal to the length of the array.
At this point, the loop checks the condition (i < fruits.length), sees that it’s no
longer true, and stops running.
That’s why the loop only prints three fruits—one for each time it runs.
Introduction to Comparison
In coding, comparing values is an important concept that helps your code
make decisions.
It’s like asking your program a question: "Is this value smaller than that one?"
or "Are these two things the same?" These comparisons guide your code to
take different actions based on the answers.
One of the simplest and most straightforward comparisons is the < or less
than operator.
This operator is like asking your code, "Is this value smaller than that one?"
It’s a crucial part of how your code makes decisions and controls what
happens next.
You’ve already seen this operator in action when we used it in our for loop.
Let’s take a moment to see how it works and why it’s so important.
JavaScript
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
● Why It Matters. This comparison keeps the loop running the right
number of times. As long as i is less than the length of the fruits, the
loop continues. Once i reaches the array’s length, the loop stops,
making sure we don’t try to access items that aren’t there.
It helps guide your loops, ensuring they do exactly what you need without
going too far.
In our for loop, this simple comparison made sure we processed every fruit
in the array, one by one, and then stopped when we were done.
In JavaScript, there are two ways to compare for equality: loose equality
(==) and strict equality (===). Each one has its own special way of
working, depending on how precise you want to be.
JavaScript
console.log(5 === "5"); // Output: false
Why It Matters
Understanding these different types of comparisons helps you write code
that does exactly what you expect. Just like the < operator helps you figure
out differences in value, equality operators help you check if values match
up the way you want them to.
Practical Example: Checking User Input
Imagine you’re building a simple login system. You want to check if the
user’s input matches the correct password.
Loose Equality:
JavaScript
let correctPassword = "1234";
let userInput = 1234;
Even though the user entered a number and the password is stored as a string, loose equality says they match
because JavaScript converts the number to a string data type.
Strict Equality:
JavaScript
let correctPassword = "1234";
let userInput = 1234;
Strict equality, however, sees that one is a string and the other is a number, so it says they don’t match.
While loose equality can be handy in some situations, it’s often better to use
strict equality to avoid unexpected results. By being clear about what you’re
comparing, you’ll make your code more predictable and easier to debug.
Remember, in most cases, it’s safer to use === to make sure that both the
value and the type match exactly.
Bringing It All Together: The .every Array
Method
Now that you have a solid understanding of loops, comparisons, and arrays,
it’s time to bring these concepts together by exploring a powerful tool in
JavaScript: the .every array method.
This method allows you to check if every item in an array meets a certain
condition, making your code more efficient and easier to read.
Let’s say you have an array of numbers, and you want to check if every
number in the array is positive.
JavaScript
let numbers = [1, 2, 3, 4, 5];
JavaScript
let numbers = [1, 2, 3, -4, 5];
How It Works
● The Array: We start with an array of numbers: [1, 2, 3, 4, 5].
● The .every Method: We use the .every method to check if every
number in the array is greater than 0.
● The Function: Inside .every, we define a function that takes each
number and checks if it’s greater than 0. If all numbers pass this test,
.every returns true; if any number fails, it returns false.
Imagine you’re writing a program that checks if every input in a form is filled
out correctly. You can use .every to make sure every field in an array of form
inputs is not empty.
JavaScript
let formInputs = ["Code", "Accelerator", "[email protected]"];
How It Works
● We have an array of form inputs (e.g., a first name, last name, and
email).
● The .every method checks if every input is not an empty string.
● If all inputs are filled out, .every returns true; otherwise, it returns false.
The .every method is a function that we can use on arrays that combines all
of these skills into one powerful tool that simplifies your code and makes it
more readable.
You’ve been building your skills step by step, and now we’re ready to use
everything we’ve learned to tackle a fun challenge: coding a tic-tac-toe
game. So far:
● Arrays: You’ve learned how to organize data in lists, and how to use
an array to represent something.
● Loops: You know how to go through each item in an array, making
sure nothing gets missed.
● Comparisons: You can check if values are what you expect, and use
those checks to decide what your code should do next.
JavaScript
function myfunc_4() {
if (flag == 1) {
document.getElementById("b2").value = "X";
document.getElementById("b2").disabled = true;
flag = 0;
}
else {
document.getElementById("b2").value = "0";
document.getElementById("b2").disabled = true;
flag = 1;
}
}
You can check out the full solution here: GeeksforGeeks Tic-Tac-Toe Game
JavaScript
function checkTie(){
for(let i = 0; i < squares.length; i++) {
if(squares[i].textContent === '') {
return false;
}
}
return true;
}
You can read her full tutorial here: Medium Tic-Tac-Toe Tutorial
What These Solutions Have in Common
If you explore these tutorials, you’ll notice that while these developers took
very different approaches, there’s something they both have in common:
they use a JavaScript control structure called the if statement.
Understanding if Statements
The if statement is one of the most important tools in your programming
toolbox. It allows your code to make decisions, which is key to building
anything interactive, like a game or a dynamic website.
With if statements, you can tell your program, "If this condition is true, then
do this. Otherwise, do something else."
● We’ve got a number, 10, and we want to check if it’s greater than 5.
● The if statement checks this condition: number > 5.
● Since 10 is indeed greater than 5, the code inside the if block runs, and
you see the message "The number is greater than 5" printed to the
console.
You’re Ready!
Now that we’ve discussed if statements, loops, comparisons, and arrays,
you’ve got all the tools you need to understand the first version of our
Tic-Tac-Toe coding challenge solution. Let’s bring everything together by
thinking through the problem with a bit of design thinking.
Design Thinking
Let’s start by reviewing what we know about Tic-Tac-Toe:
We know that there are nine cells where players can place their marks, so
let’s represent the Tic-Tac-Toe board using an array with nine elements:
JavaScript
let board = [null, null, null, null, null, null, null, null, null];
Each element in this array lines up to a cell on the board, with the first
element (board[0]) representing the top-left corner and the last element
(board[8]) representing the bottom-right corner.
One way to win is by having three marks in a column. For example, if a player
places their marks in the middle column:
They would occupy the cells with indexes 1, 4, and 7:
JavaScript
// Middle column winning combination
[1, 4, 7]
JavaScript
// Diagonal winning combination from upper-right to lower-left
[2, 4, 6]
Now, we can define all winning combinations by listing the indexes that need
to be occupied by the same player’s mark:
JavaScript
const allWinningCombinations = [
[0, 1, 2], // Top row
[3, 4, 5], // Middle row
[6, 7, 8], // Bottom row
[0, 3, 6], // Left column
[1, 4, 7], // Middle column
[2, 5, 8], // Right column
[0, 4, 8], // Diagonal from top-left to bottom-right
[2, 4, 6] // Diagonal from top-right to bottom-left
];
The cool thing about design thinking is that you can solve a lot of coding
problems in your mind before you start coding.
Now that we know all of the winning combinations, we can design the code
that we use to check for a win.
First, we’ll set up a board that has a winning combination. Let’s set up a
board where Player O wins diagonally:
JavaScript
let board = [null, null, null, null, null, null, null, null, null];
board = [
null, 'X', 'O',
'X', 'O', null,
'O', 'X', null
];
Remember the for loop?
With all the pieces in place, we can now use a for loop to go through each of
the winning combinations and check if any of them match the current board
state. This is where everything you’ve learned about loops and comparisons
comes together to complete the Tic-Tac-Toe solution!
JavaScript
function checkForWin(player) {
const allWinningCombinations = [
[0, 1, 2], // Top row
[3, 4, 5], // Middle row
[6, 7, 8], // Bottom row
[0, 3, 6], // Left column
[1, 4, 7], // Middle column
[2, 5, 8], // Right column
[0, 4, 8], // Diagonal from top-left to bottom-right
[2, 4, 6] // Diagonal from top-right to bottom-left
];
// Check if the player occupies all three spots in the current winning combination
if (board[a] === player && board[b] === player && board[c] === player) {
return true; // Player O has a winning combination
}
}
1. Function Definition
JavaScript
function checkForWin(player) {
What’s Happening?: We’re creating a list (an array) of all possible winning
combinations on the Tic-Tac-Toe board. Each combination is represented
by a smaller array of three numbers, where each number corresponds to a
position on the board. For example, [0, 1, 2] represents the top row.
What’s Happening?: We start a for loop that will go through each winning
combination one by one. The loop will run as many times as there are
winning combinations, which is 8 in this case. The variable i will keep track of
which combination we’re currently checking.
4. Accessing the Current Combination
JavaScript
const combination = allWinningCombinations[i];
const a = combination[0];
const b = combination[1];
const c = combination[2];
What’s Happening?:
What’s Happening?: If the loop finishes checking all the combinations and
doesn’t find a winning one, we return `false`, meaning there is no winner yet.
if (checkForWin('O')) {
console.log("Player O wins!");
} else {
console.log("No winner yet.");
}
What’s Happening?: We set up a sample board where Player O has a
diagonal win, then we call checkForWin('O') to see if Player O has won.
Depending on the result, we print either "Player O wins!" or "No winner yet."
Made Decisions with `if` Statements: You’ve seen how `if` statements help
your code make decisions, checking conditions and responding accordingly.
Keep Going
Coding is a journey, and you’re on a great path. Keep challenging yourself
with new projects, explore different ways to solve problems, and most
importantly, have fun with it! Every line of code you write is another step
forward in your journey to becoming a confident and skilled developer.
You’ve come so far, and there’s so much more you can achieve. Keep up the
amazing work, and remember—there’s no limit to what you can create with
code!
Homework: Grow Your Superpowers
Now that you’ve made incredible progress, it’s time to put your knowledge to
the test with some hands-on practice. This homework will help you reinforce
what you’ve learned and give you the confidence to tackle coding challenges
on your own.
Goal: The program should display the board in the console after each move,
showing the current state of the game.
Hint: Use a loop to keep the game going until all spots are filled or a player
wins.
Goal: Your program should announce the winner or declare a tie if all spots
are filled and no one has won.
Hint: Remember the winning combinations and use a loop to check each
one.
Task: Modify the game to allow a larger board, like a 4x4 grid. Adjust your
checkForWin function to find winning combinations on this bigger board.
Goal: The game should still correctly identify winners, even with the new
board size.
Hint: You’ll need to add more winning combinations to your list and think
about how to check them.
4. Reflection
Goal: This reflection will help you identify your strengths and areas where
you might want to focus more attention.
Extra Challenge: Make It Interactive
What’s Next?
Now that you’ve got the basics down, the sky’s the limit. Whether you’re
looking to build more games, create interactive web pages, or solve complex
coding challenges, you have the tools you need to get started. Remember,
every coder, no matter how advanced, started where you are now—with the
basics. The more you practice, the more these concepts will become
second nature, and the more creative and powerful your coding will become.
In the next learning session we’re going to pivot to talking about HTML, CSS,
and how we can add user input to the Tic-Tac-Toe game we’re building.