0% found this document useful (0 votes)
54 views12 pages

Javascript Note

Uploaded by

larrycompany19
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
54 views12 pages

Javascript Note

Uploaded by

larrycompany19
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 12

JAVASCRIPT

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....

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.

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.

Before you can begin to build out your locations array, you will first need to
learn about objects. Objects are an important data type in JavaScript. The next few
steps will be dedicated to learning about them so you will better understand how to
apply them in your project.

Objects are non primitive data types that store key-value pairs. Non primitive data
types are mutable data types that are not undefined, null, boolean, number, string,
or symbol. Mutable means that the data can be changed after it is created.

Here is the basic syntax for an object:

Example Code
{
key: value
}

If the property name (key) of an object has a space in it, you will need to use
single or double quotes around the name.

Here is an example of an object with a property name that has a space:


Example Code
const spaceObj = {
"Space Name": "Kirk",
};
If you tried to write a key without the quotes, it would throw an error:

Example Code
const spaceObj = {
// Throws an error
Space Name: "Kirk",
};

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".

Example Code
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:

Example Code
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:

Example Code
let uninitialized;
uninitialized = "assigned";

You can also assign the value of a variable to another variable. For example:

Example Code
let first = "One";
let second = "Two";
second = first;
The second variable would now have the value "One".
Use let to declare a count variable. Assign it the number 8. When using a number
value, you do not use quotes. For example:

Example Code
let money = 100;

With the number data type, you can perform mathematical operations, like addition.
Try printing count + 1 to the console
You can also perform subtraction (-), multiplication (*), and division (/)

In programming, you will often need to work with lots of data. There are many data
structures that can help you organize and manage your data. One of the most basic
data structures is an array.

An array is a non-primitive data type that can hold a series of values. Non-
primitive data types differ from primitive data types in that they can hold more
complex data. Primitive data types like strings and numbers can only hold one value
at a time.

Arrays are denoted using square brackets ([]). Here is an example of a variable
with the value of an empty array:

Example Code
let array = [];

When an array holds values, or elements, those values are separated by commas. Here
is an array that holds two strings:

Example Code
let array = ["first", "second"];
The order of values in an array is important, so follow that order. Remember that
strings are case-sensitive.

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].

Arrays are special in that they are considered mutable. This means you can change
the value at an index directly.

For example, this code would assign the number 25 to the second element in the
array:

Example Code
let array = [1, 2, 3];
array[1] = 25;
console.log(array); // prints [1, 25, 3]

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:

Example Code
array[array.length - 1]

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:

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.

Example Code
array.push(12);

Declaring a variable with the let keyword allows it to be reassigned. This means
you could change character later to be a completely different value.

For this project, you will not want to change these variable values. So instead,
you should use const to declare them. const variables are special.

First, a const variable cannot be reassigned like a let variable. This code would
throw an error:

Example Code
const firstName = "Naomi";
firstName = "Jessica";
A const variable also cannot be uninitialized. This code would throw an error:

JavaScript interacts with the HTML using the Document Object Model, or DOM. The DOM
is a tree of objects that represents the HTML. You can access the HTML using the
document object, which represents your entire HTML document.
One method for finding specific elements in your HTML is using the querySelector()
method. The querySelector() method takes a CSS selector as an argument and returns
the first element that matches that selector. For example, to find the <h1> element
in your HTML, you would write:

Example Code
let h1 = document.querySelector("h1");

button1 represents your first button element. These elements have a special
property called onclick, which you can use to determine what happens when someone
clicks that button.

You can access properties in JavaScript a couple of different ways. The first is
with dot notation. Here is an example of using dot notation to set the onclick
property of a button to a function reference.

Example Code
button.onclick = myFunction;
In this example, button is the button element, and myFunction is a reference to a
function. When the button is clicked, myFunction will be called.

The innerText property controls the text that appears in an HTML element. For
example:

Example Code
<p id="info">Demo content</p>
Example Code
const info = document.querySelector("#info");
info.innerText = "Hello World";
The following example would change the text of the p element from Demo content to
Hello World.

Example Code
const firstName;

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:

Example Code
for (iterator; condition; iteration) {
logic;
}
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.

Example Code
for (let index = 100; "second"; "third") {

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.

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.

To manipulate the result string, you will use a different type of loop.
Specifically, a for...of loop, which iterates over each item in an iterable object
and temporarily assigns it to a variable.

The syntax for a for...of loop looks like:

Example Code
for (const value of iterable) {

Remember in your previous loop that you used the addition operator + to increase
the value of i by 1.

You can do a similar thing with a string value, by appending a new string to an
existing string. For example, hello = hello + " World"; would add the string "
World" to the existing string stored in the hello variable. This is called
concatenation.

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:

Example Code
lineOne = lineOne + "\n" + lineTwo;

The logic for formatting this pyramid is likely going to get complicated, which
means it's a great time to extract that code into a function.

A function is a block of code that can be reused throughout your application.


Functions are declared with the following syntax:

Example Code
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.

Example Code
function test() {

}
test();

Your call variable has an undefined value, even though you defined it! This is
because your padRow function does not currently return a value. 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!":

Example Code
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:

Example Code
function demo(name) {

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.

Example Code
function demo(name) {
return name;
}
demo("Naomi");

Passed
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. Your character, count,
and rows variables are all 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:

Example Code
const title = "Professor ";
function demo(name) {
return title + name;
}
demo("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.

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:

Example Code
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:

Example Code
test = test + 1;
test += 1;

Because you are only increasing i by 1, you can use the 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:

Example Code
let test = 7;
test++;

Comments can be helpful for explaining why your code takes a certain approach, or
leaving to-do notes for your future self.

In JavaScript, you can use // to leave a single-line comment in your code.

JavaScript also has support for multi-line comments. A multi-line comment starts
with /* and ends with */.

Unlike a single-line comment, a multi-line comment will encapsulate multiple lines.

An if statement allows you to run a block of code only when a condition is met.
They use the following syntax:

Example Code
if (condition) {
logic
}

The text has appeared again! This is because "false" is a string, which when
evaluated to a boolean becomes true. This means "false" is a truthy value.

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.

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:

Example Code
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

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.

Example Code

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
}

A while loop will run over and over again until the condition specified is no
longer true. It has the following syntax:

Example Code
while (condition) {
logic;
Right now, if you change continueLoop to true, your while loop will run forever.
This is called an infinite loop, and you should be careful to avoid these. An
infinite loop can lock up your system, requiring a full restart to escape

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. .unshift()
returns the new length of the array it was called on.

Example Code
const countDown = [2, 1, 0];
const newLength = countDown.unshift(3);
console.log(countDown); // [3, 2, 1, 0]
console.log(newLength); // 4

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:

Example Code
const numbers = [1, 2, 3];
numbers.shift();
The numbers array would be [2, 3].
}

You might also like