Basic_Javascript Flashcards
What are four FAQs about JavaScript?

What is Javascript?
One of the most popular and widely used programming language in the world right now.
It’s growing faster than any other programming languages.

What large companies are building full applications around JavaScript right now?
Nextflix, Walmart and Paypal
Entire applications around Javascript
What is an average salary for a JavaScript developer?
You can work as:
Front End (React, Angular)
Backend (Node.js)
Full Stack (MEAN)

What can you do with Javascript?
We can build many things now.
mobile/web apps
networking apps / chats / video streaming / games

What was JavaScript originally designed for doing?
For a long time, Javascript was used only for building front end interactive web browsers.
But those days are long gone!
Thanks to huge community support and investment and support by Google, Facebook Javascript has changed.
Where was JavaScript originally designed to run?
Javascript was originally designed to run only in browsers.
Every browser has a JavaScript engine:
FireFox: SpiderMonkey
Chrome: v8
Where does Javascript code run?
Browser:
JavaScript Engine
Node:
C++ w/ JavaScript Engine
Both:
Javascript can be run in the browser using the built-in Javascript engine or in Node!

What happened in 2009?
Ryan Daal
Took the open-source Javascript engine in chrome and embedded it into a C++ program.
Called it Node.js
What is node?
Node is a C++ program that includes Google’s V8 Javascript engine.
Now we can run Javascript outside of a browser.
We can pass our code to Node for execution.
What is ECMA script?
ECMA script is just a specification
ECMA is responsible for defining standards
annual release of a specification
ES2015/ES6 defined many new features
What is the difference between ECMAScript and JavaScript?
JavaScript is a programming language that adheres to the standards provided in ECMAScript.

What can we do in Chrome Developer Tools?
Run JavaScript.
Every browser has a JavaScript engine

What is a good IDE for JavaScript?
Visual Studio code - lightweight IDE

What else should we install?
Node - technically don’t need node to run JavaScript but we use node for installing third-party libraries.
It’s good to have node on your machine!

What does ! Tab generate in Visual Studio Code?
Boiler plate HTML

What is the Live Server extension?
A lightweight local server we can use to run JavaScript

What does run with Live Server do?
It opens our browser and allows us to run our applications!

What is best practice for where to put the script section in our HTML page?
The best practice is to put the script at the end of the body section after all existing elements.

What do we want to explain with our comments?
Why’s
How’s

What is a statement?
A piece of code that expresses an action to be carried out
Why is it best practice to put the script after all the elements in the body section?
- The browser parses HTML file top to bottom - if script is in the head, Browser might get busy executing Javascript code and not be able to render elements on-page.
- JavaScript often acts on the elements - If the script is at the end we can be confident all elements have been rendered by the browser. Sometimes third party code requires being placed in the head (this is exception).
What’s a shortcut to bring the browser developer tools?
Option + Command + i

What is separation of concerns?
Separate HTML (content) from Javascript (behavior)
You don’t want to write it in line with HTML.
What is the difference between HTML and JavaScript?
HTML is all about content
JavaScript is all about behavior
- How should your webpage behave?
- What should happen when we hover over an element? Something pops up, something hidden?
How do we execute JavaScript code in node?
Open the terminal
call node filename.js

What is the Integrated Terminal in Visual Studio?
Can run JavaScript using node without explicitly opening our terminal.

What do we use variables for doing?
Storing data temporarily in a computer’s memory
Name of variable - label on data
How do we declare a variable?
Use the “let” keyword

What are variables by default in Javascript?
undefined
How can we declare a string in Javascript?
use single quotes

What are the rules for naming variables?
Use camelCase
Rules:
Cannot be keywords
Use meaningful names
Cannot start with a number
Cannot contain a space or hyphen
variables are case sensitive
declare each variable on a new line

How do we declare a constant in JavaScript?
use the “const” keyword
use it as default choice

What are the two types in JavaScript?
Primitive (Value) Types
Reference Types

What are the primitive (value) types in JavaScript?
String
Number
Boolean
undefined
null

What separates Javascript from other languages?
It’s a dynamic language
What is the difference between a static and dynamic language?
Static:
Declare a variable, the type is set, cannot be changed
Dynamic:
Type can change in runtime

What is a dynamic language?
Type of variable can change at runtime!

How do we clear the console in our browser?
Control + L
What are all numbers in Javascript?
Type number
integer, floating-point, etc. are all type number
What type is null?

Type object

What are the reference types in JavaScript?
Objects
Arrays
Functions

What is an object?
Related variables grouped together
Keys = Properties
What is the object literal syntax?
Curly braces

How can we access an object property?
Dot notation (one way)
default choice

What is bracket notation?
In Javascript, an object is a key-value pair
to access the value can use bracket notation
object [target property] -> value at target displayed
What is the second way to access an object’s members?
Bracket Notation
Pass a string that determines the name of the property
Use this for unknown selection

What are arrays in JavaScript?
A data structure used to represent a list of items
Dynamic
Objects and sizes are dynamic
Can store different types in arrays
Can add/remove items
Arrays in JavaScript are Objects

What are one of the fundamental building blocks in JavaScript?
Functions!

What kind of operators do we have in JavaScript?

What is an expression?

Operations + variables + constants are used to create expressions
expressions are used to create algorithms
Something that produces a value
What type of arithmetic operators do we have in JavaScript?

How does the increment operator work?

How does the decrement operator work?
–x (decrement first, then assign)
x– (assign, then decrement)
How can we use the assignment operator to increment the value by more than one?

What are comparison operators?
returns a boolean

===
(three equal signs)
equality
What is the strict equality operator?
Ensures both operands are of the same type and value
If the two operands are not of equal type
returns false
More precise and accurate

What are lose equality operators?
Converts both operands to the same type
Checks the value only

What is the ternary operator (conditional operator)?
Start with the condition
if evaluate true, use first value
if false, use the second value

What are logical operators?
Operators used to make decisions based on multiple conditions
&& - returns true if BOTH operands are true
|| - returns TRUE if ONE of the operands is true
! - reverses the boolean

What can we use logical operators to do in JavaScript?
Can use logical operators with non-boolean values!
Extremely powerful
How does JavaScript engine interpret non-boolean values in logical operations?
falsy or truthy
What values are falsy?
undefined
null
0
false (boolean)
’ ‘ (empty string)
NaN
How does JavaScript engine evaluate non-boolean logical operands?
If the value is falsy, treats it as a false
if the value is !falsy, treats it as true
runs normal && ! or || operations
What values are truthy?
not falsy (below)
undefined
null
0
false (boolean)
’ ‘ (empty string)
NaN
What is short-circuiting?
JavaScript will stop evaluation
once a truthy value is found
Ex.
false || 1 || 2
returns 1 (truthy)
doesn’t evaluate 2
What is the result of this expression?

OR operator returns true because ‘1’ is truthy
ternary operator executes first statement “hello”

What does using the logical OR operator between non-booleans allow us to do?
Provide default values
If user selects color, use it
otherwise, provide default color
value is returned

What type of conditional statements do we have in JavaScript?

What is the syntax for if-else statements in JavaScript?

How can we simplify our if-else statement?
Remove curly braces if single statement

What are switch statements?

What does mosh say about switch statements?
Outdated, look a bit ugly
Comes down to personal preference
he uses if-else statements
less noise in the code
What do loops allow us to do?
repeat an action a number of times

What kind of loops do we have in JavaScript?
Subtle differences in how they start/end
basically do the same thing

What is the syntax for a for loop?

What is a difference between a while loop and a for loop?
loop variable is declared externally
For loop, the “ i “ is part of the syntax
while loop, declare “ i “ outside the loop
What is the syntax for a while loop?
first, the condition is evaluated
if true, statements are executed
if false, loop is terminated

What is a do-while loop?
Realistically, not used often
first, evaluates the expression
then, checks the condition

What do we use the for-in and for-of loops?
Iterate over the properties in an object or array

How do we iterate the individual properties in an object?
for…in loop
Use bracket notation to access object properties
bracket notation if the value is calculated at run time

What is the syntax to display properties in an object using a for-in loop?
Must access properties with bracket notation
pass key as the name of the target property

What do we use a for-in loop to do?
iterate over the properties of an object

What is the for-of loop?
ECMASCRIPT 6 released
ideal for iterating over elements in arrays!

What are break and continue keywords?

keywords that change how loop behaves
1. break - causes javascript engine to jump out of a loop (terminate)
2. continue - causes javascript engine to jump to the beginning of the loop (restarts the loop)

Write a function that takes two numbers and returns the max of the two
(Hint: If else)


How can we make this code cleaner?
(Hint: ternary operator aka conditional operator)


What is very amateurish and ugly about this code?

no need to explicitly return true / false with ternary operator

Write code to solve the FizzBuzz algorithm?
(Hint: popular interview question)

Write a function that checks the speed of a driver
Hint:
speedLimit = 70
every 5 km over speedLimit earns user 1 point
if user gets 12 points, license suspended
test a function with different values

How can we make this code cleaner?

Use the return keyword

remove the else block
Write a function that takes a number and counts down displaying the number and whether it is “even” or “odd”.


How do we clean up this code?
(Hint: conditional operator (ternary operator))


Write code to count the number of truthy values in an array
(Hint: for..of loop)

Write code to show the properties of an object if property is a string
(Hint: for in loop, typeof)

Write a function that adds the multiples of 3 and 5 together between any number
(Hint: for loop)

What are objects in javaScript?
Collections of key, value pairs
highly related variables grouped together
variables
nested objects
functions (that act on variables)

What is OOP?
A style of programming
A collection of objects that talk to eachother to perform some functionality

What’s the problem with object literal syntax?

As our applications get large, not best approach
to create a second object, have to repeat code
Soln?
factory functions / constructor function

In modern javascript, how can we make this code cleaner?

- Variables and arguments - if key and value are the same (argument and obj. variable)
can omit the value
Ex. radius: radius vs. radius
- method syntax - instead of defining as a key value pair, can define like a function without function keyword
Ex. draw: function () {} vs. draw() { }

Why are factory functions a good way to create objects?
Allow us to reduce code duplication
if there is a bug, can fix in one place

What is the naming convention for constructor functions?
NOT camelCase (oneTwoThreeFour)
PascalNotation (OneTwoThreeFour)

What are our objects in javascript?

Dynamic
Can always add additional properties and methods!
can always remove properties and methods

What three things happen when we use the ‘new’ operator?
First, creates an empty object
Then, sets ‘this’ to point to object
Finally, returns object

What is the key difference between factory functions and constructor functions?

Factory functions - call a function that returns a new object, camelNotation
Constructor functions - uses new operator, uses ‘this’ operation, PascalNotation
developers familiar with C or Java prefer constructor functions
Why?
Looks similar to syntax

What are functions in JavaScript?
Objects!
Confusing

What two types of variables do we have in JavaScript?
primitives and objects

What must we know about primitives vs. objects in regards to copying?
primatives are copied by value (independent of one another)
objects are copied by their reference (objects, functions, arrays)
value inside a function is independent of another primative outside of scope
Ex. local parameter inside a function will point to object

How can we iterate an object to get all the methods or variables?
(Hint: Objects are not iterable by nature)

Use Object.keys - returns an keys as a string array
can iterate array, using for of loop
Use Object.entries ( ) - returns entries as a string array

How can we enumerate an object and copy all properties into a new object?
(Hint: Object.assign())

Modern JavaScript has Object.assign() method

What is a third way to clone an object in JavaScript
(Hint: Spread Operator)

How is garbage collection handled in JavaScript?
memory is automatically allocated to object
when done using, don’t have to re-allocate
JavaScript engine has a garbage collection
that will automatically look for variables that are no longer used
we have no control over this
based on a complex algorithm
runs in the background
What is the Math object?

Built in object in JavaScript
if you need to use mathemtical calculations in your applications, refer back to this object

How many kinds of strings do we have in JavaScript?
Two Kinds:
- String Primitive - JavaScript will wrap string into a string object if using dot operator
- String Object - uses constructor function and the ‘new’ keyword

What are some of the String methods?
(Hint: look at String documentation)
.length() - gives length of string

.includes()
.startsWith()
.indexOf()
.replace()
.toUpperCase()
.trim()
What is escape notation?
(Hint: Strings)


What are template literals?
(Hint: ` ` )
Help us write cleaner code
How?
Using a different character to define string (back tick character)
applications?
Sending emails in applications
Why?
Can format exactly as we want

What are the benefits of template literals?
(Hint: back ticks vs. quotes for strings?)
- Write cleaner code - don’t need escape characters for quotes or formatting, can write strings exactly as you want them displayed without extra noise
- Add dynamic fields - use ${ field } as a placeholder to insert a field dynamically!

What are Date ( ) objects in JavaScript?

What are some Date ( ) object methods?
.setFullYear ( ) - sets a year
.toDateString() - returns a date string
.toTimeString() - returns time component of date object
.toISOString( ) - standard ISO format, used in web/mobile apps, to transfer dates

How do we create an object that has street, city, zipcode fields and a function that displays the contents of the object?
(Hint: factory function, constructor function, for in loop)

How can we create an address object?
(Hint: factory method, constructor method, literal method)

How do we check if two objects are equal?
Hint: areEqual( ), areSame ( )
Cannot use ’===’
why?
Objects are reference type
JavaScript will check if these two objects have same reference

How can we create a blog object?
(Hint: object literal syntax)
comments field - is an array of objects

How do we create a blog object?
(Hint: constructor function method)

Use objects to create the price filter in yelp.
(Hint: array of price objects)

When looking at a concept:
Imagine, what properties would you put inside an object?
The more you practice this, easier it becomes

What are we going to learn in the Arrays section?
These concepts are extremely important

esp. when starting out!
Make sure to finish the excercises in this section!
How do we add elements to the beginning, end or index in an array?
(Hint: push, unshift, splice)

How do we find primitives in an array?
(Hint: indexOf, includes, lastIndexOf)

How to we locate a reference type in an array?
(Hint: find method)
Why?
includes method checks references for equality not objects
How?
Pass a predicate to .find (function that takes one argument)
specify a criteria for search in function

What are arrow functions?

Cleaner ways of passing a callback argument
pass a callback argument without annonymous classes
How?
use =>
( ) if no paraments
single line, remove curly braces
put on same line

How do we empty the contents in an array?
(Hint: reassign, set .length to zero, splice, pop)

How do we combine or slice arrays?
(Hint: concat, slice)

How can we use a forreach loop in JavaScript?
(Hint: .forEach)


How can we split and join arrays?
(Hint:.split, .join)

How do we sort an array of reference type objects?
(Hint: .sort(function))

How can we sort number array’s in JavaScript?
(Hint: primitive arrays, .sort(), .reverse())
Works on primitives - numbers, strings, etc.
DOES NOT work on reference types (Objects, Functions)

How can we test every element in an array?
.every( Predicate ) checks if every element matches a certain criteria
Ex. allPositive?

How can we test for at least one element that matches our criteria in an array?
.some(predicate)
These are new methods in JavaScript (.every ( ) .some ( ) ) - older browser’s don’t support these yet!

How can we filter an array of primitive values?
(hint: .filter(function))

How could we create a yelp filter for restaurants that are currently open?
(Hint: filter array of objects by criteria)
array of restaurants, filter based on open hours

How do we map an each number value in an array to an a cooresponding array of objects?
(Hint: .map(function))

Very useful when building real world applications!

Both .filter( ) and .map( ) return a new array!
Don’t modify original array!
These methods are chainable (can call after another in chain)
How can we use chaining for filtering and mapping arrays?
(Hint: chaining)

the power of chaining these methods!

How can we reduce an array?
(Hint: .reduce((reductionResultVariable,
reduce method (arrays) -
can reduce all elements into a single value (number, string, object, anything)

How can we create a function that converts a number range into an array of numbers based on that range?
(Hint: for loop)

How can we write the .includes ( ) function that tests each element in an array for matching a value?
(Hint:.some (lambda function))

How can we write a function that returns an array without a specific set of values present in an input array?
(Hint: for of loop, .includes( ) )
returns a new array that excludes a value from input array

How can we write an algorithm that moves items in an array?
(Hint:.splice(start, delete, value))
.splice(start, delete, add)
cut the element out of the index
paste the element into the offset index
return output

How do we write code to countOccurences of a number in an array?
(Hint: for of loop, .reduce ( ) )


How can we get the max occuring value in an array?
(Hint: reduce array to a single value)
.reduce ( )
By default, accumulator will be set to first value in array (if don’t pass init value)
Why?
Want to find largest value, reducing array into a single value

How can we write code to display the name property only of movies that are in 2018 with a rating higher than 4?
(Hint: array of objects, .filter, .map)

get all moves in 2018, rating > 4, sort in desc order (high rating first)
pick only title property, display on console

What is the key difference between function declarations and function expressions?

we can call function declaration before it’s defined!
we cannot call a function expression before it’s defined!
Why?
Hosting - moving function declarations automatically to top of file by JavaScript

Why can we call a function declaration before it’s declaration?

Popular JavaScript interview question!!
Hosting
JavaScript engine automatically moves function declarations to top of file

What should we remember about hoisting?
(Hint: scope, declarations, assignments)

What is unique about a function’s arguments in JavaScript?
(Hint: dynamic)

Can pass more arguments or less arguments

How can we write code to allow varying numbers of arguments in our JavaScript functions?
(Hint: arguments object)
iterate the arguments object
What is the arguments object?
used to work with a function that has a varying number of arguments passed
BUT!
ES6 offers rest operator!

What is the rest operator?
(hint: (…args) )

ES6 for varying number of args
puts the args in an array
elegant and professional
less code (no looping)

What can we not have after the rest parameter?

Another parameter!
can have zero or more parameters before rest!
Rest parameter has to be the last parameter!

How do we give a function default values?
(Hint: OR operator vs. ES6)

parameter with default value must be last
Cannot have a parameter without a default value following

How can we write code for getters and setters in JavaScript?

only read only!

How can we use defensive programming in JavaScript?
(Hint: throw an Error ( ) and catch it)

What is the scope of ‘const’ variables in JavaScript?
Scope of constant is limited to the code block it is defined
cannot access const outside function, for loop, if loop it is defined

What is the var keyword?
(Hint: how does it differ from let?)
scope of var is not limited to the block defined
var => function scope variable
it’s limited to the function it’s defined!
ES6 (ES2015) introduced - let and const
let, const => block scope variables

What is the problem with declaring variables using the “var” keyword in JavaScript?
(Hint: window object)
It attaches the variable to the window object (browser object)
if using a 3rd party library with same variable name, can override your variable

What does the .this keyword refer to in JavaScript?
(Hint: part of obj or not?)


How can we write code to flatten an array passed in the spread operator?
(Hint: varying args -> spread operator -> puts all into an array)
If passing an array to the spread operator,
will encapsulate into an array
creating a nested array
must flatten, to sum

How do we write code to calculate the area of a circle?
(Hint: getter function)

How can we write code to validate an input and throw an error?
(Hint: throw an error, try/catch block)

What are the next steps?
(Hint: JavaScript Object Oriented Programming)
Why?
A lot of developers write JavaScript applications without properly understanding the inner workings of JavaScript.
They keep “trying” things until it works out.
Don’t be one of these!
Get a solid foundation of the inner workings of JavaScript
It’s an immense help to your career