JavaScript Fundamentals - Complete Beginner - Quick Start Guide: Learn with Code Blocks
Learning web development is not an easy feat, especially when you've to tackle a programming language like JavaScript with no programming experience or understanding of object-oriented programming or other complex concepts. Diving into the vast world of web design and development does come with its challenges, which can be thankfully crossed with some practice and logic.
Getting your head around a new programming language is not ferns and petals, believe me, I'm saying this from my own encounter with JavaScript in my Master's course. But at times when you're stuck with a new skill, a new subject, or a new hobby, the key is to get your head around the fundamentals. Period.Here are the fundamentals of JavaScript straight from my study notes created using Notion, a powerful organizational tool, that helps me organize all my lessons, whether online, college-related, or personal practice. You may use CodePen or Visual Studio Code to test your code in the console. Let's begin!
1. Comments
// This is an inline comment
var example = 5;
/* This is a
multiline comment.
It can be used for multiple lines. */
// You can use shortcut Ctrl + / after selecting the lines to comment at once.
2. Data Types and Variables
/* Data Types:
undefined, null, boolean, string, number, and object
*/
// declare a variable
var myName = "Karan"
// Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.
// var can be changed later on like this
myName = 9;
// three ways to declare a variable:
var myName = "Karan";
// var is going to be able to be used throughout your whole program.
let ourName = "freeCodeCamp";
// let will only be used within the scope of where you declared that
const pi = 3.1415;
// const is a variable that should never change. It can never change. Unlike the var way which can be changed like in the example above. If you try to change a const, you'll get an error.
3. Declare a Read-Only Variable with the const Keyword
The keyword let
is not the only new way to declare
variables. In ES6, you can also declare variables using
the const
keyword.
const
has all the awesome features
that let
has, with the added bonus that variables
declared using const
are read-only. They are a constant
value, which means that once a variable is assigned
with const
, it cannot be reassigned:
const FAV_PET = "Cats";
FAV_PET = "Dogs";
The console will display an error due to reassigning the value
of FAV_PET
.
You should always name variables you don't want to reassign using
the const
keyword. This helps when you accidentally
attempt to reassign a variable that is meant to stay constant.
Note: It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays).
4. Storing Values with Assignment Operator
// In JavaScript, you can store a value in a variable with the assignment operator (=).
// There's a difference between assigning a variable and declaring a variable
var a; // here we declare the variable
var b = 2; // here we are assigning a variable. equal sign is assignment operator. 2 is being assigned to b.
console.log(a);
a = 7; // here we have assigned 7 to the variable a which we declared before.
b = a; // i have assigned contents of a to b
console.log(a); // allows you to see things in the console
//by using console.log() you can check what variables are at different stages of your program.
5. Initializing Variables with Assignment Operator
// initializing a variable to an initial value at the same time it's declared.
var a = 9;
6. Uninitialized Variables
//Initialize these three variables
//Before we do anything to these variables, they are uninitialized. Their value is undefined.
// var a;
// var b;
// var c;
var a = 5;
var b = 10;
var c ="I am a";
//Do not change code below this line
// reassign values to the variables
a = a + 1;
b = b + 5;
c = c + " String!";
console.log(a);
console.log(b);
console.log(c);
7. Case Sensitivity in Variables
// Variable names and function names in JS are case sensitive
// use camelCase
// Declarations
var studlyCapVar;
var properCamelCase;
var titleCaseOver;
//Assignments
studlyCapVar = 10;
properCamelCase = "A String";
titleCaseOver = 9000;
8. Adding Numbers
// for addition use the + operator
var sum = 10 + 10;
console.log(sum);
9. Subtracting Numbers
// for subtraction use the - operator
var difference = 43 - 3;
console.log(difference);
10. Multiplying Numbers
// for multiplication use the * operator
var product = 43 * 3;
console.log(product);
11. Dividing Numbers
// for division use the / operator
var quotient = 33 / 3;
console.log(quotient);
12. Incrementing Numbers
// incrementing numbers mean adding 1 to it
// following is the longhand method
var myVar = 87;
// only change code below this line
// increment the variable
//myVar = myVar + 1; // longhand
myVar++; //shorthand
console.log(myVar);
13. Decrementing Numbers
// decrementing numbers mean subtracting 1 from it
// following is the longhand method
var myVar = 87;
// only change code below this line
// increment the variable
//myVar = myVar - 1; // longhand
myVar--; //shorthand
console.log(myVar);
14. Decimal Numbers
// decimal numbers are referedd as floating point numbers or float
var ourDecimal = 5.7;
var myDecimal = 0.0009;
// Multiplying Decimals is similar to the way we did with integers using *
// Dividing Decimals is similar to the way we did with integers using /
15. Remainders
// remainder operator is %
// gives remainder of division of two numbers
// find out the remainder of 11 divided by 3
var remainder;
remainder = 11 % 3;
console.log(remainder);
// it is often used to determine whether the number is even or odd
// if the remainder is 0, then even. otherwise odd
16. Compound Assignment with Augmented Addition
var a = 3;
var b = 17;
var c = 12;
// now if we need to add a value to the above variables
// we can use the longhand method
// a = a + 12;
// b = b + 9;
// c = c + 7;
// or we could use the shorthand method by using += operator
a += 12;
b += 9;
c += 7;
// we're adding the value to the variable and assigning the answer to that variable
console.log(a);
console.log(b);
console.log(c);
17. Compound Assignment with Augmented Subtraction
var a = 11;
var b = 9;
var c = 3;
// now if we need to subtract value from the above variables
// we can use the longhand method
// a = a - 6;
// b = b - 15;
// c = c - 1;
// or we could use the shorthand method by using -= operator
a -= 6;
b -= 15;
c -= 1;
// we're subtracting the value from the variable and assigning the answer to that variable
console.log(a);
console.log(b);
console.log(c);
18. Compound Assignment with Augmented Multiplication
var a = 5;
var b = 12;
var c = 4.6;
// now if we need to multiply a value to the above variables
// we can use the longhand method
// a = a * 5;
// b = b * 3;
// c = c * 10;
// or we could use the shorthand method by using *= operator
a *= 5;
b *= 3;
c *= 10;
// we're multiplying the value to the variable and assigning the answer to that variable
console.log(a);
console.log(b);
console.log(c);
19. Compound Assignment with Augmented Division
var a = 48;
var b = 108;
var c = 33;
// now if we need to divide the above variables by new values
// we can use the longhand method
// a = a / 12;
// b = b / 4;
// c = c / 11;
// or we could use the shorthand method by using /= operator
a /= 12;
b /= 4;
c /= 11;
// we're dividing the variable by a new number and assigning the answer to that variable
console.log(a);
console.log(b);
console.log(c);
20. Escaping Literal Quotes in Strings
// use the escape character before a quotes to restrict JS from reading it as a string ending or beginning
var myStr = "I am a \\"double quoted\\" string inside \\"double quotes\\".";
console.log(myStr);
// Javascrit knows that \\" means a quotation mark
21. Quoting Strings with Single Quotes
// instead of using the quote character \\" you can start the string with single quotes and have the double quotes inside without the quote character
var myStr = '<a href ="<http://www.example.com>" target="_blank">Link</a>';
// here JS knows you're adding a double quote marks inside the string defined by single quotes
console.log(myStr);
// if you want to use both double quotes and single quotes inside the string, then use backticks or ``
var myStr = `I can write 'single quotes' and "double quotes" both without error.`;
console.log(myStr);
22. Escape Sequence in Strings
// You can escape multiple characters using the following ways:
/*
CODE OUTPUT
\\' single quote
\\" double quote
\\\\ backslash
\\n newline
\\r carriage return
\\t tab
\\b backspace
\\f form feed
*/
var myStr = "FirstLine\\n\\t\\\\SecondLine\\nThirdLine";
console.log(myStr);
23. Concatenating Strings with + Operator
// Example
var ourStr = "I come first. " + "I come second.";
var myStr = "This is the start. " + "This is the end";
console.log(ourStr);
console.log(myStr);
24. Concatenating Strings with += Operator
// Example
var ourStr = "I come first. ";
ourStr += "I come second.";
var myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";
console.log(ourStr);
console.log(myStr);
25. Constructing Strings with Variables
// Example
var ourName = "freeCodeCamp";
var ourStr = "Hello, our Name is " + ourName + ", how are you?";
var myName = "Karan";
var myStr = "Hello, my name is " + myName + ", how are you?";
console.log(ourStr);
console.log(myStr);
26. Appending Variables to Strings
// Example
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
var someAdjective = "worthwhile!";
var myStr = "Learning to code is ";
myStr += someAdjective;
console.log(ourStr);
console.log(myStr);
27. Find Length of String
// Example
var firstNameLength = 0;
var firstName = "Karan";
firstNameLength = firstName.length; //calculates the number of characters and stores an integer value
console.log(firstNameLength);
//Setup
var lastNameLength = 0;
var lastName = "Gupta";
lastNameLength = lastName.length;
console.log(lastNameLength);
28. Bracket Notation to find first character in String
// Example
var firstLetterOfFirstName = 0;
var firstName = "Karan";
firstLetterOfFirstName = firstName[0]; // stores the character at 0 index
//JS starts indexing at 0 which is zero-based indexing
console.log(firstLetterOfFirstName);
//Setup
var firstLetterOfLasttName = 0;
var lastName = "Gupta";
firstLetterOfLasttName = lastName[0];
console.log(firstLetterOfLasttName);
29. String Immutability
// Strings are immutable that means they cannot be altered once created
// this doesn't mean they can't be changed, just that the individual characters of a string literal cannot be changed
// Setup
var myStr = "Jello World";
//myStr[0] = "H"; // This won't work
// Instead we will have to change the string like this
myStr = "Hello World";
console.log(myStr);
30. Bracket Notation to Find Nth Character in String
// Example
var secondLetterOfFirstName = 0;
var firstName = "Karan";
secondLetterOfFirstName = firstName[1]; // stores the character at 1 index
//JS starts indexing at 0 which is zero-based indexing
console.log(secondLetterOfFirstName);
//Setup
var thirdLetterOfLasttName = 0;
var lastName = "Gupta";
thirdLetterOfLasttName = lastName[2];
console.log(thirdLetterOfLasttName);
31. Bracket Notation to Find Last Character in String
// Example
var lastLetterOfFirstName = 0;
var firstName = "Karan";
lastLetterOfFirstName = firstName[firstName.length - 1]; // stores the character at 1 index
//JS starts indexing at 0 which is zero-based indexing
console.log(lastLetterOfFirstName);
//Setup
var lastLetterOfLasttName = 0;
var lastName = "Gupta";
lastLetterOfLasttName = lastName[lastName.length - 1];
console.log(lastLetterOfLasttName);
32. Bracket Notation to Find Nth-to-Last Character in String
// Example
var thirdToLastLetterOfFirstName = 0;
var firstName = "Karan";
thirdToLastLetterOfFirstName = firstName[firstName.length - 3];
console.log(thirdToLastLetterOfFirstName);
//Setup
var secondToLastLetterOfLasttName = 0;
var lastName = "Gupta";
secondToLastLetterOfLasttName = lastName[lastName.length - 2];
console.log(secondToLastLetterOfLasttName);
33. Word Blanks (Challenge)
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
result += "The " + myAdjective + " " + myNoun + " " + myVerb + " to the store " + myAdverb + ".";
return result
}
console.log(wordBlanks("dog", "big", "ran", "quickly"));
console.log(wordBlanks("bike", "old", "drove", "slowly"));
34. Store Multiple Values with Arrays
// arrays allow you to store several pieces of data in one place
// Example
var ourArray = ["John", 23];
var myArray = ["Quincy", 1];
35. Nested Arrays
// Example
var ourArray = [["the universe", 42], ["everything", 101010]];
var myArray = [["Bulls", 23], ["White Sox", 45]];
36. Access Array Data with Indexes
// Example
var ourArray = [50, 60, 70];
var ourData = ourArray[0];
console.log(ourData);
var myArray = [45, "Karan", 5.6789];
var myData = myArray[1];
console.log(myData);
37. Modify Array Data with Indexes
//Example
var ourArray = [18, 64, 99];
ourArray[1] = 45; // ourArray now equals [18, 45, 99]
console.log(ourArray);
var myArray = [18, 64, 99];
myArray[0] = 45; // ourArray now equals [45, 64, 99]
console.log(myArray);
38. Access Multi-Dimensional Arrays with Indexes
// Nested arrays can be accessed using multiple index brackets
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
//Access the number 1 from the above arrray:
var ourData = myArray[0][0];
console.log(ourData);
// Access the number 8 from the above nested array:
var myData = myArray[2][1];
console.log(myData);
// Access the number 11 from the above 3 level nested array:
var yourData = myArray[3][0][1];
console.log(yourData);
39. Manipulate Arrays with push()
// you can append data to the end of an array with the push function
var ourArray = ["Stimpson", "J", "cat"];
ourArray.push("happy", "joy");
console.log(ourArray); // ['Stimpson', 'J', 'cat', 'happy', 'joy']
var myArray = [["John", 23], ["cat", 2]];
myArray.push(["dog", 3]); // append another array at the end
console.log(myArray); //[["John", 23], ["cat", 2], ["dog", 3]]
40. Manipulate Arrays with pop()
// we can remove an item from an array using the pop function
var ourArray = [1,2,3];
var removedFromOurArray = ourArray.pop();
// removes one item from the array be it a data type or another array
console.log(removedFromOurArray); // this will be the removed item
console.log(ourArray); // array now becomes [1, 2]
var myArray = [["John", 23], ["cat", 2]];
var removedFromMyArray = myArray.pop();
console.log(myArray); // my array now is [["John", 23]]
41. Manipulate Arrays with shift()
// shift function is similar to pop function except it removes the first element of the array instead of the final element
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();
console.log(removedFromOurArray); //Stimpson
console.log(ourArray); // ["J", ["cat"]]
var myArray =[["John", 23], ["dog", 3]];
var removedFromMyArray = myArray.shift();
console.log(removedFromMyArray); //['John', 23]
console.log(myArray); // [["dog", 3]]
42. Manipulate Arrays with unshift()
// unshift function is similar to the push function
// while push adds element to the end of the array
// unshift adds element to the beginning of the array
var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"]
ourArray.unshift("Happy");
// ourArray now equals ["Happy", "J", "cat"]
console.log(ourArray);
var myArray = [["John", 23], ["dog", 3]];
myArray.shift();
myArray.unshift(["Paul", 35]);
console.log(myArray); // [["Paul", 35], ["dog", 3]]
43. Shopping List (Code Challenge)
var myList = [["cereal", 3], ["milk", 2], ["bananas", 3], ["juices", 2], ["eggs", 12]];
// we've created an array of arrays which is our shopping list
44. Write Reusable Code with Functions
// functions allow us to create reusable code in JavaScript
// function functionName(){}
// everything inside the curly bracket is run anytime the function is called or invoked
function ourReusableFunction() {
console.log("Hello World");
}
ourReusableFunction();
// here the function is being called by just putting the function name with parenthesis after the name
// everytime this function is called, the console is going to say "Hello World"
// we can run the function multiple times
// ourReusableFunction();
// ourReusableFunction();
function reusableFunction() {
console.log("Hi World");
}
// call the above function
reusableFunction();
45. Passing Values to Functions with Arguments
// parameters are variables that act as place holders for the values that are to be input to a function when it is called.
function ourFunctionWithArgs(a, b) {
console.log(a - b);
}
// data in the (parameters) means that when this function is called we're going to pass data into the function or input data into the function
ourFunctionWithArgs(10, 5); // output is 5
// we're passing the values 10, 5 into the parameters defined above and performing the function created above
// So, when the function runs, it can use the information that's passed into the function
function functionWithArgs(a, b) {
console.log(a + b);
}
functionWithArgs(10, 5); // call the function with values
46. Global Scope and Functions
// scope refers to the visibility of variables
// variables which are defined outside of a function block have global scope
// global scope means they can be seen everywhere in your JavaScript code
// declare your variable here
var myGlobal = 10;
// now since this is set outside of a function we can see it anywhere in the whole code
// the program knows about the above variable because this is in global scope
function fun1()
{
// Assign 5 to oopsGlobal Here
var oopsGlobal = 5;
// normally if you do use a var keyword before the variable, since this is within a function, it will be scoped to that function
// without the var keyword, the variable becocmes global automatically. that means you can access it anywhere else in the program including here.
}
function fun2() {
var output = "";
if (typeof myGlobal != "undefined")
{
output += "myGlobal: " + myGlobal;
}
if ( typeof oopsGlobal != "undefined")
{
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
// if we don't use var keyword, the variable becomes global and makes the if statement true and gives the output of oopsGlobals
//output -> myGlobal: 10 oopsGlobal: 5
// on the other hand, if we use the var keyword in front of the oopsGlobal variable, it scopes the variable to the function fun1() and doesn't allow it to be acessed in second function fun2()
//oopsGlobal becomes undefined and if statement is false
// output -> myGlobal: 10
}
fun1();
fun2();
47. Local Scope and Functions
// variables which are declared within a function as well as the function parameters have a local scope
// That means they're only visible from within the function
function myLocalScope() {
var myVar = 5; // only visible inside the function
console.log(myVar);
}
myLocalScope();
console.log(myVar);
// error occured myVar is not defined. because it tried to access myVar outside of the function.
48. Global vs. Local Scope in Functions
// it is possible to have both local and global variable with the same name
// when you do this, the local variable takes precedent over the global variable
var outerWear = "T-Shirt";
function myOutfit() {
var outerWear = "sweater";
return outerWear;
}
console.log(myOutfit());
// the local variable within the function takes precedent over the global variable outside of the function
console.log(outerWear); // still returns T-shirt which is the initially assigned global variable outside of the function
49. Return a Value from a Function with Return
// you can return a value from a function within this return statement.
function minusSeven(num) {
return num - 7;
}
console.log(minusSeven(10));
function timesFive(num) {
return num * 5;
}
console.log(timesFive(5));
50. Understanding Undefined Value Returned from a Function
// functions can have return statements, but they don't have to
// if you don't specify a return value, the return value is just undefined
var sum = 0;
function addThree() {
sum += 3;
}
console.log(addThree()); // returns undefined
function addFive() {
sum += 5;
}
console.log(addFive()); // returns undefined
51. Assignment with a Returned Value
// it's simple to assign a returned value to a variable
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
console.log(changed); //returns 5
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
processed = processArg(12);
console.log(processed); //returns 3
52. Stand in Line - Queues
// in computer science, a queue is an abstract data structure where items are kept in order
// new items can be added to the back of the queue and old items are taken off from the front of the queue
// we're going to simulate that right now. some of the functionality of a queue using the nextInLine function
function nextInLine(arr, item) {
arr.push(item); // appends item to the end in this case 6
return arr.shift(); // removes the first item in the list and returns
}
var testArr = [1,2,3,4,5];
console.log("Before: " + JSON.stringify(testArr)); // JSON.stringify is just a way to change an array into a string
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
53. Boolean Values
// Boolean is another data type in JavaScript
// have only two values -> true or false
// They're basically little on/off switches where true is on and false is off
function welcomToBooleans() {
return true;
}
console.log(welcomToBooleans()); //output is true
54. Use Conditional Logic with IF statements
// an IF statement is 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 parenthesis
// if the condition within the parenthesis is true, then the code within the curly braces will be evaluated or run
// Example
function ourTrueOrFalse(isItTrue) {
if (isItTrue) {
return "Yes, it is true!";
}
return "No, it is false!";
}
console.log(ourTrueOrFalse(true)); // output: Yes, it is true!
// Another example
function trueOrFalse(wasThatTrue) {
if (wasThatTrue) {
return "Yes, that's true!";
}
return "No, that's false";
}
console.log(trueOrFalse(true)); //output: Yes, that's true!
55. Comparison with the Equality Operator
// There are many comparison operators in JavaScript that will return a Boolean of true or false. Most common is the equality operator
// == is the equality operator to check whether two values are equal
function testEqual(val) {
if (val == 12) {
return "Equal";
}
return "Not Equal";
}
console.log(testEqual(10)); //output: Not Equal
56. Comparison with the Strict Equality Operator
// === is the strict equality operator sign
// difference between equality == and strict equality operator sign:
// the double equal sign attempts to convert both the values beign compared to a common type while the strict equality operator does not do the type conversion
// 3 === 3 will be true because of strict equality operator
// 3 == '3' will be true because of equality operator since the number will be converted to string
// 3 === '3' will be false because of the equality operator
//Example
function testStrict(val) {
if (val === 7) {
return "Equal";
}
return "Not Equal";
}
console.log(testStrict('7')); // Output: Not Equal becuase 7 here is a string
57. Practice Comparing Different Values
function compareEquality(a, b) {
if (a == b) {
return "Equal";
}
return "Not Equal";
}
console.log(compareEquality(10, "10")); // output is Equal
function compareEquality(a, b) {
if (a === b) {
return "Equal";
}
return "Not Equal";
}
console.log(compareEquality(10, "10")); // output is Not Equal
58. Comparison with the Inequality Operator
// != is the inequality operator. It means 'not equal to'.
// just like the equality operator, it does type conversion
function testNotEqual(val) {
if (val != 99) {
return "Not Equal"
}
return "Equal";
}
console.log(testNotEqual(10)); // output is Not Equal
59. Comparison with the Strict Inequality Operator
// Basically opposite of strict equality operator
// does not convert type
function testStrictNotEqual(val) {
if (val !== 17) {
return "Not Equal";
}
return "Equal";
}
console.log(testStrictNotEqual('17')); //output is Not Equal but it would've been Equal had we used the equality operator
60. Comparisons with the Greater than Operator
function testGreaterThan(val) {
if (val > 100) {
return "Over 100";
}
if (val > 10) {
return "Over 10";
}
return "10 or Under";
}
console.log(testGreaterThan(11)); // output is Over 10
61. Comparison with the Greater Than Or Equal to Operator
function testGreaterOrEqual(val) {
if (val >= 20) {
return "20 or over";
}
if (val >= 10) {
return "10 or over";
}
return "Less than 10";
}
console.log(testGreaterOrEqual(11)); // output is 10 or over
62. Comparison with Less Than Operator
function testLessThan(val) {
if (val < 25) {
return "Under 25";
}
if (val < 55) {
return "Under 55";
}
return " 55 or Over";
}
console.log(testLessThan(10)); //output is Under 25
63. Comparison with Less Than Or Equal To Operator
function testLessOrEqual(val) {
if (val <= 12) {
return "Smaller Than or Equal to 12";
}
if (val <= 24) {
return "Smaller Thanor Equal to 24";
}
return "More Than 24";
}
console.log(testLessOrEqual(12)); // Output: Smaller Than or Equal to 12
64. Comparisons with the Logical AND Operator
// && is symbol for AND operator
// used to check two conditions simultaneously
// both the statements have to be true for program to be executed
function testLogicalAnd(val) {
if (val <=50 && val >= 25) {
return "Yes";
}
return "No";
}
console.log(testLogicalAnd(26));
65. Comparisons with the Logical OR Operator
// Used check if either one of the statements is true
// If you're using multiple If statements to return the same value, then use the OR operator
// || is the symbol for OR operator
function testLogicalOr(val) {
if (val < 10 || val > 20) {
return "Outside";
}
return "Inside";
}
console.log(testLogicalOr(11)); //output is Inside
66. Else Statements
// When If statement is true, normally the block of code after the If statement will be evaluated.
// But with an Else statement, an alternate block of code can be executed when it's not true.
function testElse(val) {
var result = "";
if (val > 5) {
result = "Bigger than 5";
} else {
result = "5 or Smaller"
}
return result;
}
console.log(testElse(4));
67. Else If Statements
// if you have multiple conditions that need to be addressed, you can use else if statements.
// it's a way of chaining multiple If statements together
function testElseIf(val) {
if (val > 10) {
return "Greater Than 10";
} else if (val < 5){
return "Smaller Than 5";
} else {
return "Between 5 and 10";
}
}
console.log(testElseIf(6)); // output is Between 5 and 10
68. Logical Order in If Else Statements
// When you're using else if statements, order is very important.
// Once the first condition is met, it doesn't even check for the rest of the conditions
function orderMyLogic(val) {
if (val < 5) {
return "Less Than 5";
} else if (val < 10) {
return "Less Than 10";
} else {
return "Greater than or equal to 10";
}
}
console.log(orderMyLogic(3));
// this will say Less Than 10 if val < 10 is kept at the top in the logical order
// when the order is changed and val < 5 is kept above the val < 10, then the output will be correct i.e. Less Than 5
69. Chaining If Else Statements
// you can change multiple if else statements
/*
Write chained if/else if statements to fulfill the fulfill conditions:
num < 5 - return "Tiny"
num < 10 - return "Small"
num < 15 - return "Medium"
num < 20 - return "Large"
num >= 20 - return "Huge"
*/
function testSize(num) {
if (num < 5) {
return "Tiny";
} else if (num < 10) {
return "Small";
} else if (num < 15) {
return "Medium";
} else if (num < 20) {
return "Large";
} else {
return "Huge";
}
}
console.log(testSize(3)); // "Tiny"
console.log(testSize(7)); // "Small"
console.log(testSize(12)); // "Medium"
console.log(testSize(16)); // "Large"
console.log(testSize(21)); // "Huge"
70. Golf Game (Code Challenge)
var names = ["Holes-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home"];
function golfScore(par, strokes) {
if (strokes == 1) {
return names[0];
}
else if (strokes <= par - 2){
return names[1];
}
else if (strokes == par - 1){
return names[2];
}
else if (strokes == par){
return names[3];
}
else if (strokes == par + 1){
return names[4];
}
else if (strokes == par + 2){
return names[5];
}
else if (strokes >= par + 2){
return names[6];
}
}
console.log(golfScore(5, 4));
/*
Strokes Return
1 "Hole-in-one"
<= par - 2 "Eagle"
par - 1 "Birdie"
par "Par"
par + 1 "Bogey"
par + 2 "Double Bogey"
>= par + 2 "Go Home"
*/
71. Switch Statements
// Instead o dusing chained else if statements you can use a switch statement
// A switch statement tests a value and can have many case statements which define various possible values
function caseInSwitch(val) {
var answer = "";
switch (val) {
case 1: // here it's using strict equality operator
answer = "alpha";
break; // if you don't have a break statement it will just run through to the next case statement automatically. it would just skip over to the next case statement
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
break;
default: // default option is kind of like else statement in else if statements
answer = undefined;
break;
}
return answer;
}
console.log(caseInSwitch(3));
72. Multiple Identical Options in Switch Statements
// Sometimes you want a switch statement where multiple inputs give the same output
// that's easy enough by omitting the break statement
// you can change a chain of else if statements to a switch statement
function sequentialSizes(val) {
var answer = "";
switch (val) {
case 1:
case 2:
case 3:
answer = "Low";
break;
case 4:
case 5:
case 6:
answer = "Mid"
break;
case 7:
case 8:
case 9:
answer ="High"
break;
default:
break;
}
return answer;
}
console.log(sequentialSizes(6));
73. Returning Boolean Values from Functions
// All the comparison operators return a boolean true or false value so thre is no need to create an else if statement
// convert this else if to a single line of code
function isLess(a,b) {
// if(a < b){
// return true;
// } else {
// return false;
// }
return a < b; // will return true or false
}
console.log(isLess(10,15));
74. Returning Early Pattern from Functions
// you cana exit a function with a return before the last return is executed
function abTest(a, b) {
if (a < 0 || b < 0) {
return undefined;
}
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
console.log(abTest(-2,2));
75. Counting Cards (Code Challenge)
// We are going to create a blackjack card counting function
// how this card counting works
// when you see a low card, the count goes up
// when you see a high card, the count goes down
// if it's a middle value card, the count stays the same
// when the count is positive, the player should bet high
// when the count is zero or negative, the player should bet low
// we're going to use a switch statement to figure out what card has been passed in and what to do about it.
var count = 0; // depending on what the card is, it's going to increase this global variable or decrease it or stay the same
function cc(card) {
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
count--;
break;
}
var holdbet = 'Hold';
if (count > 0) {
holdbet = 'Bet';
}
return count + " " + holdbet; // return the current count value and whether the player should hold or bet
}
// everytime you call the cc function, it's going to change this count value and return the total count
cc(2); cc('K'); cc(10); cc('K'), cc('A');
console.log(cc(4));
76. Build JavaScript Objects
// objects are similar to arrays except that instead of using indexes to access data, you use properties
// objects are going to be defined with curly braces at the beginning and the end
// property: value
// properties can be any data type in JavaScript
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": [everything];
};
var myDog = {
"name": "Quincy",
"legs": 3,
"tails": 2,
"friends": []
};
// this way we have create our own two objects ourDog and myDog
77. Accessing Object Properties with Dot Notation
// there are two main ways to access a property on an object
// first is dot notation
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
var hatValue = testObj.hat; //assigns the hat property to the variable. so the value will be ballcap.
var shirtValue = testObj.shirt;
78. Accessing Object Properties with Bracket Notation
// you can use the bracket notation anytime but it is required if the property name has a space in it
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water",
}
var entreeValue = testObj["an entree"]; //value set to hamburger
var sideValue = testObj['my side']; //value set to veggies
var drinkValue = testObj["the drink"]; // value set to water
79. Accessing Object Properties with Variables
// bracket notation can also be used to look up object properties using variables
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber]; // value comes as "Montana"
80. Updating Object Properties
// we can use dot notation to update object properties
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.name = "Happy Camper";
console.log(ourDog.name); // Happy Camper
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ['freeCodeCamp Campers']
};
myDog.name = "Happy Coder";
console.log(myDog.name);
81. Add New Properties to an Object
// add new properties to an object using dot notation or bracket notation
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.bark = "bow-wow"; // a new property is added to the object
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ['freeCodeCamp Campers']
};
myDog['bark'] = "woof"; // a new property is added to the object
82. Delete Properties from an Object
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"],
"bark": "bow-wow"
};
delete ourDog.bark; // will delete the bark property
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ['freeCodeCamp Campers'],
"bark": "woof"
};
delete myDog.tails; // will delete the tails property from the object
83. Using Objects for Lookups
// objects can be thought of as a key value storage like a dictionary.
// you can use an object to lookup values
function phoneticLookup(val) {
var result = "";
// switch (val) {
// case "alpha":
// result = "Adams";
// break;
// case "bravo":
// result = "Boston";
// break;
// case "charlie":
// result = "Chicago";
// break;
// case "delta":
// result = "Denver";
// break;
// case "echo":
// result = "Easy";
// break;
// case "foxtrot":
// result = "Frank";
// break;
// default:
// return undefined;
// break;
// }
//Instead of the above switch statement, we can create an object
var lookup = {
"alpha": "Adams",
"bravo": "Boston",
"charlie": "Chicago",
"delta": "Denver",
"echo": "Easy",
"foxtrot": "frank"
};
result = lookup[val];
return result;
}
console.log(phoneticLookup("delta"));
84. Testing Objects for Properties
// you can check if an object has a property with the hasown property method
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
if (myObj.hasOwnProperty(checkProp)) {
return myObj[checkProp];
} else {
return "Not Found"
}
}
console.log(checkObj("gift")); // pony
console.log(checkObj("hello")); // Not Found
85. Manipulating Complex Objects
// A JavaScript object is a way to store flexible data
// So you can store strings, numbers, arrays and even other objects
// inside the below objects are all the key value pairs with the strings and numbers
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
},
{
"artist": "Beau Carnes",
"title": "Cereal Man",
"release_year": 2002,
"formats": [
"YouTube video"
]
}
];
// here we've created a second object in our myMusic array
// and each object holds data and a property which is the key value format
// this is very similar to JSON
86. Accessing Nested Objects
//in order to access the sub properties of an object you can chain together the dot or bracket notation
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
var gloveBoxContents = myStorage.car.inside["glove box"];
console.log(gloveBoxContents); // maps
87. Accessing Nested Arrays
// array bracket notation can be changed to access nested arrays
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
// we can combine dot notation and bracket notation to access the secocnd tree
var secondTree = myPlants[1].list[2];
console.log(secondTree);
88. Record Collection (Challenge)
// we're given this object here which is a record collection
// each record has an ID number and then also has different pieces of information about the record
// create the updateRecords function where we can pass in the ID, property and the value
// and it's going to update our record collection with the property and the value
var collection = {
"2548": {
"album": "Slippery When Wet",
"artist": "Bon Jovi",
"tracks": [
"Let It Rock",
"You Give Love a Bad Name"
]
},
"2468": {
"album": "1999",
"artist": "Prince",
"tracks": [
"1999",
"Little Red Corvette"
]
},
"1245": {
"artist": "Robert Palmer",
"tracks": []
},
"5439": {
"album": "ABBA Gold"
}
};
var collectionCopy = JSON.parse(JSON.stringify(collection));
// just a fancy way in JavaScript to make a copy of the object
function updateRecords(id, prop, value) {
if (value === "") {
delete collection[id][prop]
} else if (prop === "tracks"){
collection [id][prop] = collection[id][prop] || [];
collection[id][prop].push(value);
} else {
collection[id][prop] = value;
}
return collection;
}
console.log(updateRecords(5439, "artist", "ABBA"));
89. Iterate with While Loops
// loops allow you to run code multiple times
// while loops runs while a specified condition is true and stops once it's not longer true
var myArray = [];
var i = 0; // first we define where the variable starts off at
while (i < 5) {
myArray.push(i); // pushes i to the end of the array
i++; // to make sure the loop ends, we'll have to increment it till it reaches 4
}
console.log(myArray); // (5) [0, 1, 2, 3, 4]
// every time it went through this five different times and pushed 0,1,2,3,4 onto the loop
90. Iterate with For Loops
// for loop is the most common type of loop is JS
var ourArray = [];
// first we have the initialisation, it happens before any of the inside the loop runs
// then we have the condition
// once the condition becomes false, we break out of the loop
// the final parameter in the for loop defines what we do at the end of each iteration
// here at the end of each iteration, we increment i by 1
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
console.log(ourArray);
var myArray = [];
for (var i = 1; i < 6; i++) {
myArray.push(i);
}
console.log(myArray);
91. Iterate Odd Numbers with a For Loop
var ourArray = [];
for (let i = 0; i < 10; i += 2) {
ourArray.push(i);
}
console.log(ourArray); //(5) [0, 2, 4, 6, 8]
var myArray = [];
for (let i = 1; i < 10; i += 2) {
myArray.push(i);
}
console.log(myArray); //(5) [1, 3, 5, 7, 9]
92. Count Backwards with a For Loop
var ourArray = [];
for (let i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
console.log(ourArray); //(5) [10, 8, 6, 4, 2]
var myArray = [];
for (let i = 9; i > 0; i -= 2) {
myArray.push(i);
}
console.log(myArray); //(5) [9, 7, 5, 3, 1]
93. Iterate through an Array with a For Loop
var ourArr = [9, 10, 11, 12];
var ourTotal = 0;
for (let i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
console.log(ourTotal); // adding up all the numbers in the array is 42
var myArr = [2, 3, 4, 5, 6,];
var myTotal = 0;
for (let i = 0; i < myArr.length; i++) {
myTotal += myArr[i];
}
console.log(myTotal); // 20
94. Nesting For Loops
function multiplyAll(arr) {
var product = 1;
for (let i = 0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++){
product *= arr[i][j]; // this takes items from both the arrays and multiply them
}
}
return product;
}
var product = multiplyAll([[1,2], [3,4], [5,6,7]]);
console.log(product); //5040
95. Iterate with Do…While Loops
// a while loop will first check the condition and then run the loop
// a do while loop will atleast runs once before checking the condition
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 5);
// while (i < 5) {
// myArray.push(i);
// i++;
// }
console.log(i, myArray);
96. Profile Lookup (Code Challenge)
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0556699882",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "04455996212",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "07788541882",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "07785499882",
"likes": ["Javascript", "Gaming", "Foxes"]
},
]
function lookupProfile(name, prop) {
for (let i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name) {
return contacts[i][prop] || "No such property";
}
}
return "No such contact";
}
var data = lookupProfile("Sherlock", "number");
console.log(data);
97. Generate Random Fractions
// there's a simple way to create a random decimal number in JS with the math.random function
function randomFraction() {
return Math.random();
}
console.log(randomFraction());
98. Generate Random Whole Numbers
// often you want a random whole number instead of a random decimal number
// this can be done with math.floor
// math.floor rounds down to the nearest whole number
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
return Math.floor( Math.random() * 10);
}
console.log(randomWholeNum());
console.log(randomNumberBetween0and19);
99. Generate Random Whole Numbers within a Range
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
var ourRandom = ourRandomRange(1,9);
console.log(ourRandom);
function myRandomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax -myMin + 1)) + myMin;
}
console.log(myRandomRange(5,15));
100. Use the parseInt Function
// it takes a string and returns an integer
// a useful function
// many times you want to make sure you're dealing with integers and not strings for different calculations
// if the string can't be converted into an integer, it returns in NaN for Not a Number
function converToInt(str) {
return parseInt(str);
}
console.log(converToInt("89"));
101. Use the parseInt Function with a Radix
// radix spicifies the base of the number in the string such as base 2 or base 7 or base 8
// base would be binary so it's one of the most common to use
// default is base 10
// the function below converts the binary input into base 10
function converToInteger(str) {
return parseInt(str, 2)
}
console.log(converToInteger("10011"));
102. Use the Conditional (Ternary) Operator
// it's like a one line if-else statement
// we can replace an if else statement with a ternary operator
// basic syntax:
// condition ? statement-if-true : statement-if-false;
function checkEqual(a, b) {
if (a === b) {
return true;
} else {
return false;
}
}
console.log(checkEqual(1, 1));
// the above if else can be replaced with a ternary operator like this
function newCheckEqual(x, y) {
return x === y ? true : false;
}
console.log(newCheckEqual(1,1));
103. Using Multiple Conditional (Ternary) Operators
// the greatest feature of ternary operators is that you can nest them within each other which gives them even more power
// we will create a function that checks if the input number num is positive or negative or zero
function checkSign(num) {
return num > 0 ? "positive" : num < 0 ? "negative" : "zero";
}
console.log(checkSign(0));
// first the num is checked with the first ternary operator and then the second one and it returns the false statement because num is not less than 0. It follows the sequence.
104. Differences Between the var and let keywords
// let doesn't allow to declare the same variable twice in the same scope
// this allows your program to give you an error to tell you that you've done something wrong
// if we don't use the word let here we could just set the catName variable
// some people never use var to declare a variable and some only use let and const
let catName = "Quincy";
let quote;
catName = "Beau";
function catTalk() {
"use Strict"; // this enables strict mode which catches common coding mistakes and unsafe actions
// many programmers use this at the top of thei JS code to detect any coding mistakes such as if create a variable and don't declare it with var, let or const
catName = "Oliver";
quote = catName + " says Meow"
}
console.log(catTalk());
105. Compare Scopes of the var and let Keywords
// Another major diference between a var and a let keyword is that the var declaration declares the variable globally or locally if declared inside a function
// the scope of let is limited to the block statement or expression that it was declared in
function checkScope() {
"use strict";
let i = "function scope";
if (true) {
let i = "block scope";
console.log("Block Scope i is: ", i);
}
console.log("Function scope i is: ", i);
return i;
}
checkScope();
/* Block Scope i is: block scope
main.js:8
Function scope i is: function scope */
106. Declare a Read Only variable with the const keyword
// const has all the features of let but it's also read-only
// you cannot reassign const
// can be very helpful to stop you from making mistakes later
// if you know for sure that you're never going to reassign a variable then you should always use const so you don't accidently reassign it when you don't mean to
// when using const write it in a standard UPPERCASE
function printManyTimes(str) {
"use strict";
const SENTENCE = str + " is cool!";
for (let i = 0; i < str.length; i++) {
console.log(SENTENCE);
}
}
console.log(printManyTimes("freeCodeCamp"));
107. Mutate an Array declared with Const
const s = [5, 7, 2];
function editInPlace() {
"use strict";
//s = [2,5,7];
s[0] = 2;
s[1] = 5;
s[2] = 7;
}
editInPlace();
console.log(s);
108. Prevent Object Mutation
// const declaration won't really protect your data from mutation
// objects and arrays can be mutated even if it's declared with const
// object.freeze prevents data mutation
function freezeObj() {
"use strict";
const MATH_CONSTANTS = {
PI: 3.14,
};
Object.freeze(MATH_CONSTANTS);
try {
MATH_CONSTANTS.PI = 99;
} catch (ex) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
const PI = freezeObj();
console.log
109. Use Arrow Functions to Write Concise Anonymous Functions
var magic = function () {
return new Date();
};
// this is an anonymous function.
// no name
// assigned to a variable
// you can convert it into an arrow function
// arrow function makes it quicker to write
const magic = () => new Date();
110. Use Arrow Functions with Parameters
// var myConcat = function (arr1, arr2) {
// return arr1.concat(arr2);
// };
// ! This is can be converted into an arrow function with parameters
const myConcat = (arr1, arr2) => arr1.concat(arr2);
console.log(myConcat([1, 2], [3, 4, 5]));
111. Write Higher Order Arrow Functions
// arrow function work well with higher order functions such as map, filter, and reduce
// they take functions as arguments for processing collections of data
// ! Whenever one function takes another function as an argument, that's a good time for an arrow function
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
// we want to compute the square of only the positive integers in the array
const squareList = (arr) => {
const squaredIntegers = arr
.filter((num) => Number.isInteger(num) && num > 0)
.map((x) => x * x);
return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers); //(3) [16, 1764, 36]
112. Write Arrow Functions with Default Parameters
// in order to create more flexible functions you can use default parameters
// the default parameter kicks in when the argument is not specified or is undefined
const increment = (function () {
return function increment(number, value = 1) {
return number + value;
};
})();
console.log(increment(5, 3)); //8
console.log(increment(5)); //6
113. Use the Rest Operator with Function Parameters
// rest operator allows you to create a function that takes a variable number of arguments
// the following code adds up three different arguments
// const sum = (function () {
// return function sum(x, y, z) {
// const args = [x, y, z];
// return args.reduce((a, b) => a + b, 0);
// };
// })();
// console.log(sum(1, 2, 3));
// we can change this to use the rest operator
const sum = (function () {
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3, 4));
// ...args converts everything that's passed in into one array and the array is called as args
// so we don't need to declare it again
// we can also now add any number of numbers
114. Use the Spread Operator to Evaluate Arrays In-Place
// the spread operator looks just like the rest operator i.e. three dots ...
// but it expands an already existing array
// it spreads an array into its individual parts
// ! you can use it only in an argument to a function or in an array literal
const arr1 = ["JAN", "FEB", "MAR", "APR", "MAY"];
let arr2;
(function () {
arr2 = [...arr1]; // this is the spread operator
})();
console.log(arr2);
115. Use Destructuring Assignment to Assign Variables from Objects
// destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes they are more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and so on.
// this is a special syntax for neatly assignign variables taken drectly from an object to a variable
var voxel = { x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x;
var y = voxel.y;
var z = voxel.z;
// above was the traditional way
const { x: a, y: b, z: c } = voxel;
console.log(c);
const AVG_TEMPERATURES = {
today: 77.5,
tomorrow: 79,
};
function getTempOfTmrw(avgTemperatures) {
"use strict";
const { tomorrow: tempOfTomorrow } = avgTemperatures;
return tempOfTomorrow;
}
console.log(getTempOfTmrw(AVG_TEMPERATURES));
116. Destructuring Assignment with Nested Objects
// We can also use destructuring assignment to assign variables from nested objects
const LOCAL_FOREST = {
today: { min: 72, max: 83 },
tomorrow: { min: 73.3, max: 84.6 },
};
function getMaxOfTmrw(forecast) {
"use strict";
const {
tomorrow: { max: maxOfTomorrow },
} = forecast;
return maxOfTomorrow;
}
console.log(getMaxOfTmrw(LOCAL_FOREST)); //84.6
117. Use destructuring assignment to assign variables from arrays
// difference between destructuring from arrays and destructuring from objects is that you cannot specify which element from the array to go into a variable, it goes in order
const [z, x, , y] = [1, 2, 3, 4, 5, 6];
console.log(z, x, y);
// can use destructuring of arrays to switch the places of variables
let a = 8,
b = 6;
(() => {
"use strict";
[a, b] = [b, a];
})();
console.log(a);
console.log(b);
118. Using Destructuring Assignment with the Rest Operator
// we can use destructuring assignment with the rest operator to reassign array elements
// we want to return the array with the first two elements removed
const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function removeFirstTwo(list) {
const [, , ...arr] = list;
return arr;
}
const arr = removeFirstTwo(source);
console.log(arr); //[3, 4, 5, 6, 7, 8, 9, 10]
console.log(source);
119. Use Destructuring Assignment to Pass an Object as a Function’s Parameters
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85,
};
// const half = (function () {
// return function half(stats) {
// return (stats.max + stats.min) / 2;
// };
// })();
// instead of passing the entire stats in this function below, we can pass in what we need
const half = (function () {
return function half({ max, min }) {
return (max + min) / 2;
};
})();
// when the stats gets passed in, it's destructured into just the max and min variables
console.log(stats);
console.log(half(stats));
// this is commonly used with API Calls
// when you are getting information from an Ajax request or an API request, it will often have a lot more information that what you need
// you can use destructuring to get it down to what we actually want to work with
120. Create Strings using Template Literals
// template literals are a special type of string that makes creating complex strings easier
// begins and ends with back ticks
const person = {
name: "Zodiac Hasbro",
age: 56,
};
//template literal with multi-line and string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting);
// advantages: you can make multiline strings
// you can add single or double quotation marks right in the string
// you can put variables right in the string
// anything within the dollar sign and curly braces is JavaScript
// allows you to add variables right in the strings
// let's try a coding challenge using template literals
const result = {
success: ["max-length", "no-amd", "prefer-arrow-functions"],
failure: ["no-var", "var-on-top", "linebreak"],
skipped: ["id-blacklist", "no-dup-keys"],
};
function makeList(arr) {
const resultDisplayArray = [];
for (let i = 0; i < arr.length; i++) {
resultDisplayArray.push(`<li class="text-warning">${arr[i]}</li>`);
}
return resultDisplayArray;
}
const resultDisplayArray = makeList(result.failure);
console.log(resultDisplayArray);
121. Write Concise Object Literal Declarations Using Simple Fields
// const createPerson = (name, age, gender) => {
// return {
// name: name,
// age: age,
// gender: gender,
// };
// };
// console.log(createPerson("Zodiac Hasbro", 56, "male"));
const createPerson = (name, age, gender) => ({ name, age, gender });
console.log(createPerson("Zodiac Hasbro", 56, "male"));
122. Write Concise Declarative Functions
// an object can contain a function
// long way to do it
// const bicycle = {
// gear: 2,
// setGear: function (newGear) {
// "use strict";
// this.gear = newGear;
// },
// };
// bicycle.setGear(3);
// console.log(bicycle.gear);
// short way to do it
const bicycle = {
gear: 2,
setGear(newGear) {
"use strict";
this.gear = newGear;
},
};
bicycle.setGear(3);
console.log(bicycle.gear);
If you found the above article exciting or interesting or if you gained anything valuable from this, do me a favor, and leave a comment, or better, share it with your friends, family members, colleagues, batchmates, buddies, and your social circle!