Javascript (JS)

Fundamentals

console.log()

The console.log() method is used to log or print messages to the console. It can also be used to print objects and other info.

console.log('Hi there!'); // Prints: Hi there!

JavaScript

JavaScript is a programming language that powers the dynamic behavior on most websites. Alongside HTML and CSS, it is a core technology that makes the web run.

Methods

Methods return information about an object, and are called by appending an instance with a period ., the method name, and parentheses.

// Returns a number between 0 and 1 Math.random();

Built-in Objects

Built-in objects contain methods that can be called by appending the object name with a period ., the method name, and a set of parentheses.

Math.random(); // ☝️ Math is the built-in object

Numbers

Numbers are a primitive data type. They include the set of all integers and floating point numbers.

let amount = 6; let price = 4.99;

String .length

The .length property of a string returns the number of characters that make up the string.

let message = 'good nite'; console.log(message.length); // Prints: 9 console.log('howdy'.length); // Prints: 5

Data Instances

When a new piece of data is introduced into a JavaScript program, the program keeps track of it in an instance of that data type. An instance is an individual case of a data type.

Booleans

Booleans are a primitive data type. They can be either true or false.

let lateToWork = true;

Math.random()

The Math.random() method returns a floating-point, random number in the range from 0 (inclusive) up to but not including 1.

console.log(Math.random()); // Prints: 0 - 0.9999999999999999

Math.floor()

The Math.floor() function returns the largest integer less than or equal to the given number.

console.log(Math.floor(5.95)); // Prints: 5

Single Line Comments

In JavaScript, single-line comments are created with two consecutive forward slashes //.

// This line will denote a comment

Null

Null is a primitive data type. It represents the intentional absence of value. In code, it is represented as null.

let x = null;

Strings

Strings are a primitive data type. They are any grouping of characters (letters, spaces, numbers, or symbols) surrounded by single quotes ' or double quotes ".

let single = 'Wheres my bandit hat?'; let double = "Wheres my bandit hat?";

Arithmetic Operators

JavaScript supports arithmetic operators for:

  • + addition
  • - substraction
  • * multiplication
  • / division
  • % modulo
// Addition 5 + 5 // Subtraction 10 - 5 // Multiplication 5 * 10 // Division 10 / 5 // Modulo 10 % 5

Multi-line Comments

In JavaScript, multi-line comments are created by surrounding the lines with /* at the beginning and */ at the end. Comments are good ways for a variety of reasons like explaining a code block or indicating some hints, etc.

/* The below configuration must be changed before deployment. */ let baseUrl = 'localhost/taxwebapp/country';

Remainder / Modulo Operator

The remainder operator, sometimes called modulo, returns the number that remains after the right-hand number divides into the left-hand number as many times as it evenly can.

// calculates # of weeks in a year, rounds down to nearest integer const weeksInYear = Math.floor(365/7); // calcuates the number of days left over after 365 is divded by 7 const daysLeftOver = 365 % 7 ; console.log("A year has " + weeksInYear + " weeks and " + daysLeftOver + " days");

Assignment Operators

An assignment operator assigns a value to its left operand based on the value of its right operand. Here are some of them:

  • += addition assignment
  • -= substraction assignment
  • *= multiplication assignment
  • /= division assignment
let number = 100; // Both statements will add 10 number = number + 10; number += 10; console.log(number); // Prints: 120

String Interpolation

String interpolation is the process of evaluating string literals containing one or more placeholders (expressions, variables, etc).

It can be performed using template literals: text ${expression} text.

let age = 7; // String concatenation 'Tommy is ' + age + ' years old.'; // String interpolation `Tommy is ${age} years old.`;

Variables

Variables are used whenever there’s a need to store a piece of data. A variable contains data that can be used in the program elsewhere. Using variables also ensures code re-usability since it can be used to replace the same value in multiple places.

const currency = '$'; let userIncome = 85000; console.log(currency + userIncome + ' is more than the average income.'); // Prints: $85000 is more than the average income.

Undefined

undefined is a primitive JavaScript value that represents lack of defined value. Variables that are declared but not initialized to a value will have the value undefined.

var a; console.log(a); // Prints: undefined

Learn Javascript: Variables

A variable is a container for data that is stored in computer memory. It is referenced by a descriptive name that a programmer can call to assign a specific value and retrieve it.

// Examples of variables let name = "Tammy"; const found = false; var age = 3; console.log(name, found, age); // Prints: Tammy false 3

Declaring Variables

To declare a variable in JavaScript, any of these three keywords can be used along with a variable name:

  • var is used in pre-ES6 versions of JavaScript.
  • let is the preferred way to declare a variable when it can be reassigned.
  • const is the preferred way to declare a variable with a constant value.
var age; let weight; const numberOfFingers = 20;

Template Literals

Template literals are strings that allow embedded expressions, ${expression}. While regular strings use single ' or double " quotes, template literals use backticks instead.

let name = "Codecademy"; console.log(`Hello, ${name}`); // Prints: Hello, Codecademy console.log(`Billy is ${6+8} years old.`); // Prints: Billy is 14 years old.

let Keyword

let creates a local variable in JavaScript & can be re-assigned. Initialization during the declaration of a let variable is optional. A let variable will contain undefined if nothing is assigned to it.

let count; console.log(count); // Prints: undefined count = 10; console.log(count); // Prints: 10

const Keyword

A constant variable can be declared using the keyword const. It must have an assignment. Any attempt of re-assigning a const variable will result in JavaScript runtime error.

const numberOfColumns = 4; numberOfColumns = 8; // TypeError: Assignment to constant variable.

String Concatenation

In JavaScript, multiple strings can be concatenated together using the + operator. In the example, multiple strings and variables containing string values have been concatenated. After execution of the code block, the displayText variable will contain the concatenated string.

let service = 'credit card'; let month = 'May 30th'; let displayText = 'Your ' + service + ' bill is due on ' + month + '.'; console.log(displayText); // Prints: Your credit card bill is due on May 30th.

Functions

Arrow Functions (ES6)

Arrow function expressions were introduced in ES6. These expressions are clean and concise. The syntax for an arrow function expression does not require the function keyword and uses a fat arrow => to separate the parameter(s) from the body.

There are several variations of arrow functions:

  • Arrow functions with a single parameter do not require () around the parameter list.
  • Arrow functions with a single expression can use the concise function body which returns the result of the expression without the return keyword.
// Arrow function with two parameters const sum = (firstParam, secondParam) => { return firstParam + secondParam; }; console.log(sum(2,5)); // Prints: 7 // Arrow function with no parameters const printHello = () => { console.log('hello'); }; printHello(); // Prints: hello // Arrow functions with a single parameter const checkWeight = weight => { console.log(`Baggage weight : ${weight} kilograms.`); }; checkWeight(25); // Prints: Baggage weight : 25 kilograms. // Concise arrow functions const multiply = (a, b) => a * b; console.log(multiply(2, 30)); // Prints: 60

Functions

Functions are one of the fundamental building blocks in JavaScript. A function is a reusable set of statements to perform a task or calculate a value. Functions can be passed one or more values and can return a value at the end of their execution. In order to use a function, you must define it somewhere in the scope where you wish to call it.

The example code provided contains a function that takes in 2 values and returns the sum of those numbers.

// Defining the function: function sum(num1, num2) { return num1 + num2; } // Calling the function: sum(3, 6); // 9

Anonymous Functions

Anonymous functions in JavaScript do not have a name property. They can be defined using the function keyword, or as an arrow function. See the code example for the difference between a named function and an anonymous function.

// Named function function rocketToMars() { return 'BOOM!'; } // Anonymous function const rocketToMars = function() { return 'BOOM!'; }

Function Expressions

Function expressions create functions inside an expression instead of as a function declaration. They can be anonymous and/or assigned to a variable.

const dog = function() { return 'Woof!'; }

Function Parameters

Inputs to functions are known as parameters when a function is declared or defined. Parameters are used as variables inside the function body. When the function is called, these parameters will have the value of whatever is passed in as arguments. It is possible to define a function without parameters.

// The parameter is name function sayHello(name) { return `Hello, ${name}!`; }

return Keyword

Functions return (pass back) values using the return keyword. return ends function execution and returns the specified value to the location where it was called. A common mistake is to forget the return keyword, in which case the function will return undefined by default.

// With return function sum(num1, num2) { return num1 + num2; } // Without return, so the function doesn't output the sum function sum(num1, num2) { num1 + num2; }

Function Declaration

Function declarations are used to create named functions. These functions can be called using their declared name. Function declarations are built from:

  • The function keyword.
  • The function name.
  • An optional list of parameters separated by commas enclosed by a set of parentheses ().
  • A function body enclosed in a set of curly braces {}.
function add(num1, num2) { return num1 + num2; }

Calling Functions

Functions can be called, or executed, elsewhere in code using parentheses following the function name. When a function is called, the code inside its function body runs. Arguments are values passed into a function when it is called.

// Defining the function function sum(num1, num2) { return num1 + num2; } // Calling the function sum(2, 4); // 6

Iterators

Functions Assigned to Variables

In JavaScript, functions are a data type just as strings, numbers, and arrays are data types. Therefore, functions can be assigned as values to variables, but are different from all other data types because they can be invoked.

let plusFive = (number) => { return number + 5; }; // f is assigned the value of plusFive let f = plusFive; plusFive(3); // 8 // Since f has a function value, it can be invoked. f(9); // 14

Callback Functions

In JavaScript, a callback function is a function that is passed into another function as an argument. This function can then be invoked during the execution of that higher order function (that it is an argument of).

Since, in JavaScript, functions are objects, functions can be passed as arguments.

const isEven = (n) => { return n % 2 == 0; } let printMsg = (evenFunc, num) => { const isNumEven = evenFunc(num); console.log(`The number ${num} is an even number: ${isNumEven}.`) } // Pass in isEven as the callback function printMsg(isEven, 4); // Prints: The number 4 is an even number: True.

Higher-Order Functions

In Javascript, functions can be assigned to variables in the same way that strings or arrays can. They can be passed into other functions as parameters or returned from them as well.

A “higher-order function” is a function that accepts functions as parameters and/or returns a function.

JavaScript Functions: First-Class Objects

JavaScript functions are first-class objects. Therefore:

  • They have built-in properties and methods, such as the name property and the .toString() method.
  • Properties and methods can be added to them.
  • They can be passed as arguments and returned from other functions.
  • They can be assigned to variables, array elements, and other objects.
//Assign a function to a variable originalFunc const originalFunc = (num) => { return num + 2 }; //Re-assign the function to a new variable newFunc const newFunc = originalFunc; //Access the function's name property newFunc.name; //'originalFunc' //Return the function's body as a string newFunc.toString(); //'(num) => { return num + 2 }' //Add our own isMathFunction property to the function newFunc.isMathFunction = true; //Pass the function as an argument const functionNameLength = (func) => { return func.name.length }; functionNameLength(originalFunc); //12 //Return the function const returnFunc = () => { return newFunc }; returnFunc(); //[Function: originalFunc]

The .reduce() Method

The .reduce() method iterates through an array and returns a single value.

In the above code example, the .reduce() method will sum up all the elements of the array. It takes a callback function with two parameters (accumulator, currentValue) as arguments. On each iteration, accumulator is the value returned by the last iteration, and the currentValue is the current element. Optionally, a second argument can be passed which acts as the initial value of the accumulator.

const arrayOfNumbers = [1, 2, 3, 4]; const sum = arrayOfNumbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; }); console.log(sum); // 10

The .forEach() Method

The .forEach() method executes a callback function on each of the elements in an array in order.

In the above example code, the callback function containing a console.log() method will be executed 5 times, once for each element.

const numbers = [28, 77, 45, 99, 27]; numbers.forEach(number => { console.log(number); });

The .filter() Method

The .filter() method executes a callback function on each element in an array. The callback function for each of the elements must return either true or false. The returned array is a new array with any elements for which the callback function returns true.

In the above code example, the array filteredArray will contain all the elements of randomNumbers but 4.

const randomNumbers = [4, 11, 42, 14, 39]; const filteredArray = randomNumbers.filter(n => { return n > 5; });

The .map() Method

The .map() method executes a callback function on each element in an array. It returns a new array made up of the return values from the callback function.

The original array does not get altered, and the returned array may contain different elements than the original array.

In the example code above, the .map() method is used to add ' joined the contest.' string at the end of each element in the finalParticipants array.

const finalParticipants = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby']; // add string after each final participant const announcements = finalParticipants.map(member => { return member + ' joined the contest.'; }) console.log(announcements);

Requests

JSON-Formatted Response Body

The .json() method will resolve a returned promise to a JSON object, parsing the body text as JSON.

In the example code, the .json() method is used on the response object which returns a promise to a JSON-formatted response body as jsonResponse.

fetch('url') .then( response => response.json() ).then(jsonResponse => { console.log(jsonResponse); });

HTTP GET Request

HTTP GET requests are made with the intention of retrieving information or data from a source (server) over the web.

GET requests have no body, so the information that the source requires, in order to return the proper response, must be included in the request URL path or query string.

The fetch() Function

The JavaScript Fetch API is used to write HTTP requests using Promises. The main fetch() function accepts a URL parameter and returns a promise that resolves to a response object or rejects with an error message if a network error occurs.

The example code begins by calling the fetch() function. Then a then() method is chained to the end of the fetch(). It ends with the response callback to handle success and the rejection callback to handle failure.

fetch('url') .then( response => { console.log(response); }, rejection => { console.error(rejection.message); );

Customizing Fetch Requests

The fetch() function accepts an optional second argument, an options object, used to customize the request. This can be used to change the request type, headers, specify a request body, and much more.

In the example code below, the fetch() function as a second argument—an object containing options for the fetch request specifying the method and the body.

fetch('https://api-to-call.com/endpoint', { method: 'POST', body: JSON.stringify({id: "200"}) }).then(response => { if(response.ok){ return response.json(); } throw new Error('Request failed!'); }, networkError => { console.log(networkError.message); }).then(jsonResponse => { console.log(jsonResponse); })

HTTP POST Request

HTTP POST requests are made with the intention of sending new information to the source (server) that will receive it.

For a POST request, the new information is stored in the body of the request.

Using async…await with Fetch

The async…await syntax is used with the Fetch API to handle promises.

In the example code, the async keyword is used to make the getSuggestions() function an async function. This means that the function will return a promise. The await keyword used before the fetch() call makes the code wait until the promise is resolved.

const getSuggestions = async () => { const wordQuery = inputField.value; const endpoint = `${url}${queryParams}${wordQuery}`; try{ const response = await fetch(endpoint, {cache: 'no-cache'}); if(response.ok){ const jsonResponse = await response.json() } } catch(error){ console.log(error) } }