JavaScript is the programming language that powers the web. Unlike the HTML and CSS you have learned previously, JavaScript is most commonly used to write logic instead of markup.
In this project, you will learn the basics of Javascript and apply those concepts to building a pyramid generator.
A pyramid generator is a program where you can set the type of character, the count for the pyramid, and the direction of the pyramid. The program will then generate a pyramid based on those inputs.
Click on the "Check your code"
button to proceed to the next step and start the project.
JavaScript is the programming language that powers the web. Unlike the HTML and CSS you have learned previously, JavaScript is most commonly used to write logic instead of markup.
One of the most important concepts in programming is variables. A variable points to a specific memory address that stores a value. Variables are given a name which can be used throughout your code to access that value.
Declaring a variable means giving it a name. In JavaScript, this is often done with the let
keyword. For example, here is how you would declare a hello
variable:
let hello;
Variable naming follows specific rules: names can include letters, numbers, dollar signs, and underscores, but cannot contain spaces and must not begin with a number.
Note: It is common practice to end statements in JavaScript with a semicolon. ;
You can assign a value using the assignment operator =
. For example:
let hello = "Hello";
Assigning a value to a variable at the moment of its declaration is known as initialization.
JavaScript has seven primitive data types, with String
being one of them. In JavaScript, a string represents a sequence of characters and can be enclosed in either single ('
) or double ("
) quotes.
Note that strings are immutable, which means once they are created, they cannot be changed. The variable can still be reassigned another value.
The console allows you to print and view JavaScript output. You can send information to the console using console.log()
. For example, this code will print "Naomi"
to the console:
let developer = "Naomi";
console.log(developer);
The code above accesses the developer
variable with its name in the console.log()
. Note that the value between the parentheses is the value that will be printed.
When a variable is declared with the let
keyword, you can reassign (or change the value of) that variable later on. In this example, the value of programmer
is changed from "Naomi"
to "CamperChan"
.
let programmer = "Naomi";
programmer = "CamperChan";
Note that when reassigning a variable, you do not use the let
keyword again.
When variable names are more than one word, there are specific naming conventions for how you capitalize the words. In JavaScript, the convention to use is camel case.
Camel case means that the first word in the name is entirely lowercase, but the following words are all title-cased. Here are some examples of camel case:
let variableOne;
let secondVariable;
let yetAnotherVariable;
let thisIsAnAbsurdlyLongName;
When you declare a variable without initializing it, it is considered uninitialized.
The default value of an uninitialized variable is undefined
. This is a special data type that represents a value that does not have a definition yet.
You can still assign a value to an uninitialized variable. Here is an example:
let uninitialized;
uninitialized = "assigned";
You can also assign the value of a variable to another variable. For example:
let first = "One";
let second = "Two";
second = first;
The second
variable would now have the value "One"
.
You can access the values inside an array using the index of the value. An index is a number representing the position of the value in the array, starting from 0
for the first value.
You can access the value using bracket notation, such as array[0]
.
Notice how the value inside your rows
array has been changed directly? This is called mutation. As you learn more about arrays, you will learn when to mutate an array, and when you should not.
Before moving on, this is a great opportunity to learn a common array use. Currently, your code accesses the last element in the array with rows[2]
. But you may not know how many elements are in an array when you want the last one.
You can make use of the .length
property of an array - this returns the number of elements in the array. To get the last element of any array, you can use the following syntax:
array[array.length - 1]
array.length
returns the number of elements in the array. By subtracting 1
, you get the index of the last element in the array. You can apply this same concept to your rows
array.
A method in JavaScript is a function that's associated with certain values or objects. An example you've already encountered is the .log()
method, which is part of the console
object.
Arrays have their own methods, and the first you will explore is the .push()
method. This allows you to "push" a value to the end of an array. Here is an example to add the number 12
to the end of an array:
array.push(12);
Another method essential for this project is the .pop()
method. It removes the last element from an array and returns that element.
When a method returns a value, you can think of it as giving the value back to you, making it available for use in other parts of your code.
Create a new variable called popped
and assign it the result of rows.pop()
. Then, log popped
to the console.
Were you expecting to see 4
in the console? .push()
returns the new length of the array, after adding the value you give it.
It is important to be aware of what values a method returns. Take some time to experiment with .push()
and .pop()
. When you are ready, remove all of your .push()
and .pop()
calls, and your console.log
statements.
To generate a pyramid, you will need to create multiple rows. When you have to perform a task repeatedly until a condition is met, you will use a loop. There are many ways to write a loop.
You are going to start with a basic for
loop. for
loops use the following syntax:
for (iterator; condition; iteration) {
logic;
}
In the upcoming steps, you'll explore each component of a loop in detail. For now, construct a for
loop that includes the terms "iterator"
, "condition"
, and "iteration"
for the three components. Keep the loop body, the section within the curly braces {}
, empty.
Your loop now needs a proper iterator. The iterator is a variable you can declare specifically in your for
loop to control how the loop iterates or goes through your logic.
It is a common convention to use i
as your iterator variable in a loop. A for
loop allows you to declare this in the parentheses ()
. For example, here is a for
loop that declares an index
variable and assigns it the value 100
.
for (let index = 100; "second"; "third") {
}
Replace the string "iterator"
with a let
declaration for the variable i
. Assign it the value 0
to start. This will give the i
variable the value 0
the first time your loop runs.
The condition of a for
loop tells the loop how many times it should iterate. When the condition
becomes false, the loop will stop.
In JavaScript, a Boolean value can be either true
or false
. These are not strings - you will learn more about the difference later on.
For now, you will use the less than operator (<
). This allows you to check if the value on the left is less than the value on the right. For example, count < 3
would evaluate to true
if count
is 2
, and false
if count
is 4
.
Replace your "condition"
string with a condition to check if i
is less than count
.
Your iteration statement will tell your loop what to do with the iterator after each run.
When you reassign a variable, you can use the variable to reference the previous value before the reassignment. This allows you to do things like add three to an existing number. For example, bees = bees + 3;
would increase the value of bees
by three.
Use that syntax to replace your "iteration"
string with a reassignment statement that increases i
by one.
Now all of your numbers are appearing on the same line. This will not work for creating a pyramid.
You will need to add a new line to each row. However, pressing the return key to insert a line break between quotes in JavaScript will result in a parsing error. Instead, you need to use the special escape sequence \n
, which is interpreted as a new line when the string is logged. For example:
lineOne = lineOne + "\n" + lineTwo;
You're getting closer! At this point, you're encountering what's known as an off-by-one error, a frequent problem in zero-based indexing languages like JavaScript.
The first index of your rows
array is 0
, which is why you start your for
loop with i = 0
. But repeating a string zero times results in nothing to print.
A function is a block of code that can be reused throughout your application. Functions are declared with the following syntax:
function name(parameter) {
}
The function
keyword tells JavaScript that the name
variable is going to be a function. parameter
is a variable that represents a value that is passed into the function when it is used. A function may have as many, or as few, parameters as you'd like. Like a for
loop, the space between the curly braces is the function body.
In order to use a function, you need to call it. A function call tells your application to run the code from the function wherever you choose to call it. The syntax for a function call is the function name followed by parentheses. For example, this code defines and calls a test
function.
function test() {
}
test();
By default, functions return undefined
as their value.
In order to return something else, you need to use the return
keyword. Here is an example of a function that returns the string "Functions are cool!"
:
function demo() {
return "Functions are cool!";
}
When you have a value that is explicitly written in your code, like the "Hello!"
string in your function, it is considered to be hard-coded. Hard-coding a value inside a function might not make it as reusable as you'd like.
Instead, you can define parameters for the function. Parameters are special variables that are given a value when you call the function, and can be used in your function to dynamically change the result of the function's code.
To add a parameter to your function, you need to add a variable name inside the parentheses. For example, this demo
function has a name
parameter:
function demo(name) {
}
A function does not have to return a hard-coded value. It can return the value stored in a variable. Parameters are special variables for a function, so they can also be returned.
When you pass a value to a function call, that value is referred to as an argument. Here is an example of calling a demo
function and passing "Naomi"
as the argument for the name
parameter.
function demo(name) {
return name;
}
demo("Naomi");
Variables in JavaScript are available in a specific scope. In other words, where a variable is declared determines where in your code it can be used.
The first scope is the global scope. Variables that are declared outside of any "block" like a function or for
loop are in the global scope.
When a variable is in the global scope, a function can access it in its definition. Here is an example of a function using a global title
variable:
const title = "Professor ";
function demo(name) {
return title + name;
}
demo("Naomi")
This example would return "Professor Naomi"
.
Variables can also be declared inside a function. These variables are considered to be in the local scope, or block scope. A variable declared inside a function can only be used inside that function. If you try to access it outside of the function, you get a reference error.
Values returned out of a function are used by calling the function. You can use the function call directly as the value it returns, or capture the returned value in a variable. This way, you can use the value assigned to a locally scoped variable, outside the function it was created in.
function getName() {
const name = "Camper cat";
return name;
}
console.log(getName()); // "Camper cat"
const capturedReturnValue = getName();
console.log(capturedReturnValue); // "Camper cat"
console.log(name); // reference error
An important thing to know about the return
keyword is that it does not just define a value to be returned from your function, it also stops the execution of your code inside a function or a block statement. This means any code after a return
statement will not run.
A function call allows you to actually use a function. You may not have been aware of it, but the methods like .push()
that you have been using have been function calls.
A function is called by referencing the function's name, and adding ()
. Here's how to call a test
function:
test();
Functions has parameters which you define. Values are provided to those parameters when a function is called.
The values you provide to a function call are referred to as arguments, and you pass arguments to a function call. Here's a function call with "Hello"
passed as an argument:
test("Hello");
You can pass full expressions as an argument. The function will receive the result of evaluating that expression. For example, these two function calls would yield the same result:
test(2 * 3 + 1);
test(7);
The addition operator is not the only way to add values to a variable. The addition assignment operator can be used as shorthand to mean "take the original value of the variable, add this value, and assign the result back to the variable." For example, these two statements would yield the same result:
test = test + 1;
test += 1;
increment operator ++
. This operator increases the value of a variable by 1, updating the assignment for that variable. For example, test
would become 8
here:
let test = 7;
test++;
An if
statement allows you to run a block of code only when a condition is met. They use the following syntax:
if (condition) {
logic
}
Create an if
statement with the boolean true
as the condition. In the body, print the string "Condition is true"
.
A truthy value is a value that is considered true when evaluated as a boolean. Most of the values you encounter in JavaScript will be truthy.
A falsy value is the opposite - a value considered false when evaluated as a boolean. JavaScript has a defined list of falsy values. Some of them include false
, 0
, ""
, null
, undefined
, and NaN
.
Try changing your if
condition to an empty string ""
, which is a falsy value.
In addition to if
statements, JavaScript also has else if statements. else if
statements allow you to check multiple conditions in a single block of code.
Here is the syntax for an else if
statement:
if (condition1) {
// code to run if condition1 is true
} else if (condition2) {
// code to run if condition2 is true
} else if (condition3) {
// code to run if condition3 is true
}
If the first condition is false
, JavaScript will check the next condition in the chain. If the second condition is false
, JavaScript will check the third condition, and so on.
Below your if
statement, add an else if
statement that checks if 5
is less than 10
. Then inside the body of the else if
statement, log the string "5 is less than 10"
to the console.
Check the console to see the results.
Sometimes you will want to run different code when all of the if...else if
conditions are false
. You can do this by adding an else
block.
An else
block will only evaluate if the conditions in the if
and else if
blocks are not met.
Here the else
block is added to the else if
block.
if (condition) {
// this code will run if condition is true
} else if (condition2) {
// this code will run if the first condition is false
} else {
// this code will run
// if the first and second conditions are false
}
Add an else
block to the else if
block. Inside the else
block, log the string "This is the else block"
to the console.
To see the results in the console, you can manually change the <
in the else if
statement to >
. That will make the condition false
and the else
block will run.
A while
loop will run over and over again until the condition
specified is no longer true. It has the following syntax:
while (condition) {
logic;
}
The equality operator ==
is used to check if two values are equal. To compare two values, you'd use a statement like value == 8
.
The equality operator can lead to some strange behavior in JavaScript. For example, "0" == 0
is true, even though one is a string and one is a number.
The strict equality operator ===
is used to check if two values are equal and share the same type. As a general rule, this is the equality operator you should always use. With the strict equality operator, "0" === 0
becomes false, because while they might have the same value of zero, they are not of the same type.
The strict inequality operator !==
allows you to check if two values are not equal, or do not have the same type. The syntax is similar to the equality operator: value !== 4
.
Arrays have a special length
property that allows you to see how many values, or elements, are in the array. You would access this property using syntax like myArray.length
.
Just like addition, there are different operators you can use for subtraction. The subtraction assignment operator -=
subtracts the given value from the current variable value, then assigns the result back to the variable.
The .unshift()
method of an array allows you to add a value to the beginning of the array, unlike .push()
which adds the value at the end of the array. Here is an example:
const numbers = [1, 2, 3];
numbers.unshift(5);
The numbers
array would now be [5, 1, 2, 3]
.
Use const
to declare an unshifted
variable, and assign it the result of calling .unshift()
on your numbers
array. Pass 5
as the argument. Then print your unshifted
variable.
Notice that like .push()
, .unshift()
returns the new length of the array after the element is added.
Arrays also have a .shift()
method. This will remove the first element of the array, unlike .pop()
which removes the last element. Here is an example of the .shift()
method:
const numbers = [1, 2, 3];
numbers.shift();
The numbers
array would be [2, 3]
.
Directly below your numbers
array, declare a shifted
variable and assign it the result of calling .shift()
on the numbers
array. On the next line, log the shifted
variable to the console.