[Javascript Tutorial 2/4] Lists, Functions, If statements, comparison

1. Constructing Strings with Variables

Sometimes you will need to build a string, Mad Libs style. By using the concatenation operator (+), you can insert one or more variables into a string you're building.


Example:


const ourName = "freeCodeCamp";

const ourStr = "Hello, our name is " + ourName + ", how are you?";

ourStr would have a value of the string Hello, our name is freeCodeCamp, how are you?.



2. Appending Variables to Strings

Just as we can build a string over multiple lines out of string literals, we can also append variables to a string using the plus equals (+=) operator.


Example:


const anAdjective = "awesome!";

let ourStr = "freeCodeCamp is ";

ourStr += anAdjective;

ourStr would have the value freeCodeCamp is awesome!.


3. Find the Length of a String

You can find the length of a String value by writing .length after the string variable or string literal.


console.log("Alan Peter".length);

The value 10 would be displayed in the console. Note that the space character between "Alan" and "Peter" is also counted.


For example, if we created a variable const firstName = "Ada", we could find out how long the string Ada is by using the firstName.length property.


let lastNameLength = 0;
const lastName = "Lovelace";


lastNameLength = lastName.length;

console.log(lastNameLength)


4. Use Bracket Notation to Find the First Character in a String

Bracket notation is a way to get a character at a specific index within a string.


Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as Zero-based indexing.


For example, the character at index 0 in the word Charles is C. So if const firstName = "Charles", you can get the value of the first letter of the string by using firstName[0].


Example:


const firstName = "Charles";

const firstLetter = firstName[0];

firstLetter would have a value of the string C.


5. Understand String Immutability

In JavaScript, String values are immutable, which means that they cannot be altered once created.


For example, the following code:


let myStr = "Bob";

myStr[0] = "J";

cannot change the value of myStr to Job, because the contents of myStr cannot be altered. Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:


let myStr = "Bob";

myStr = "Job";


6. Use Bracket Notation to Find the Nth Character in a String

You can also use bracket notation to get the character at other positions within a string.


Remember that computers start counting at 0, so the first character is actually the zeroth character.


Example:


const firstName = "Ada";

const secondLetterOfFirstName = firstName[1];

secondLetterOfFirstName would have a value of the string d.

const lastName = "Lovelace";

const thirdLetterOfLastName = lastName[2];

console.log(thirdLetterOfLastName)

v


7. Use Bracket Notation to Find the Nth-to-Last Character in a String

You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.


For example, you can get the value of the third-to-last letter of the const firstName = "Augusta" string by using firstName[firstName.length - 3]


Example:


const firstName = "Augusta";

const thirdToLastLetter = firstName[firstName.length - 3];

thirdToLastLetter would have a value of the string s.


8. Word Blanks

We will now use our knowledge of strings to build a "Mad Libs" style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence.


In a "Mad Libs" game, you are provided sentences with some missing words, like nouns, verbs, adjectives and adverbs. You then fill in the missing pieces with words of your choice in a way that the completed sentence makes sense.


Consider this sentence - It was really ____, and we ____ ourselves ____. This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows:


const sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";



9. Store Multiple Values in one Variable using JavaScript Arrays

With JavaScript array variables, we can store several pieces of data in one place.


You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:


const sandwich = ["peanut butter", "jelly", "bread"];


10. Nest one Array within Another Array

You can also nest arrays within other arrays, like below:


const teams = [["Bulls", 23], ["White Sox", 45]];

This is also called a multi-dimensional array.


11. Access Array Data with Indexes

We can access the data inside arrays using indexes.


Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array has an index of 0.



Example


const array = [50, 60, 70];

console.log(array[0]);

const data = array[1];


60



12. Modify Array Data With Indexes

Unlike strings, the entries of arrays are mutable and can be changed freely, even if the array was declared with const.


Example


const ourArray = [50, 40, 30];

ourArray[0] = 15;

ourArray now has the value [15, 40, 30].


Note: There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.


Modify the data stored at index 0 of myArray to a value of 45.


13. Access Multi-Dimensional Arrays With Indexes

One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.


Example


const arr = [

  [1, 2, 3],

  [4, 5, 6],

  [7, 8, 9],

  [[10, 11, 12], 13, 14]

];


arr[3];

arr[3][0];

arr[3][0][1];

arr[3] is [[10, 11, 12], 13, 14], arr[3][0] is [10, 11, 12], and arr[3][0][1] is 11.


Note: There shouldn't be any spaces between the array name and the square brackets, like array [0][0] and even this array [0] [0] is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.

const myArray = [
  [123],
  [456],
  [789],
  [[101112], 1314],
];

const myData = myArray[2][1];
console.log(myData)

8


14. Manipulate Arrays With push()

An easy way to append data to the end of an array is via the push() function.


.push() takes one or more parameters and "pushes" them onto the end of the array.


Examples:


const arr1 = [1, 2, 3];

arr1.push(4);


const arr2 = ["Stimpson", "J", "cat"];

arr2.push(["happy", "joy"]);

arr1 now has the value [1, 2, 3, 4] and arr2 has the value ["Stimpson", "J", "cat", ["happy", "joy"]].


const myArray = [["John"23], ["cat"2]];


myArray.push(["dog"3])

console.log(myArray)
[ [ 'John', 23 ], [ 'cat', 2 ], [ 'dog', 3 ] ]


15. Manipulate Arrays With pop()

Another way to change the data in an array is with the .pop() function.


.pop() is used to pop a value off of the end of an array. We can store this popped off value by assigning it to a variable. In other words, .pop() removes the last element from an array and returns that element.


Any type of entry can be popped off of an array - numbers, strings, even nested arrays.


const threeArr = [1, 4, 6];

const oneDown = threeArr.pop();

console.log(oneDown);

console.log(threeArr);

The first console.log will display the value 6, and the second will display the value [1, 4].

const myArray = [["John"23], ["cat"2]];

var removeFromMyArray = myArray.pop();

console.log(myArray);
[ [ 'John', 23 ] ]


16. Manipulate Arrays With shift()

pop() always removes the last element of an array. What if you want to remove the first?


That's where .shift() comes in. It works just like .pop(), except it removes the first element instead of the last.


Example:


const ourArray = ["Stimpson", "J", ["cat"]];

const removedFromOurArray = ourArray.shift();

removedFromOurArray would have a value of the string Stimpson, and ourArray would have ["J", ["cat"]].


const myArray = [["John"23], ["cat"2], ["dog"3]];


const removedFromMyArray = myArray.shift();

console.log(myArray);
[ [ 'cat', 2 ], [ 'dog', 3 ] ]



17. Manipulate Arrays With unshift()

Not only can you shift elements off of the beginning of an array, you can also unshift elements to the beginning of an array i.e. add elements in front of the array.


.unshift() works exactly like .push(), but instead of adding the element at the end of the array, unshift() adds the element at the beginning of the array.


Example:


const ourArray = ["Stimpson", "J", "cat"];

ourArray.shift();

ourArray.unshift("Happy");

After the shift, ourArray would have the value ["J", "cat"]. After the unshift, ourArray would have the value ["Happy", "J", "cat"].


const myArray = [["John"23], ["dog"3]];
myArray.shift();

myArray.unshift(["Paul"33]);


console.log(myArray);
[ [ 'Paul', 33 ], [ 'dog', 3 ] ]


18. Shopping List

Create a shopping list in the variable myList. The list should be a multi-dimensional array containing several sub-arrays.


The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity i.e.

["Chocolate Bar", 15]


19. Write Reusable JavaScript with Functions

In JavaScript, we can divide up our code into reusable parts called functions.


Here's an example of a function:

function functionName() {
  console.log("Hello World");
}
functionname();
Hello World

You can call or invoke this function by using its name followed by parentheses, like this: functionName(); Each time the function is called it will print out the message Hello World on the dev console. All of the code between the curly braces will be executed every time the function is called.


20. Passing Values to Functions with Arguments

Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or "passed") into a function when it is called are known as arguments.


Here is a function with two parameters, param1 and param2:


function testFun(param1, param2) {
  console.log(param1, param2);
}

Then we can call testFun like this: testFun("Hello", "World");. We have passed two string arguments, Hello and World. Inside the function, param1 will equal the string Hello and param2 will equal the string World. Note that you could call testFun again with different arguments and the parameters would take on the value of the new arguments.

function functionWithArgs(ab) {
  console.log(a + b);
}

functionWithArgs(5,10);

15



21. Return a Value from a Function with Return

We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.


Example

function plusThree(num) {
  return num + 3;
}

const answer = plusThree(5);

plusThree takes an argument for num and returns a value equal to num + 3.


function timesFive(num) {
  return num * 5;
}

const answer = timesFive(6);

console.log(answer);
30


22. Global Scope and Functions

In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.


Variables which are declared without the let or const keywords are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with let or const.


23. Local Scope and Functions

Variables which are declared within a function, as well as the function parameters, have local scope. That means they are only visible within that function.


Here is a function myTest with a local variable called loc.


function myTest() {

  const loc = "foo";

  console.log(loc);

}


myTest();

console.log(loc);

The myTest() function call will display the string foo in the console. The console.log(loc) line (outside of the myTest function) will throw an error, as loc is not defined outside of the function.


23. Global vs. Local Scope in Functions

It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.


In this example:


const someVar = "Hat";


function myFun() {

  const someVar = "Head";

  return someVar;

}

The function myFun will return the string Head because the local version of the variable is present.

const outerWear = "T-Shirt";

function myOutfit() {

    var outerWear = "sweater";

  return outerWear;
}

console.log(myOutfit());
console.log(outerWear);
sweater
T-Shirt


24. Assignment with a Returned Value

If you'll recall from our discussion of Storing Values with the Assignment Operator, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.


Assume we have pre-defined a function sum which adds two numbers together, then:

ourSum = sum(5, 12);

will call the sum function, which returns a value of 17 and assigns it to the ourSum variable.


let processed = 0;

function processArg(num) {
  return (num + 3) / 5;
}


processed = processArg(7);

console.log(processed);
2


25. Stand in Line
In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

function nextInLine(arritem) {
  
  arr.push(item);
  return arr.shift();
 
}

// Setup
const testArr = [12345];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr6));
console.log("After: " + JSON.stringify(testArr));

Before: [1,2,3,4,5]
1
After: [2,3,4,5,6]


26. Understanding Boolean Values

Another data type is the Boolean. Booleans may only be one of two values: true or false. They are basically little on-off switches, where true is on and false is off. These two states are mutually exclusive.


Note: Boolean values are never written with quotes. The strings "true" and "false" are not Boolean and have no special meaning in JavaScript.


27. Use Conditional Logic with If Statements

if statements are used to make decisions in code. The keyword if tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean conditions and they may only be true or false.


When the condition evaluates to true, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false, the statement inside the curly braces will not execute.


Pseudocode


if (condition is true) {

  statement is executed

}

Example

function test (myCondition) {
  if (myCondition) {
    return "It was true";
  }
  return "It was false";
}

test(true);
test(false);

test(true) returns the string It was true, and test(false) returns the string It was false.


When test is called with a value of true, the if statement evaluates myCondition to see if it is true or not. Since it is true, the function returns It was true. When we call test with a value of false, myCondition is not true and the statement in the curly braces is not executed and the function returns It was false.


28. Comparison with the Equality Operator

There are many comparison operators in JavaScript. All of these operators return a boolean true or false value.


The most basic operator is the equality operator ==. The equality operator compares two values and returns true if they're equivalent or false if they are not. Note that equality is different from assignment (=), which assigns the value on the right of the operator to a variable on the left.

function equalityTest(myVal) {
  if (myVal == 10) {
    return "Equal";
  }
  return "Not Equal";
}

If myVal is equal to 10, the equality operator returns true, so the code in the curly braces will execute, and the function will return Equal. Otherwise, the function will return Not Equal. In order for JavaScript to compare two different data types (for example, numbers and strings), it must convert one type to another. This is known as Type Coercion. Once it does, however, it can compare terms as follows:


1   ==  1  // true

1   ==  2  // false

1   == '1' // true

"3" ==  3  // true



function testEqual(val) {
  if (val == 12) { 
    return "Equal";
  }
  return "Not Equal";
}

console.log(testEqual(10));

Not Equal


29. Comparison with the Strict Equality Operator

Strict equality (===) is the counterpart to the equality operator (==). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.


If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.

3 ===  3  // true
3 === '3' // false

In the second example, 3 is a Number type and '3' is a String type.


30. Practice comparing different values

In the last two challenges, we learned about the equality operator (==) and the strict equality operator (===). Let's do a quick review and practice using these operators some more.


If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.

Examples

3 == '3' returns true because JavaScript performs type conversion from string to number. 3 === '3' returns false because the types are different and type conversion is not performed.

Note: In JavaScript, you can determine the type of a variable or a value with the typeof operator, as follows:

typeof 3
typeof '3'

typeof 3 returns the string number, and typeof '3' returns the string string.



31. Comparison with the Inequality Operator

The inequality operator (!=) is the opposite of the equality operator. It means not equal and returns false where equality would return true and vice versa. Like the equality operator, the inequality operator will convert data types of values while comparing.

Examples

1 !=  2    // true
1 != "1"   // false
1 != '1'   // false
1 != true  // false
0 != false // false


32. Comparison with the Greater Than Operator

The greater than operator (>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns true. Otherwise, it returns false.

Like the equality operator, the greater than operator will convert data types of values while comparing.

Examples

5   >  3  // true
7   > '3' // true
2   >  3  // false
'1' >  9  // false
function testGreaterThan(val) {
  if (val > 100) { 
    return "Over 100";
  }

  if (val > 10) {  
    return "Over 10";
  }

  return "10 or Under";
}

console.log(testGreaterThan(10));

10 or Under


33. Comparison with the Greater Than Or Equal To Operator

The greater than or equal to operator (>=) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.


Like the equality operator, the greater than or equal to operator will convert data types while comparing.


Examples

6   >=  6  // true
7   >= '3' // true
2   >=  3  // false
'7' >=  9  // false
function testGreaterOrEqual(val) {
  if (val >= 20) {  // Change this line
    return "20 or Over";
  }

  if (val >= 10) {  // Change this line
    return "10 or Over";
  }

  return "Less than 10";
}

console.log(testGreaterOrEqual(10));

10 or Over


34. Comparison with the Less Than Operator

The less than operator (<) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true. Otherwise, it returns false. Like the equality operator, the less than operator converts data types while comparing.

Examples

2   < 5 // true
'3' < 7 // true
5   < 5 // false
3   < 2 // false
'8' < 4 // false
function testLessThan(val) {
  if (val < 25 ) { 
    return "Under 25";
  }

  if (val < 55) { 
    return "Under 55";
  }

  return "55 or Over";
}

console.log(testLessThan(10));

Under 25


Popular posts from this blog

[Python] Dictionary

[Visual Design 2/3]

[JavaScript] For loop , Function