Javascript Technical Interview (Theory)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Script paths

./filename is a relative path meaning the ./ means it's in the current directory of the file where the relative path is written. If it's in another folder, you would change the path to be ./folder/filename When importing you can use ../folder/filename - the ../ means to go up one level (where the folder maybe)

map(); method

This method applies the same code for every value in an array and returns a new array. Ex.) const numbers = [1,2,3]; const doubledNumber = numbers.map((number) => { return number *2; [the condition] }); console.log(doubledNumber); result - [2,4,6] every value * 2

Named Export

This should be used when you want to export multiple values. You should put the name in curly brackets without writing default. You must use the same name when importing. Ex.) const dog1 = new Dog("Lego"); const dog2 = new Dog("Meno"); export { dog1, dog2 } import { dog1, dog2 } from "./dogData"; dog1.info(); dog2.info();

filter(); method

To get all the values that match the condition you can use the filter method. It'll return a new array with all the matching values. Ex.) const numbers = [1,3,5,7]; const filterNumber = numbers.find((number) => { return number > 3; [the condition] }); console.log(filterNumber); result - [5,7]

Override Methods

When a method that has the same name as a method in the parent class is defined in the child class, the child class method is used. The child class overrides the parent class method. Ex.) class Animal { info(){ } } class Dog extends Animal{ info(){ } } The Dog child class inherits the properties of the Animal parent class BUT even those they have two methods with the same name, the child method would be used because it override the parent's method of the same name.

Inheritance

When creating a class you can use inheritance to have the a child class inherit from a parent class. Ex.) //here the class Dog inherits the attributes of Animal class Dog extends Animal { } This means you can use any method defined in the parent class

Default Export

With default export, when a file is imported, the export default value is automatically imported which means the value name when exporting and importing can be different. A default export can only be used for one value in one file. Since the default export value will automatically be imported when importing the file, only one value is allowed. Ex.) const dog = new Dog("Leo"); export default dog; import doggy from "./filename"; doggy.info(); doggy doesn't match the dog export name but it still works

Callback function

a function specified as part of an event listener; it is written by the programmer but called by the system as the result of an event trigger.

Accumulator Pattern

a pattern is a chunk of code that you see repeated in the code script that you're working on. A pattern is not code that is duplicated exactly. Rather, it's code that repeats the same pattern. The accumulator pattern is a method of building up or accumulating data.

Classes

class Animal { } const animal = new Animal(); It's like a blueprint that can be used with many instances. You can create an object from a class, they are called instances.

Importing a Javascript file to be used in another file

import className from "./filename"; You can import any kind of value, strings, integers, or even functions can be imported. Ex.) (A variable name imported) Ex.) import text from "./sample1";

While Loop Explained

let number = 1; while (condition){ code }

Template Literals

An alternative sign other than the plus sign to combing strings and constants. Template literals allow you to embed constants (Variables) inside a string. Example: const name = "Ken the Ninja"; console.log(`Hello,Mr. ${name} `); Ex.2) console.log(`Today I am ${age} years old`); (You have to encase it on ` backticks)

Exporting a Javascript file to be used in another file

Class className { } Ex.) export default className; You can export any kind of value, strings, integers, or even functions can be exported. Ex.) (A variable exported) const text = "Hello World"; export default text;

Construtor

Classes often have a special method called a constructor, the constructor gives the initial values to new instances. To add a constructor to a class: Ex.) class Animal { construtor(){ console.log("Hello!"); } } You can also add properties and values Ex. class Animal { construtor(){ this.name = "Leo"; } } const animal = new Animal(); console.log(animal.name);

Override Constructors

Constructors can be overridden the same way as methods. When overriding constructors you must add super() in the first line. Parent class ParentClass{ constructor(name,age){ this.name = name; this.age= age; } } Ex.) class ChildClass extends ParentClass{ constructor(){ super(name,age); this.breed = breed; //code here } } It will run the parent's this.name and this.age from the original parent class but also run the newly added this.breed

Construtor Arguments

Ex.) class Animal { construtor(name,age){ this.name = name; this.age = age; } } const animal = new Animal("Leo",3);

Functions that belong to a class are called Methods.

Ex.) class Animal { construtor(name,age){ } greet(){ //method console.log("Hello!"); } } const animal = new Animal("Leo",3); animal.greet();

Importing packages

Packages are code open and publicly available. Ex.) import constantName from "packageName"; (using it in the same file) console.log(constantName.instruction(" ")); After importing, you will be able to use the package in the file.

Switch Statement

Switch statements are a different way of control flow. You can use switch statements when the code branches off depending on certain values. Ex.) const color= "red"; switch (color){ case "red": console.log("Stop!"); break; switch (color){ case "yellow": console.log("Slow down"); break; default: console.log("Oop"); break; }

Method fine

The find method gets the first value from the array that matches the given conditional expression. Ex.) const numbers = [1,3,5,7]; const foundNumber = numbers.find((number) => { return number > 3; [the condition] }); console.log(foundNumber); result - 5 This would return the first element that matches the condition. You can also use it with arrays to return the entire object that contains the matching property.

&& (and)

&& evaluates to true if the values on both sides are true. // and (Do both sides evaluate to `true`?) true && true;// returns true true && false; // returns false false && true; // returns false

multi-line comment

(/*) this is a longer, multi-line comment (*/)

Finding length of string

// Get the length of a string "Hello".length; // 5 let longWord = "supercalifragilisticexpialidocious"; longWord.length; // 34 It's an example of a property, when you access properties, like determining string length with .length, you're not actually changing the string. You're simply gathering data about the string, like how long it is.

you can overwrite variables

// Overwriting variables // Set the variable 'coding' to "weird" let coding = "weird"; // Print the variable 'coding' to your console console.log("coding is " + coding); //-> "coding is weird" // Set 'coding' to "cool and fun" coding = "cool and fun"; // Print the variable 'coding' to your console again console.log("coding is " + coding); //-> "coding is cool and fun" let dogAge = 6; dogAge = 7;

Truthy and Falsy Values

// Values that evaluate to `false` false; // `false` itself ""; // Empty string 0; // Zero null; undefined; NaN; // Not a number Each of these values gets treated as false if it's in an if statement, or whenever JavaScript is looking for a boolean (like with the ! operator). if the value isn't false, "", 0, null, undefined, or NaN, it's coerced to true. In other words, everything else will evaluate to true, even if the value looks "empty" to you. That includes strings with just a space inside them, like " ", as well as negative numbers like -8. Believe it or not, those are both treated as true!

one-line comment

// a one-line comment

function camelize

// camelCasing // Feel free to change the function input so you // can see how the functions camel-cases the input you give it!. // Example inputs: camelize("I like camels"); camelize("camelize-me-please"); // Try your examples below! // DO NOT MODIFY FUNCTION BELOW // Function for camelizing input. function camelize(text) { let camelizedText = text.replace(/^([A-Z])|[\s-_]+(\w)/g, function(match, p1, p2, offset) { if (p2) return p2.toUpperCase(); return p1.toLowerCase(); }); console.log(camelizedText); }

Data Types

A data type is a value that variables can have in a given programming language. Different kinds of data types can do different tasks. For instance, numbers can be added and multiplied. Text can also be combined together using the + operator—in other words, you can use the + to stick one piece of text on the end of the other. But you can't multiply text. JavaScript has eight data types. But for now, you'll focus on the five most common kinds: String Number Boolean Null Undefined These five data types (booleans, numbers, strings, nulls, and undefined) are sometimes referred to as primitives.

Are zip codes and telephone numbers are string data types

A number doesn't always represent a number data type. In other words, some numbers act like characters, not numbers, and have a text value rather than a numerical value. Zipcodes and Telephone Numbers - These values would likely be stored in strings, not numbers. You don't add or multiply zip codes, so they aren't really acting like numbers, per se.

Accessing a nested object

Access to nested objects uses the same dot or bracket notation. The notation is chained for each property until it gets to a property with a primitive data type. university.programs.science.enrollment // 2000 Dot and bracket notation can also be combined to access or set nested object properties: university["programs"]["computer science"].dean // "Sofia Patel" university.programs.science["enrollment"] = 2000;

Function vs Method

All of those are functions. They're sets of instructions that you can run when you want. When you use parentheses after the function's name, JavaScript jumps to those instructions and follows them one by one. Functions like toLowerCase() and pop() are built into JavaScript. Methods are built in compared to functions that we make.

Objects

An object is a type of collection that holds information, just like an array. But instead of operating like a storage box, an object can be represented using another analogy. Objects are like a collection of gifts that need to be handed out to a group of people. This analogy captures the structure of an object. An object holds many values (represented by the gifts), and each value has a unique key (represented by the gift tags). Try modeling the gift example below using an object. // An example of an object let gifts = { tommy: "stuffed giraffe", lisa: "coloring book", roberto: "baseball cap", beth: "suit of armor", }; JavaScript object has keys or properties holding values. Objects are a different data type than the other five data types in Javascript. The other five data types (booleans, numbers, strings, nulls, and undefined) are sometimes referred to as primitives. Objects are a complex data type because objects can contain other variables as properties, including other complex data types like objects, arrays, and functions.

Nested objects

An object that is a property of another object is referred to as a nested object. In this example, programs is nested under university. And science is nested under programs. let university = { name: "State University", programs: { "science": { credits: 100, enrollment: 2000, dean: "Juanita Doe" }, "computer science": { credits: 120, enrollment: 2400, dean: "Sofia Patel" } } }

Arrays

Arrays are collections of ordered items. it helps you organize many items by storing each item in a specific numbered slot. You can then return to those slots as needed, and you know that they're storing whatever data or information you've put there. And in JavaScript, there's an added bonus: an array can have as many slots as you want! Arrays must be structured in a particular way. The square brackets [ and ] show where the array starts and ends. A comma , separates each item in the array, but there's no comma after the last item.

Types of Arrays

Arrays are created with zero or more elements. Arrays can contain any data type—including other arrays. Take a look at these examples below. let listOfPuppies = ["shadow", "mocha", "ranger"]; let emptyArray = []; let puppyAges = [0, 1, 2]; let puppyAgeDescriptions = ["two months", "thirteen months", 2]; // we can mix strings and numbers! let puppiesAndAges = [ ["shadow", "mocha", "ranger"], [0, 1, 2] ]; // arrays inside arrays!

Nesting data

Arrays can have objects inside them. Objects can also have arrays inside. Arrays can have arrays inside, and objects can have other objects inside too. When there are "things inside things," that's called nesting. You might hear someone talk about nested arrays or nested objects. The syntax for accessing nested objects is sometimes confusing to follow. It can help to break it down piece by piece.

meaningful variable names

As the codebase grows and more developers collaborate on projects, creating meaningful variable names becomes a necessity. If every variable has a name like x and y and foo, you and your fellow developers won't know what those variables actually stand for. But if your variables have more specific names, like age, location, and phoneNumber, it'll be easier to read and understand your variables. And you'll have a much better sense of what your code is doing.

Function Syntax

As you can see, function declarations have a few key parts: Function keyword: Before creating the function, you need to give JavaScript a heads-up. Just like you define variables by using the keyword let, you define functions by using the keyword function. Identifier: You give the function a name. This is how you'll refer to the function later. Parameters: You put the names of any parameters in between parentheses. If there are no parameters, leave the parentheses empty, like (). This is the function's input. Function body: The body of the function goes inside curly brackets {}. This is a list of instructions; it's what the function will do. Return statement: You use the return keyword for the function's output. Remember, the function's output is what the function sends back. Keep the following in mind: Functions stop running when they see return. Functions can only return one value. If they don't use return, then by default, they return undefined. After the function is declared, you can use it via the following elements: Function call: You run the function using the name and parentheses, like bakeCake(). You can say that you run, call, or invoke the function. Arguments: When you invoke a function, you pass in values between the parentheses, like favoriteFood("pizza"). In this case, "pizza" is the argument; in other words, it's the input to the function.

Booleans

Booleans signify true and false. They are used to represent logic in programs. They have two possible values: true or false.

comparison operator ==

Check if two items are equal to each other using the triple equals operator: ==. This is a comparison operator. If you compare items with different types, it will not necessarily return false. For example, if you try comparing a number to a string, it will attempt to coerce the string into a number, like this: 7 === "7"; // false 7 == "7"; // true The == operator turns the string "7" into the number 7 before checking whether the values are equal.

comparison operator ===

Check if two items are equal to each other using the triple equals operator: ===. This is a comparison operator. 7 === 7; // true 7 === 8; // false "mysafepassword" === "mysafepassword"; // true "mysafepassword" === "not my password"; // false If you try comparing two things with different data types, === will return false. Triple equals (===) is called strict equality checking, because it's predictable and you know what you're working with; it's not loose like ==. Many developers find it easier to stick to ===, because you don't need to think about a data type conversion under the hood.

Object Bracket notation (Accessing Object)

Dot notation won't always work. You'll sometimes need to use bracket notation when the key you wish to access is a string with a space in it // Getting information out of an object let categories = { 'best picture': 'Shrek', 'best director': 'Shrek 2' }; // You can't do these categories.best director; categories.best picture; // So use bracket notation instead categories['best picture']; // 'Shrek' categories['best director']; // 'Shrek 2' You can see that the notation that works here is objectName[key] because there are spaces in the key 'best picture' and 'best director'. And as you might've noticed, using bracket notation looks a lot like accessing values in an array, except that you can use names instead of numbers.

Functions and scope

Each time that you call a function, it creates a little bubble for the variables inside. The values are only "visible" inside the function. Outside the function, those names disappear. Scope is the little bubble—the one that contains the variables that are visible inside your function When you try to access a variable that's not in scope, you get a ReferenceError. If you see a ReferenceError, it either means that you haven't defined the variable anywhere, or it's not visible where you're trying to use it. Every variable has a scope. You've already learned one rule: variables created inside a function are only visible inside the function. Outside of functions, all the variables go in one big scope called the global scope. Nested functions can see the variables in the scope that encloses them—not just the variables in the global scope. Each time that you call the function, it creates a new scope. When the function ends, that scope disappears. Function parameters act like variables created inside a function. They get assigned to the values passed in, and they disappear when the function ends.

Conditional Branching

Essential concept in programming. It's when you make conditions for when to run certain code.

Do methods change the original string?

Even with these methods applied, the original string doesn't actually change. Instead of changing the original string, the methods "turn into" a new value. These new values are being created and stored in the code, but they don't affect the original string. It's as if each piece of code is being swapped out for the result. Ex.) let loudText = "WHAT A BEAUTIFUL DAY"; loudText.toLowerCase(); console.log(loudText); // WHAT A BEAUTIFUL DAY console.log(loudText.toLowerCase()); // what a beautiful day Because there's no assignment operator = on the second line, the variable loudText is still holding onto "WHAT A BEAUTIFUL DAY", which is entirely capitalized. To fix the code so that it logs the lowercase version, the variable needs to be reassigned with a =, as seen below. let loudText = "WHAT A BEAUTIFUL DAY"; loudText = loudText.toLowerCase(); console.log(loudText); // what a beautiful day

Getting Object Values with Arrays

Ex.) const items = [ {name:"Ken",price:20}, {name:"Barb",price:30} ]; arrayName[indexNumber].propertyName Ex.) items[1].price = 30

.forEach() method

Ex.) const numbers = [1,2,3] numbers.forEach((number) => {console.log(number)}) this would print out each number, using the console log 1 2 3

Switch statement explained

Ex.) switch(conditional value){ case value1: when the conditional value is equal to value1 break; case value2: when the conditional value is equal to value2 break; default: break; } case is the different cases break is the end the switch otherwise it's an endless loop default is if no case matches then it goes to that code

Function Parameters and arguments

Example: function favoriteFood(food) { console.log("My favorite food is " + food); } The (food) is a placeholder, these placeholders are called parameters. When you run the function later on, you can fill in the placeholder. The values that fill in the placeholders are called arguments favoriteFood("pizza"); favoriteFood("mac and cheese"); favoriteFood("pickled herring"); favoriteFood("sunflower seeds"); //pizza and the others are arguments When you run the function then it's as if you had said: let food = "pizza"; console.log("My favorite food is " + food); If you were to run it then it would say: My favorite food is pizza My favorite food is mac and cheese My favorite food is pickled herring My favorite food is sunflower seeds

Functions with multiple parameters

Functions can have more than one parameter: function leftAndRight(left, right) { console.log(left + " is on the left"); console.log(right + " is on the right"); } When you call the function, the values get filled in in the same order as the definition. For example, take a look at the following function call: leftAndRight("A dog", "A cat"); //=> A dog is on the left //=> A cat is on the right "A dog" gets assigned to left and "A cat" gets assigned to right. JavaScript doesn't limit how many parameters you can have, but your code can get pretty confusing if you have a lot.

Return stops the code

Functions can return only one value. JavaScript stops when it sees return, so anything after return doesn't run. function tryToReturnTwice() { return "first"; // This never runs: return "second"; }

Function

Functions wrap up code and give it a name so that you can use it in other places. When you hear that "functions are the building blocks of programs," that's what it means—you make big programs by composing functions and arranging them together. You can use functions to do the following: -Reuse code -Transform inputs into outputs -Solve pieces of a problem Comments, variables, data types, conditionals, and loops—you can use them all inside functions. (You can even use functions inside other functions - function goToSchool() { walkToBusStop(); rideTheBus(); walkTheRestOfTheWay(); }

Function Scope rules

Here's a summary of the scope rules that you've learned so far: - Every variable is part of a scope. - If the variable is created outside of any function, it's stored in the global scope. - Variables in the global scope are visible everywhere. - Each time that a function is called, it creates a new scope. - If the variable is created inside a function, it gets stored inside the function's scope. - Variables in a function scope are only visible inside the function. - The function scope disappears when the function ends. - Parameters get assigned function scope, as if they were variables created inside the function. - Parameters get assigned the values from the arguments when the function is called.

if block

If the condition is true, the code in the block is executed. Because if deals with conditions, it's called a conditional statement. It tells the code to perform different tasks based on different kinds of information. let userLoggedInToday = true; if (userLoggedInToday) { console.log("Thanks for logging in today!"); } the code inside the block—which is marked off by the curly brackets {...}—runs only if the condition in the () is true. And in fact, userLoggedInToday is true here, so the console.log() statement will run. If it's false then the code won't run (let userLoggedInToday = false;)

else if

If you have multiple conditions that you want to check, you can use if ... else if ... else to check them one after the other. Ex.) let loginCount = 3; if (loginCount > 10) { console.log("That's a lot of logins today, champ! Maybe give it a rest."); } else if (loginCount > 0) { console.log("Thanks for logging in!"); } else { console.log("Don't forget to log in today"); } Instead of only providing an else block, you can make another decision. In this example, there are three branches to the condition.

Converting Data Types

If you want to combine an expression involving numbers and an expression involving text. In this case, you can use the + operator in JavaScript to convert the numeric values into string values and combine the expressions into a string. Ex.) let stringVar = 'Life was simpler when I was ' let numVar = 12 let combined = stringVar + numVar console.log(typeof(combined)) // => 'string' console.log(combined) // => Life was simpler when I was 12

increment and decrement operators

Increase/decrease the value of a variable by a particular amount. Addition: x += 1 will accomplish x = x + 1. Subtraction: x -= 2 will accomplish x = x - 2. Multiplication: x *= 5 will accomplish x = x * 5. To increment or decrement by one, do: x++ x---

camelCasing

It's best practice to start the variable in lowercase (if it's one word then have the entire word in lowercase) thisIsCamelCasing; alsoThisIsCamelCasing; andThisIsToo; camelCasingIsFun; youWillCamelCaseToo;

Converting Strings to Numbers

JavaScript provides two commands to help developers with this task. Both begin with parse, which is a command that scans the string and returns the information you're looking for. But the two parse commands differ in what kind of information they're looking for. You'd pick the parse that you need based on the kind of number you want to retrieve.

For Loop

Loops are used to run through a set of instructions in the code a specific number of times. With a loop, you can tell the code to perform the same task, or series of tasks, multiple times. for(variable;condition;update){ code.. } / An example of a `for` loop let countTo = 5; for (let step = 1; step <= countTo; step++) { console.log(step); } Starting at step = 1, you can follow along: Check if step is less than or equal to the value of countTo (5). Log the value of step. Increase step by one. Then repeat this code.

Logical operators

Made to handle several conditions at once. They combine boolean values so that you can express more complex ideas in code, like this condition and that condition, this condition or that condition, and this condition but not that condition. The and, or, and not logical operators tell the code how to work with various pieces of information simultaneously. In JavaScript, the three logical operators are written as follows: && (and), || (or), and ! (not). let userLoggedIn = true; let userPurchasedItem = false; // Test if both values are `true` userLoggedIn && userPurchasedItem; // => false // Test if either value is `true` userLoggedIn || userPurchasedItem; // => true // Invert the value of a variable !userLoggedIn; // => false !userPurchasedItem; // => true

Null

Null is a data type that's used to indicate that a variable has no value. A null value means that the developer decided that the value was empty. It was a deliberate choice. // Examples of null and undefined let example = null; example; // null (This is a choice to intentionally make it empty compared to undefined)

Object Syntax

Objects start and end with curly brackets: the { and }. Keys must be a string data type, but they can be any string. A colon : sits between each key and the value it points to, and a comma , separates key: value pairs. Unlike keys, values can be any data type. They can be a number, an array, a boolean value, null, or even another object. Any JavaScript data type can be a value. Take a look at the example below. Ex.) let variable = { key: "value", keyTwo: 10, keyThree: ["value1" , "value2", "value3"], keyFour: true, };

Object Dot notation (Accessing Object)

Once an object is defined, you can get the values inside it using either dot notation or bracket notation. Dot notation is the most common method for retrieving values from inside an object, and it looks like this: objectName.key. let actionFigure = { name: "Super Awesome Guy", heightInCentimeters: 10, accessories: ["cape", "disguise", "laser ring"], limitedEdition: true, }; actionFigure.name; // 'Super Awesome Guy' actionFigure.limitedEdition; // true console.log(actionFigure.heightInCentimeters); // 10

Adding a new key-value pairs to an object

Once you've defined an object, you can add new key-value pairs to the object using either dot notation or bracket notation. // Adding a new key-value pair let myFamily = { mom: "Cynthia", dad: "Paul", }; myFamily.sister = "Lucinda"; // Dot notation myFamily["brother in law"] = "Merle"; // Bracket notation

Order of operations

PEMDAS in math class. (Usually, there was a mnemonic acronym, too: "Please Excuse My Dear Aunt Sally.") PEMDAS is a simple tool that outlines the correct order of operations. Parentheses Exponents Multiplication Division Addition Subtraction

! (not)

Pronounced not or bang, ! inverts a boolean value. This means that !false turns into true, and !true turns into false. ! works on just one value, and gives the opposite of a value. Therefore, !true evaluates to false, and !false evaluates to true. // not (Return the inverse) !true; // returns false !false; // returns true

Strings

Strings are used to represent text. The data type is called a string because it's made up of a string of characters, such as letters, that are arranged in a line. In JavaScript, the syntax for a string is a series of characters inside quotation marks. The quotes can be either single ' or double ". But you must use the same type of quotation mark at the beginning and the end of a string. // Declare a string with quotes let city = "Seattle"; let state = "Washington"; let str = "nine"; // str is a string let str = "9"; // str is a string let str = 9; // str is a number (not good for a variable called 'str' to be a number!) let str = nine; // error 'nine is not defined' --> the computer doesn't know how to deal with the word nine because it isn't in quotes

Short-circuiting

The && and || operators are actually slightly more complicated because of a behavior called short-circuiting. This means that when JavaScript sees that the first value of an && expression is falsy, it can stop there. And it does! false && console.log("this will not be printed"); Similarly, the code stops early if the first value of the || operator is truthy. This variation of short-circuiting can be seen below. true || console.log("this will not be printed"); With this concept in mind, consider these "revised" rules for && and ||: && (and) returns the first falsy value, or the last value if no values are falsy. || (or) returns the first truthy value, or the last value if no values are truthy.

Methods

The methods are the functions in the code that do stuff. Methods are similar to properties and operators; they are a pre-existing functionality that you can use in your code. But unlike properties, methods don't simply reveal information. They take action. The syntax for a method is as follows: a ., the name of the method (like toLowerCase or replace), and parentheses (). Methods can do many things, like make a change, perform a calculation, or produce a side effect like printing something to the console. When you use methods, it's possible to modify and manipulate the information you're calling it on.

Numbers

The number data type in JavaScript is used to represent numbers. Big surprise, right? Numbers represent integer values, which are whole numbers like 1, 2, 3, 74,883, and so forth, and floating-point decimal numbers, which are numbers like 1.234999. Numbers with decimals are sometimes just called floats.

parseFloat()

The parseFloat() method is used for converting strings that have fractional parts or decimals, like 3.14 and -0.89.

Coercion

The process of automatic conversion is called coercion, which means that the number was coerced into a string. If you combine a number with a string using the + operator, the resulting value will be a string.

Else block

The statement or block of code following the "else" keyword. You'll regularly build backup plans into your code. In other words, you'll often need the code to do one thing when given certain conditions, and you'll need it to do something else if the conditions are different. In JavaScript, you can add a backup plan with the else statement. let userLoggedInToday = false; if (userLoggedInToday) { // this code will not run! console.log("Thanks for logging in today!"); } else { // this code will run console.log("Don't forget to log in today!"); } As you can see, the if and else blocks run in opposite situations here. The code in the else block runs only if the if block is skipped, which happens if userLoggedInToday is false. But the code in the else block will be skipped when the if block runs, which occurs if userLoggedInToday is true.

Undefined

The undefined data type is a special value that, in a way, means exactly that—that a variable was never defined. An undefined value, means that the value was left empty, simply because nothing was ever assigned to it. let magicWord; magicWord; // Undefined

single or double quotes for strings?

There is no difference, the only rule is that you can't mix and match the string types for the beginning and ending - for example (let var = 'test") would be incorrect. You can use double or single quotes within a string, you just have to use the opposite to wrap the string. let var = "You Ain't Good For Me".

Array Method push()

This adds an item to the end of an array. It returns the new length of the array. let myFavoriteFruits = ["banana", "cherry", "mango"]; myFavoriteFruits.push("pear"); console.log(myFavoriteFruits); myFavoriteFruits.push("banana"); console.log(myFavoriteFruits); [ 'banana', 'cherry', 'mango', 'pear' ] [ 'banana', 'cherry', 'mango', 'pear', 'banana' ]

= means?

This is assignment not equality // Assignment (one equal sign) let currentForecast = "sunny"; // Equality comparison (three equal signs) if (currentForecast === "rain") { let recommendation = "Bring your umbrella! ☔"; }

Increment Operator

This operator adds one to the number currently stored in the variable. The code step++ is the same as step+=1, and thus we can also use step+=2to increment the variable by two, or even step+=10 to increment the variable by ten.

Array Method pop()

This removes the last item from the end of an array. It returns the last item. let myFavoriteFruits = ["banana", "cherry", "mango", "pear"]; myFavoriteFruits.pop(); //-> removes last item from the list [ 'banana', 'cherry', 'mango' ]

trim() method does what?

This removes whitespace (spaces, tabs, and so forth) at the beginning and end of a string. Ex.) let stringWithWhitespace = " It's so roomy in here "; console.log(stringWithWhitespace.trim());

Concatenation of Strings

To put two or more strings together, grouping items together in a chain or series. Example concatenation: let currentHour = "3"; let currentMinutes = "15"; let currentSeconds = "47"; let oClock = currentHour + "o'Clock"; //-> "3o'Clock" let oClockPretty = currentHour + " o'Clock"; //-> "3 o'Clock" let hoursMinutes = currentHour + currentMinutes; //-> "315" let formattedHoursMinutes = currentHour + ":" + currentMinutes; //-> "3:15" let formattedHoursMinutesSeconds = currentHour + ":" + currentMinutes + ":" + currentSeconds; // "3:15:47" let timeIsMessage = "The time is:"; console.log(formattedHoursMinutesSeconds); console.log(timeIsMessage + formattedHoursMinutes); //-> "The time is:3:15" console.log(timeIsMessage + " " + formattedHoursMinutes); //-> "The time is: 3:15" console.log(timeIsMessage + " " + formattedHoursMinutesSeconds);

Converting Numbers to Strings

To turn a number into a string. You did this above using the + operator, and you can always try that approach. You can also use the toString() as an option, which turns a number into a string.

Relational Operators

Used to compare two values. Operators include =,<,>,<=,>=,<> // Greater than: `>` 7 > 4; // true 2 > 10; // false 100 > 100; // false // Less than: `<` 7 < 4; // false 2 < 10; // true 100 < 100; // false // Greater than or equal to: `>=` 7 >= 4; // true 2 >= 10; // false 100 >= 100; // true // Less than or equal to: `<=` 7 <= 4; // false 2 <= 10; // true 100 <= 100; // true // Not equal: `!==` (opposite of `===`) 7 !== 4; // true 2 !== 10; // true 100 !== 100; // false

Does the original array change?

When you learned about the string methods replace(), trim(), toUpperCase(), and toLowerCase(), you discovered that the original string doesn't change when you use these methods. the technical term that means "to change the original" is to mutate. The string methods you learned about will not mutate a string. But of the array methods you've explored so far, push() and pop() will mutate an array, but length will not.

Using bracket notation with variables

When you use bracket notation to access a property, you are allowed to use any string—including a variable or an expression. let myFamily = { mom: "Cynthia", dad: "Paul", } myFamily.mom; // "Cynthia" myFamily["mom"]; // "Cynthia" let parent = "mom"; myFamily[parent]; // "Cynthia" // Also allowed, though pretty silly! myFamily["m" + "o" + "m"]; // "Cynthia" You can put any expression inside the brackets! JavaScript will turn whatever is in between the [ and ] into a key, and give you back the corresponding value.

Checking values

With the boolean data type, it just has true and false. You can get these booleans as the results of operations that check something. It can make the if a much more robust tool. At its most basic level, a check allows you to find the answer to a question in your code. You can set it up to reveal the boolean true or false based on the answer. Here are a few different kinds of checks that you can do: Is this equal to that? Is this larger (or smaller) than that? Is this a multiple of that? Does this string have that string inside it? But these are just the basics. Imagine creating checks that are more useful! Is the password long enough? Is the user signed in? Is that email address already in use? Is the photo small enough for a profile picture?

Pseudocoding

Write code to solve large problems, you'll find that it's easy to get lost in the complexity of the process. A great remedy for this issue is to pseudocode your solution. pseudocoding simply refers to writing a comment that describes what each piece of your code will do. For example, imagine you were given the challenge below. "Write code that will take a collection of numbers, multiply each number by itself, then add up all the results." As you can see, the pseudocode essentially creates a scaffold for your real code. With these comments in place, it'll be easier for you to build the code incrementally and consider every element of the challenge, piece by piece. You can focus on just one task at a time instead of trying to solve everything all at once.

Getting Items From Arrays

You access an item in an array using bracket notation and the index of that item, which is that item's slot number. To do this, you use square brackets with the index inside, like [2]. This is easy to remember because you also create arrays with those square brackets []. Arrays are zero indexed. That means that the numbering system starts at zero, not one. So if you want to retrieve the first item in an array, you must ask for the item in position 0. let listOfPuppies = ["shadow", "mocha", "ranger"]; listOfPuppies[0]; // 'shadow' listOfPuppies[1]; // 'mocha' listOfPuppies[2]; // 'ranger'

Multiple Arguments in Functions

You can define multiple functions by: const introduce = (name,age) => { } introduce("Ken the Ninja",14);(

!! two "not" operators

You can force any value to be an actual true or false by using two "not" operators (!!). This "double bang" turns anything to a boolean. !!true // true !!false // false !!10 // true !!0 // false !!(-8) // true !!"hello" // true !!"" // false !!" " // true !!undefined // false !!NaN // false !!null // false

Functions Returning values

You can use the keyword return, as shown below, to make your function produce an output. function add(num1, num2) { return num1 + num2; } The return keyword tells JavaScript to send the value back to the place where you called the function. Whenever JavaScript sees return in a function, it does the following: Stops running the code in that function Takes the value to the right of return Swaps in the return value where the function was called Many built-in functions return a value. For example, you can use the value that parseInt() returns: let number = parseInt("9"); // `number` gets the return value from `parseInt()` If you forget to use return (or decide not to return anything), the function will return a value of undefined. Keep that in mind in case you see undefined pop up somewhere!

Defining a Function

You can write: const introduce = function (parameter){ }; OR const introduce = (parameter) => { }; The ES6 introduced arrow functions, they don't require any other changes besides replacing the function with a () => You call it by stating introduce(value);

typeof

built-in operator that JavaScript provides to reveal the data type of a particular value: console.log(typeof 2); // Number console.log(typeof "2"); // String console.log(typeof true); // Boolean

console.log() vs. return

console.log() shows you a value, you can use it to demonstrate what's happening in your code. But in real-world applications, it actually isn't very common for console.log() to make it into the "real" code. return keyword is different—it's how functions usually work. when you return a value from a function, the return value fills in the spot where the function was called. Developers use console.log() while they're developing, to debug or to see the intermediate values while they're working. But when they're finished, they usually remove the console.log() statements to tidy up after themselves. So in most of the functions that you'll write, you'll use return instead of console.log().

toLowerCase() method does what?

converts a string to lowercase letters. This returns a string with all the letters lowercase. let sentence = "this sentence is not Capitalized CorrectlY."; console.log(sentence.toLowerCase()); or let lowerCased = sentence.toLowerCase();

toUpperCase() method does what?

converts a string to uppercase letters. This returns a string with all the letters capitalized. Ex.) let sentence = "shout"; console.log(sentence.toUpperCase()); or let uppercaseSentence = sentence.toUpperCase();

|| (or)

evaluates to true if either one of the values is true. // or (Does either side evaluate to `true`?) true || true; // returns true true || false; // returns true false || false; // returns false

The anatomy of a for loop

for (initialExpression; condition; incrementExpression) { loop body } initialExpression: This expression typically initializes the loop counter. It runs at the start of a loop. A very common example is let i = 0. The i variable is short for index, and it's frequently used for the step counter that you saw above. condition: At the end of each loop, the condition expression is evaluated. In the example above, the condition is "if step is less than or equal to the countTo variable." If the value of the condition is true, the loop statement executes. If the value of the condition is false, the loop statement terminates. In the example above, step would eventually get to 6. At that point, because the value would be greater than 5, the loop would stop. incrementExpression: At the end of each loop, this statement is executed. In the example above, the code is incrementing the variable step by one (++) each time through the loop. But it's important to note that you're not limited to incrementing by one for the final condition. Depending on what you're building or the problem you're solving, you can decrement (i--) by some amount, or you could increment by another amount, like 2 (step += 2). That said, incrementing by one is the most common technique. loop body: If the condition is true, this code will run. In the example above, the loop body that executes uses console.log to display the value of step during the loop.

For Loop Explained

for (variable definition; condition; variable update){ code inside }

Function Syntax

function bakeCake() { console.log('Getting ingredients...'); console.log('Mixing ingredients...'); console.log('Putting in the oven...'); console.log('Cake is complete!'); } To call a function: bakeCake(); What you see above is a function declaration. It's code that makes a function called bakeCake(). Take a closer look at the syntax. Notice the following: It starts with the keyword function. It gives the function the name bakeCake. It has empty parentheses (). You'll learn more about these later. It has curly braces { and }. Between the curly braces is some code (a bunch of console.log() statements). The code between the curly braces is called the body of the function. It's what the function will do. Creating the function doesn't run the code inside—it stores it for later. You can think of this as similar to writing down a recipe to cook later.

Ex.) of PEMDAS CODE

if (!5 - 4 > 2 === 2 * 10 / 5 === 4) { console.log("the expression was truthy") } else { console.log("it was falsy"); } it was falsy console.log(!5) // false console.log(!5 - 4) // -4 console.log(4 > 2) // true console.log(5 - 4 > 2) // false console.log(4 > 2 === 2)// false console.log(2 * 10 / 5) // 4 console.log(2 * 10 / 5 === 4)// true

toString()

let age = 101; let ageString = age.toString(); console.log(typeof age) // 'number' console.log(typeof ageString) // 'string' // Age is just a number—until you use `toString()`!

variables are case sensitive

let coding = "fun"; let Coding = "mysterious"; (the computer reads this code and treats these two variables as completely separate items)

Editing an existing key-value pair

let myFamily = { mom: "Cynthia", dad: "Paul", }; myFamily.mom = "Linda; // Dot notation myFamily["dad"] = "John"; // Bracket notation let myFamily = { mom: "Linda", dad: John", };

Array Method length

let myFavoriteFruits = ["banana", "cherry", "mango", "pear"]; console.log(myFavoriteFruits.length); //-> prints array length, 4 Just like the string tool length, this gives the length of the array—in other words, the number of items. You'll notice that length doesn't need parentheses. That's because it's technically a property and not a method.

Creating an Array

let myFavoriteFruits = ["banana", "cherry", "mango"]; // an array of strings let myLuckyNumbers = [4, 8, 15, 16, 23, 42]; // an array of numbers let emptyArray = myFavoriteFruits + myLuckyNumbers; // an empty array

Objects in arrays

let partyPeople = [ { name: "Joe", attending: false }, { name: "Jasmine", attending: true }, { name: "Julio", attending: false }, { name: "Julia", attending: true }, ];

Loop array example "Array object + likes to party"

let partyPeople = ["Joe", "Julie", "Jasmine", "Julio"]; for (let i = 0; i < partyPeople.length; i++) { console.log(partyPeople[i] + " likes to party!"); } The length of the array is used in the condition. In this case, the condition is "if i is less than the number of things in the partyPeople array." The counter starts at 0. The code accesses the array at a different slot each time that it steps through the loop.

variables

let sentence = "this is a sentence, a string data type set to the variable called sentence"

Example of Coercion

let x = "42" + 7; let y = "42" - 7; console.log(x); -> 427 console.log(y); -> 35

parseInt()

parses a string and returns an integer. parseInt returns only integers, like -5, 0, 111, 22,847, and so on. It doesn't deal with decimals, like 1.618.

replace() method does what?

searches for a regexp or substring and replaces it with a new string. This replaces part of a string with another string. Ex.) let sentence = "this sentence is not Capitalized CorrectlY."; console.log(sentence.replace("this", "This")); let capitalized = lowerCased.replace("this", "This"); let corrected = capitalized.replace("not ", ""); console.log(corrected);

Decrement Operator

which looks like this: step--. Perhaps not surprisingly, the decrement subtracts one from the number currently stored in the variable.

Manipulating Array Data

you can change what's stored in each numbered slot. If you want to change an array, you use access and assign. let dogAges = [6, 9, 10]; dogAges[0]; // 6 dogAges[0] = 7; // happy birthday to the first dog! dogAges[0]; // 7 You can even use this technique to assign values to slots in the array that weren't holding any information to begin with. let dogAges = [6, 9, 10]; dogAges[3] = 5; // a fourth dog, five years old dogAges; // [6, 9, 10, 5]

Truth and coercion

you used the + operator to add together a string and a number. In that situation, JavaScript converted the number to a string and combined the strings into one. If you write an if statement with an item that isn't a boolean, JavaScript will behave in a similar way. Specifically, it will convert your data into true or false. let weather = "sunny"; if (weather) { console.log("There is weather outside"); }


Kaugnay na mga set ng pag-aaral

Chapter 19: Infectious Diseases Affecting the Respiratory System

View Set

Fine Arts Survey A - Basic Techniques (Topic Test #2)

View Set

Micro ch 4-5 test (test questions)

View Set

Materials Chapter 13 Review Questions

View Set

HIST. 201 - Chapter 15: "What Is Freedom?": Reconstruction (1865 - 1877) Multiple Choice/Review Questions

View Set

Public Speaking Final Chapter 15

View Set

Local Anesthetics Evolve Quizzes

View Set

Disasters Lec 8 Atmosphere and Severe Weather

View Set